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 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
67                        bool AllowTemplates=false)
68       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
69         AllowClassTemplates(AllowTemplates) {
70     WantExpressionKeywords = false;
71     WantCXXNamedCasts = false;
72     WantRemainingKeywords = false;
73   }
74 
75   bool ValidateCandidate(const TypoCorrection &candidate) override {
76     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
77       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
78       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
79       return (IsType || AllowedTemplate) &&
80              (AllowInvalidDecl || !ND->isInvalidDecl());
81     }
82     return !WantClassName && candidate.isKeyword();
83   }
84 
85  private:
86   bool AllowInvalidDecl;
87   bool WantClassName;
88   bool AllowClassTemplates;
89 };
90 
91 }
92 
93 /// \brief Determine whether the token kind starts a simple-type-specifier.
94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
95   switch (Kind) {
96   // FIXME: Take into account the current language when deciding whether a
97   // token kind is a valid type specifier
98   case tok::kw_short:
99   case tok::kw_long:
100   case tok::kw___int64:
101   case tok::kw___int128:
102   case tok::kw_signed:
103   case tok::kw_unsigned:
104   case tok::kw_void:
105   case tok::kw_char:
106   case tok::kw_int:
107   case tok::kw_half:
108   case tok::kw_float:
109   case tok::kw_double:
110   case tok::kw_wchar_t:
111   case tok::kw_bool:
112   case tok::kw___underlying_type:
113   case tok::kw___auto_type:
114     return true;
115 
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123 
124   default:
125     break;
126   }
127 
128   return false;
129 }
130 
131 namespace {
132 enum class UnqualifiedTypeNameLookupResult {
133   NotFound,
134   FoundNonType,
135   FoundType
136 };
137 } // namespace
138 
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
140 /// dependent class.
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145                                 SourceLocation NameLoc,
146                                 const CXXRecordDecl *RD) {
147   if (!RD->hasDefinition())
148     return UnqualifiedTypeNameLookupResult::NotFound;
149   // Look for type decls in base classes.
150   UnqualifiedTypeNameLookupResult FoundTypeDecl =
151       UnqualifiedTypeNameLookupResult::NotFound;
152   for (const auto &Base : RD->bases()) {
153     const CXXRecordDecl *BaseRD = nullptr;
154     if (auto *BaseTT = Base.getType()->getAs<TagType>())
155       BaseRD = BaseTT->getAsCXXRecordDecl();
156     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157       // Look for type decls in dependent base classes that have known primary
158       // templates.
159       if (!TST || !TST->isDependentType())
160         continue;
161       auto *TD = TST->getTemplateName().getAsTemplateDecl();
162       if (!TD)
163         continue;
164       auto *BasePrimaryTemplate =
165           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166       if (!BasePrimaryTemplate)
167         continue;
168       BaseRD = BasePrimaryTemplate;
169     }
170     if (BaseRD) {
171       for (NamedDecl *ND : BaseRD->lookup(&II)) {
172         if (!isa<TypeDecl>(ND))
173           return UnqualifiedTypeNameLookupResult::FoundNonType;
174         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
175       }
176       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178         case UnqualifiedTypeNameLookupResult::FoundNonType:
179           return UnqualifiedTypeNameLookupResult::FoundNonType;
180         case UnqualifiedTypeNameLookupResult::FoundType:
181           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
182           break;
183         case UnqualifiedTypeNameLookupResult::NotFound:
184           break;
185         }
186       }
187     }
188   }
189 
190   return FoundTypeDecl;
191 }
192 
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194                                                       const IdentifierInfo &II,
195                                                       SourceLocation NameLoc) {
196   // Lookup in the parent class template context, if any.
197   const CXXRecordDecl *RD = nullptr;
198   UnqualifiedTypeNameLookupResult FoundTypeDecl =
199       UnqualifiedTypeNameLookupResult::NotFound;
200   for (DeclContext *DC = S.CurContext;
201        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202        DC = DC->getParent()) {
203     // Look for type decls in dependent base classes that have known primary
204     // templates.
205     RD = dyn_cast<CXXRecordDecl>(DC);
206     if (RD && RD->getDescribedClassTemplate())
207       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
208   }
209   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
210     return ParsedType();
211 
212   // We found some types in dependent base classes.  Recover as if the user
213   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
214   // lookup during template instantiation.
215   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
216 
217   ASTContext &Context = S.Context;
218   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219                                           cast<Type>(Context.getRecordType(RD)));
220   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
221 
222   CXXScopeSpec SS;
223   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
224 
225   TypeLocBuilder Builder;
226   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227   DepTL.setNameLoc(NameLoc);
228   DepTL.setElaboratedKeywordLoc(SourceLocation());
229   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
231 }
232 
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
235 ///
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242                              Scope *S, CXXScopeSpec *SS,
243                              bool isClassName, bool HasTrailingDot,
244                              ParsedType ObjectTypePtr,
245                              bool IsCtorOrDtorName,
246                              bool WantNontrivialTypeSourceInfo,
247                              IdentifierInfo **CorrectedII) {
248   // Determine where we will perform name lookup.
249   DeclContext *LookupCtx = nullptr;
250   if (ObjectTypePtr) {
251     QualType ObjectType = ObjectTypePtr.get();
252     if (ObjectType->isRecordType())
253       LookupCtx = computeDeclContext(ObjectType);
254   } else if (SS && SS->isNotEmpty()) {
255     LookupCtx = computeDeclContext(*SS, false);
256 
257     if (!LookupCtx) {
258       if (isDependentScopeSpecifier(*SS)) {
259         // C++ [temp.res]p3:
260         //   A qualified-id that refers to a type and in which the
261         //   nested-name-specifier depends on a template-parameter (14.6.2)
262         //   shall be prefixed by the keyword typename to indicate that the
263         //   qualified-id denotes a type, forming an
264         //   elaborated-type-specifier (7.1.5.3).
265         //
266         // We therefore do not perform any name lookup if the result would
267         // refer to a member of an unknown specialization.
268         if (!isClassName && !IsCtorOrDtorName)
269           return ParsedType();
270 
271         // We know from the grammar that this name refers to a type,
272         // so build a dependent node to describe the type.
273         if (WantNontrivialTypeSourceInfo)
274           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
275 
276         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
278                                        II, NameLoc);
279         return ParsedType::make(T);
280       }
281 
282       return ParsedType();
283     }
284 
285     if (!LookupCtx->isDependentContext() &&
286         RequireCompleteDeclContext(*SS, LookupCtx))
287       return ParsedType();
288   }
289 
290   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291   // lookup for class-names.
292   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
293                                       LookupOrdinaryName;
294   LookupResult Result(*this, &II, NameLoc, Kind);
295   if (LookupCtx) {
296     // Perform "qualified" name lookup into the declaration context we
297     // computed, which is either the type of the base of a member access
298     // expression or the declaration context associated with a prior
299     // nested-name-specifier.
300     LookupQualifiedName(Result, LookupCtx);
301 
302     if (ObjectTypePtr && Result.empty()) {
303       // C++ [basic.lookup.classref]p3:
304       //   If the unqualified-id is ~type-name, the type-name is looked up
305       //   in the context of the entire postfix-expression. If the type T of
306       //   the object expression is of a class type C, the type-name is also
307       //   looked up in the scope of class C. At least one of the lookups shall
308       //   find a name that refers to (possibly cv-qualified) T.
309       LookupName(Result, S);
310     }
311   } else {
312     // Perform unqualified name lookup.
313     LookupName(Result, S);
314 
315     // For unqualified lookup in a class template in MSVC mode, look into
316     // dependent base classes where the primary class template is known.
317     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318       if (ParsedType TypeInBase =
319               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
320         return TypeInBase;
321     }
322   }
323 
324   NamedDecl *IIDecl = nullptr;
325   switch (Result.getResultKind()) {
326   case LookupResult::NotFound:
327   case LookupResult::NotFoundInCurrentInstantiation:
328     if (CorrectedII) {
329       TypoCorrection Correction = CorrectTypo(
330           Result.getLookupNameInfo(), Kind, S, SS,
331           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
332           CTK_ErrorRecovery);
333       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
334       TemplateTy Template;
335       bool MemberOfUnknownSpecialization;
336       UnqualifiedId TemplateName;
337       TemplateName.setIdentifier(NewII, NameLoc);
338       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339       CXXScopeSpec NewSS, *NewSSPtr = SS;
340       if (SS && NNS) {
341         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
342         NewSSPtr = &NewSS;
343       }
344       if (Correction && (NNS || NewII != &II) &&
345           // Ignore a correction to a template type as the to-be-corrected
346           // identifier is not a template (typo correction for template names
347           // is handled elsewhere).
348           !(getLangOpts().CPlusPlus && NewSSPtr &&
349             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350                            false, Template, MemberOfUnknownSpecialization))) {
351         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352                                     isClassName, HasTrailingDot, ObjectTypePtr,
353                                     IsCtorOrDtorName,
354                                     WantNontrivialTypeSourceInfo);
355         if (Ty) {
356           diagnoseTypo(Correction,
357                        PDiag(diag::err_unknown_type_or_class_name_suggest)
358                          << Result.getLookupName() << isClassName);
359           if (SS && NNS)
360             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361           *CorrectedII = NewII;
362           return Ty;
363         }
364       }
365     }
366     // If typo correction failed or was not performed, fall through
367   case LookupResult::FoundOverloaded:
368   case LookupResult::FoundUnresolvedValue:
369     Result.suppressDiagnostics();
370     return ParsedType();
371 
372   case LookupResult::Ambiguous:
373     // Recover from type-hiding ambiguities by hiding the type.  We'll
374     // do the lookup again when looking for an object, and we can
375     // diagnose the error then.  If we don't do this, then the error
376     // about hiding the type will be immediately followed by an error
377     // that only makes sense if the identifier was treated like a type.
378     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379       Result.suppressDiagnostics();
380       return ParsedType();
381     }
382 
383     // Look to see if we have a type anywhere in the list of results.
384     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385          Res != ResEnd; ++Res) {
386       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
387         if (!IIDecl ||
388             (*Res)->getLocation().getRawEncoding() <
389               IIDecl->getLocation().getRawEncoding())
390           IIDecl = *Res;
391       }
392     }
393 
394     if (!IIDecl) {
395       // None of the entities we found is a type, so there is no way
396       // to even assume that the result is a type. In this case, don't
397       // complain about the ambiguity. The parser will either try to
398       // perform this lookup again (e.g., as an object name), which
399       // will produce the ambiguity, or will complain that it expected
400       // a type name.
401       Result.suppressDiagnostics();
402       return ParsedType();
403     }
404 
405     // We found a type within the ambiguous lookup; diagnose the
406     // ambiguity and then return that type. This might be the right
407     // answer, or it might not be, but it suppresses any attempt to
408     // perform the name lookup again.
409     break;
410 
411   case LookupResult::Found:
412     IIDecl = Result.getFoundDecl();
413     break;
414   }
415 
416   assert(IIDecl && "Didn't find decl");
417 
418   QualType T;
419   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420     DiagnoseUseOfDecl(IIDecl, NameLoc);
421 
422     T = Context.getTypeDeclType(TD);
423     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
424 
425     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426     // constructor or destructor name (in such a case, the scope specifier
427     // will be attached to the enclosing Expr or Decl node).
428     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429       if (WantNontrivialTypeSourceInfo) {
430         // Construct a type with type-source information.
431         TypeLocBuilder Builder;
432         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
433 
434         T = getElaboratedType(ETK_None, *SS, T);
435         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436         ElabTL.setElaboratedKeywordLoc(SourceLocation());
437         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
439       } else {
440         T = getElaboratedType(ETK_None, *SS, T);
441       }
442     }
443   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
445     if (!HasTrailingDot)
446       T = Context.getObjCInterfaceType(IDecl);
447   }
448 
449   if (T.isNull()) {
450     // If it's not plausibly a type, suppress diagnostics.
451     Result.suppressDiagnostics();
452     return ParsedType();
453   }
454   return ParsedType::make(T);
455 }
456 
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460   for (;; DC = DC->getLookupParent()) {
461     DC = DC->getPrimaryContext();
462     auto *ND = dyn_cast<NamespaceDecl>(DC);
463     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464       return NestedNameSpecifier::Create(Context, nullptr, ND);
465     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467                                          RD->getTypeForDecl());
468     else if (isa<TranslationUnitDecl>(DC))
469       return NestedNameSpecifier::GlobalSpecifier(Context);
470   }
471   llvm_unreachable("something isn't in TU scope?");
472 }
473 
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475                                                 SourceLocation NameLoc) {
476   // Accepting an undeclared identifier as a default argument for a template
477   // type parameter is a Microsoft extension.
478   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
479 
480   // Build a fake DependentNameType that will perform lookup into CurContext at
481   // instantiation time.  The name specifier isn't dependent, so template
482   // instantiation won't transform it.  It will retry the lookup, however.
483   NestedNameSpecifier *NNS =
484       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
486 
487   // Build type location information.  We synthesized the qualifier, so we have
488   // to build a fake NestedNameSpecifierLoc.
489   NestedNameSpecifierLocBuilder NNSLocBuilder;
490   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
492 
493   TypeLocBuilder Builder;
494   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495   DepTL.setNameLoc(NameLoc);
496   DepTL.setElaboratedKeywordLoc(SourceLocation());
497   DepTL.setQualifierLoc(QualifierLoc);
498   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
499 }
500 
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo").  If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507   // Do a tag name lookup in this scope.
508   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509   LookupName(R, S, false);
510   R.suppressDiagnostics();
511   if (R.getResultKind() == LookupResult::Found)
512     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513       switch (TD->getTagKind()) {
514       case TTK_Struct: return DeclSpec::TST_struct;
515       case TTK_Interface: return DeclSpec::TST_interface;
516       case TTK_Union:  return DeclSpec::TST_union;
517       case TTK_Class:  return DeclSpec::TST_class;
518       case TTK_Enum:   return DeclSpec::TST_enum;
519       }
520     }
521 
522   return DeclSpec::TST_unspecified;
523 }
524 
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
529 /// @code
530 /// template<class T> class A {
531 /// public:
532 ///   typedef int TYPE;
533 /// };
534 /// template<class T> class B : public A<T> {
535 /// public:
536 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
537 /// };
538 /// @endcode
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540   if (CurContext->isRecord()) {
541     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
542       return true;
543 
544     const Type *Ty = SS->getScopeRep()->getAsType();
545 
546     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547     for (const auto &Base : RD->bases())
548       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
549         return true;
550     return S->isFunctionPrototypeScope();
551   }
552   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
553 }
554 
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556                                    SourceLocation IILoc,
557                                    Scope *S,
558                                    CXXScopeSpec *SS,
559                                    ParsedType &SuggestedType,
560                                    bool AllowClassTemplates) {
561   // We don't have anything to suggest (yet).
562   SuggestedType = ParsedType();
563 
564   // There may have been a typo in the name of the type. Look up typo
565   // results, in case we have something that we can suggest.
566   if (TypoCorrection Corrected =
567           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568                       llvm::make_unique<TypeNameValidatorCCC>(
569                           false, false, AllowClassTemplates),
570                       CTK_ErrorRecovery)) {
571     if (Corrected.isKeyword()) {
572       // We corrected to a keyword.
573       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574       II = Corrected.getCorrectionAsIdentifierInfo();
575     } else {
576       // We found a similarly-named type or interface; suggest that.
577       if (!SS || !SS->isSet()) {
578         diagnoseTypo(Corrected,
579                      PDiag(diag::err_unknown_typename_suggest) << II);
580       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583                                 II->getName().equals(CorrectedStr);
584         diagnoseTypo(Corrected,
585                      PDiag(diag::err_unknown_nested_typename_suggest)
586                        << II << DC << DroppedSpecifier << SS->getRange());
587       } else {
588         llvm_unreachable("could not have corrected a typo here");
589       }
590 
591       CXXScopeSpec tmpSS;
592       if (Corrected.getCorrectionSpecifier())
593         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
594                           SourceRange(IILoc));
595       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
597                                   false, ParsedType(),
598                                   /*IsCtorOrDtorName=*/false,
599                                   /*NonTrivialTypeSourceInfo=*/true);
600     }
601     return;
602   }
603 
604   if (getLangOpts().CPlusPlus) {
605     // See if II is a class template that the user forgot to pass arguments to.
606     UnqualifiedId Name;
607     Name.setIdentifier(II, IILoc);
608     CXXScopeSpec EmptySS;
609     TemplateTy TemplateResult;
610     bool MemberOfUnknownSpecialization;
611     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612                        Name, ParsedType(), true, TemplateResult,
613                        MemberOfUnknownSpecialization) == TNK_Type_template) {
614       TemplateName TplName = TemplateResult.get();
615       Diag(IILoc, diag::err_template_missing_args) << TplName;
616       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618           << TplDecl->getTemplateParameters()->getSourceRange();
619       }
620       return;
621     }
622   }
623 
624   // FIXME: Should we move the logic that tries to recover from a missing tag
625   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
626 
627   if (!SS || (!SS->isSet() && !SS->isInvalid()))
628     Diag(IILoc, diag::err_unknown_typename) << II;
629   else if (DeclContext *DC = computeDeclContext(*SS, false))
630     Diag(IILoc, diag::err_typename_nested_not_found)
631       << II << DC << SS->getRange();
632   else if (isDependentScopeSpecifier(*SS)) {
633     unsigned DiagID = diag::err_typename_missing;
634     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635       DiagID = diag::ext_typename_missing;
636 
637     Diag(SS->getRange().getBegin(), DiagID)
638       << SS->getScopeRep() << II->getName()
639       << SourceRange(SS->getRange().getBegin(), IILoc)
640       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641     SuggestedType = ActOnTypenameType(S, SourceLocation(),
642                                       *SS, *II, IILoc).get();
643   } else {
644     assert(SS && SS->isInvalid() &&
645            "Invalid scope specifier has already been diagnosed");
646   }
647 }
648 
649 /// \brief Determine whether the given result set contains either a type name
650 /// or
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653                        NextToken.is(tok::less);
654 
655   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
657       return true;
658 
659     if (CheckTemplate && isa<TemplateDecl>(*I))
660       return true;
661   }
662 
663   return false;
664 }
665 
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667                                     Scope *S, CXXScopeSpec &SS,
668                                     IdentifierInfo *&Name,
669                                     SourceLocation NameLoc) {
670   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671   SemaRef.LookupParsedName(R, S, &SS);
672   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673     StringRef FixItTagName;
674     switch (Tag->getTagKind()) {
675       case TTK_Class:
676         FixItTagName = "class ";
677         break;
678 
679       case TTK_Enum:
680         FixItTagName = "enum ";
681         break;
682 
683       case TTK_Struct:
684         FixItTagName = "struct ";
685         break;
686 
687       case TTK_Interface:
688         FixItTagName = "__interface ";
689         break;
690 
691       case TTK_Union:
692         FixItTagName = "union ";
693         break;
694     }
695 
696     StringRef TagName = FixItTagName.drop_back();
697     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
700 
701     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
702          I != IEnd; ++I)
703       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
704         << Name << TagName;
705 
706     // Replace lookup results with just the tag decl.
707     Result.clear(Sema::LookupTagName);
708     SemaRef.LookupParsedName(Result, S, &SS);
709     return true;
710   }
711 
712   return false;
713 }
714 
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717                                   QualType T, SourceLocation NameLoc) {
718   ASTContext &Context = S.Context;
719 
720   TypeLocBuilder Builder;
721   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
722 
723   T = S.getElaboratedType(ETK_None, SS, T);
724   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725   ElabTL.setElaboratedKeywordLoc(SourceLocation());
726   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
728 }
729 
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732                    SourceLocation NameLoc, const Token &NextToken,
733                    bool IsAddressOfOperand,
734                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
735   DeclarationNameInfo NameInfo(Name, NameLoc);
736   ObjCMethodDecl *CurMethod = getCurMethodDecl();
737 
738   if (NextToken.is(tok::coloncolon)) {
739     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740                                 QualType(), false, SS, nullptr, false);
741   }
742 
743   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744   LookupParsedName(Result, S, &SS, !CurMethod);
745 
746   // For unqualified lookup in a class template in MSVC mode, look into
747   // dependent base classes where the primary class template is known.
748   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749     if (ParsedType TypeInBase =
750             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
751       return TypeInBase;
752   }
753 
754   // Perform lookup for Objective-C instance variables (including automatically
755   // synthesized instance variables), if we're in an Objective-C method.
756   // FIXME: This lookup really, really needs to be folded in to the normal
757   // unqualified lookup mechanism.
758   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760     if (E.get() || E.isInvalid())
761       return E;
762   }
763 
764   bool SecondTry = false;
765   bool IsFilteredTemplateName = false;
766 
767 Corrected:
768   switch (Result.getResultKind()) {
769   case LookupResult::NotFound:
770     // If an unqualified-id is followed by a '(', then we have a function
771     // call.
772     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773       // In C++, this is an ADL-only call.
774       // FIXME: Reference?
775       if (getLangOpts().CPlusPlus)
776         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
777 
778       // C90 6.3.2.2:
779       //   If the expression that precedes the parenthesized argument list in a
780       //   function call consists solely of an identifier, and if no
781       //   declaration is visible for this identifier, the identifier is
782       //   implicitly declared exactly as if, in the innermost block containing
783       //   the function call, the declaration
784       //
785       //     extern int identifier ();
786       //
787       //   appeared.
788       //
789       // We also allow this in C99 as an extension.
790       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
791         Result.addDecl(D);
792         Result.resolveKind();
793         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
794       }
795     }
796 
797     // In C, we first see whether there is a tag type by the same name, in
798     // which case it's likely that the user just forget to write "enum",
799     // "struct", or "union".
800     if (!getLangOpts().CPlusPlus && !SecondTry &&
801         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
802       break;
803     }
804 
805     // Perform typo correction to determine if there is another name that is
806     // close to this name.
807     if (!SecondTry && CCC) {
808       SecondTry = true;
809       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810                                                  Result.getLookupKind(), S,
811                                                  &SS, std::move(CCC),
812                                                  CTK_ErrorRecovery)) {
813         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814         unsigned QualifiedDiag = diag::err_no_member_suggest;
815 
816         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817         NamedDecl *UnderlyingFirstDecl
818           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821           UnqualifiedDiag = diag::err_no_template_suggest;
822           QualifiedDiag = diag::err_no_member_template_suggest;
823         } else if (UnderlyingFirstDecl &&
824                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829         }
830 
831         if (SS.isEmpty()) {
832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833         } else {// FIXME: is this even reachable? Test it.
834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836                                   Name->getName().equals(CorrectedStr);
837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838                                     << Name << computeDeclContext(SS, false)
839                                     << DroppedSpecifier << SS.getRange());
840         }
841 
842         // Update the name, so that the caller has the new name.
843         Name = Corrected.getCorrectionAsIdentifierInfo();
844 
845         // Typo correction corrected to a keyword.
846         if (Corrected.isKeyword())
847           return Name;
848 
849         // Also update the LookupResult...
850         // FIXME: This should probably go away at some point
851         Result.clear();
852         Result.setLookupName(Corrected.getCorrection());
853         if (FirstDecl)
854           Result.addDecl(FirstDecl);
855 
856         // If we found an Objective-C instance variable, let
857         // LookupInObjCMethod build the appropriate expression to
858         // reference the ivar.
859         // FIXME: This is a gross hack.
860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861           Result.clear();
862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863           return E;
864         }
865 
866         goto Corrected;
867       }
868     }
869 
870     // We failed to correct; just fall through and let the parser deal with it.
871     Result.suppressDiagnostics();
872     return NameClassification::Unknown();
873 
874   case LookupResult::NotFoundInCurrentInstantiation: {
875     // We performed name lookup into the current instantiation, and there were
876     // dependent bases, so we treat this result the same way as any other
877     // dependent nested-name-specifier.
878 
879     // C++ [temp.res]p2:
880     //   A name used in a template declaration or definition and that is
881     //   dependent on a template-parameter is assumed not to name a type
882     //   unless the applicable name lookup finds a type name or the name is
883     //   qualified by the keyword typename.
884     //
885     // FIXME: If the next token is '<', we might want to ask the parser to
886     // perform some heroics to see if we actually have a
887     // template-argument-list, which would indicate a missing 'template'
888     // keyword here.
889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890                                       NameInfo, IsAddressOfOperand,
891                                       /*TemplateArgs=*/nullptr);
892   }
893 
894   case LookupResult::Found:
895   case LookupResult::FoundOverloaded:
896   case LookupResult::FoundUnresolvedValue:
897     break;
898 
899   case LookupResult::Ambiguous:
900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901         hasAnyAcceptableTemplateNames(Result)) {
902       // C++ [temp.local]p3:
903       //   A lookup that finds an injected-class-name (10.2) can result in an
904       //   ambiguity in certain cases (for example, if it is found in more than
905       //   one base class). If all of the injected-class-names that are found
906       //   refer to specializations of the same class template, and if the name
907       //   is followed by a template-argument-list, the reference refers to the
908       //   class template itself and not a specialization thereof, and is not
909       //   ambiguous.
910       //
911       // This filtering can make an ambiguous result into an unambiguous one,
912       // so try again after filtering out template names.
913       FilterAcceptableTemplateNames(Result);
914       if (!Result.isAmbiguous()) {
915         IsFilteredTemplateName = true;
916         break;
917       }
918     }
919 
920     // Diagnose the ambiguity and return an error.
921     return NameClassification::Error();
922   }
923 
924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926     // C++ [temp.names]p3:
927     //   After name lookup (3.4) finds that a name is a template-name or that
928     //   an operator-function-id or a literal- operator-id refers to a set of
929     //   overloaded functions any member of which is a function template if
930     //   this is followed by a <, the < is always taken as the delimiter of a
931     //   template-argument-list and never as the less-than operator.
932     if (!IsFilteredTemplateName)
933       FilterAcceptableTemplateNames(Result);
934 
935     if (!Result.empty()) {
936       bool IsFunctionTemplate;
937       bool IsVarTemplate;
938       TemplateName Template;
939       if (Result.end() - Result.begin() > 1) {
940         IsFunctionTemplate = true;
941         Template = Context.getOverloadedTemplateName(Result.begin(),
942                                                      Result.end());
943       } else {
944         TemplateDecl *TD
945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947         IsVarTemplate = isa<VarTemplateDecl>(TD);
948 
949         if (SS.isSet() && !SS.isInvalid())
950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951                                                     /*TemplateKeyword=*/false,
952                                                       TD);
953         else
954           Template = TemplateName(TD);
955       }
956 
957       if (IsFunctionTemplate) {
958         // Function templates always go through overload resolution, at which
959         // point we'll perform the various checks (e.g., accessibility) we need
960         // to based on which function we selected.
961         Result.suppressDiagnostics();
962 
963         return NameClassification::FunctionTemplate(Template);
964       }
965 
966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
967                            : NameClassification::TypeTemplate(Template);
968     }
969   }
970 
971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973     DiagnoseUseOfDecl(Type, NameLoc);
974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980 
981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982   if (!Class) {
983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
984     if (ObjCCompatibleAliasDecl *Alias =
985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986       Class = Alias->getClassInterface();
987   }
988 
989   if (Class) {
990     DiagnoseUseOfDecl(Class, NameLoc);
991 
992     if (NextToken.is(tok::period)) {
993       // Interface. <something> is parsed as a property reference expression.
994       // Just return "unknown" as a fall-through for now.
995       Result.suppressDiagnostics();
996       return NameClassification::Unknown();
997     }
998 
999     QualType T = Context.getObjCInterfaceType(Class);
1000     return ParsedType::make(T);
1001   }
1002 
1003   // We can have a type template here if we're classifying a template argument.
1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005     return NameClassification::TypeTemplate(
1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 
1008   // Check for a tag type hidden by a non-type decl in a few cases where it
1009   // seems likely a type is wanted instead of the non-type that was found.
1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011   if ((NextToken.is(tok::identifier) ||
1012        (NextIsOp &&
1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     QualType T = Context.getTypeDeclType(Type);
1018     if (SS.isNotEmpty())
1019       return buildNestedType(*this, SS, T, NameLoc);
1020     return ParsedType::make(T);
1021   }
1022 
1023   if (FirstDecl->isCXXClassMember())
1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025                                            nullptr, S);
1026 
1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028   return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030 
1031 // Determines the context to return to after temporarily entering a
1032 // context.  This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 
1036   // Functions defined inline within classes aren't parsed until we've
1037   // finished parsing the top-level class, so the top-level class is
1038   // the context we'll need to return to.
1039   // A Lambda call operator whose parent is a class must not be treated
1040   // as an inline member function.  A Lambda can be used legally
1041   // either as an in-class member initializer or a default argument.  These
1042   // are parsed once the class has been marked complete and so the containing
1043   // context would be the nested class (when the lambda is defined in one);
1044   // If the class is not complete, then the lambda is being used in an
1045   // ill-formed fashion (such as to specify the width of a bit-field, or
1046   // in an array-bound) - in which case we still want to return the
1047   // lexically containing DC (which could be a nested class).
1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049     DC = DC->getLexicalParent();
1050 
1051     // A function not defined within a class will always return to its
1052     // lexical context.
1053     if (!isa<CXXRecordDecl>(DC))
1054       return DC;
1055 
1056     // A C++ inline method/friend is parsed *after* the topmost class
1057     // it was declared in is fully parsed ("complete");  the topmost
1058     // class is the context we need to return to.
1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060       DC = RD;
1061 
1062     // Return the declaration context of the topmost class the inline method is
1063     // declared in.
1064     return DC;
1065   }
1066 
1067   return DC->getLexicalParent();
1068 }
1069 
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071   assert(getContainingDC(DC) == CurContext &&
1072       "The next DeclContext should be lexically contained in the current one.");
1073   CurContext = DC;
1074   S->setEntity(DC);
1075 }
1076 
1077 void Sema::PopDeclContext() {
1078   assert(CurContext && "DeclContext imbalance!");
1079 
1080   CurContext = getContainingDC(CurContext);
1081   assert(CurContext && "Popped translation unit!");
1082 }
1083 
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085                                                                     Decl *D) {
1086   // Unlike PushDeclContext, the context to which we return is not necessarily
1087   // the containing DC of TD, because the new context will be some pre-existing
1088   // TagDecl definition instead of a fresh one.
1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090   CurContext = cast<TagDecl>(D)->getDefinition();
1091   assert(CurContext && "skipping definition of undefined tag");
1092   // Start lookups from the parent of the current context; we don't want to look
1093   // into the pre-existing complete definition.
1094   S->setEntity(CurContext->getLookupParent());
1095   return Result;
1096 }
1097 
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099   CurContext = static_cast<decltype(CurContext)>(Context);
1100 }
1101 
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1104 ///
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106   // C++0x [basic.lookup.unqual]p13:
1107   //   A name used in the definition of a static data member of class
1108   //   X (after the qualified-id of the static member) is looked up as
1109   //   if the name was used in a member function of X.
1110   // C++0x [basic.lookup.unqual]p14:
1111   //   If a variable member of a namespace is defined outside of the
1112   //   scope of its namespace then any name used in the definition of
1113   //   the variable member (after the declarator-id) is looked up as
1114   //   if the definition of the variable member occurred in its
1115   //   namespace.
1116   // Both of these imply that we should push a scope whose context
1117   // is the semantic context of the declaration.  We can't use
1118   // PushDeclContext here because that context is not necessarily
1119   // lexically contained in the current context.  Fortunately,
1120   // the containing scope should have the appropriate information.
1121 
1122   assert(!S->getEntity() && "scope already has entity");
1123 
1124 #ifndef NDEBUG
1125   Scope *Ancestor = S->getParent();
1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1128 #endif
1129 
1130   CurContext = DC;
1131   S->setEntity(DC);
1132 }
1133 
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135   assert(S->getEntity() == CurContext && "Context imbalance!");
1136 
1137   // Switch back to the lexical context.  The safety of this is
1138   // enforced by an assert in EnterDeclaratorContext.
1139   Scope *Ancestor = S->getParent();
1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141   CurContext = Ancestor->getEntity();
1142 
1143   // We don't need to do anything with the scope, which is going to
1144   // disappear.
1145 }
1146 
1147 
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 
1173 void Sema::ActOnExitFunctionContext() {
1174   // Same implementation as PopDeclContext, but returns to the lexical parent,
1175   // rather than the top-level class.
1176   assert(CurContext && "DeclContext imbalance!");
1177   CurContext = CurContext->getLexicalParent();
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180 
1181 
1182 /// \brief Determine whether we allow overloading of the function
1183 /// PrevDecl with another declaration.
1184 ///
1185 /// This routine determines whether overloading is possible, not
1186 /// whether some new function is actually an overload. It will return
1187 /// true in C++ (where we can always provide overloads) or, as an
1188 /// extension, in C when the previous function is already an
1189 /// overloaded function declaration or has the "overloadable"
1190 /// attribute.
1191 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1192                                        ASTContext &Context) {
1193   if (Context.getLangOpts().CPlusPlus)
1194     return true;
1195 
1196   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1197     return true;
1198 
1199   return (Previous.getResultKind() == LookupResult::Found
1200           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1201 }
1202 
1203 /// Add this decl to the scope shadowed decl chains.
1204 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1205   // Move up the scope chain until we find the nearest enclosing
1206   // non-transparent context. The declaration will be introduced into this
1207   // scope.
1208   while (S->getEntity() && S->getEntity()->isTransparentContext())
1209     S = S->getParent();
1210 
1211   // Add scoped declarations into their context, so that they can be
1212   // found later. Declarations without a context won't be inserted
1213   // into any context.
1214   if (AddToContext)
1215     CurContext->addDecl(D);
1216 
1217   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1218   // are function-local declarations.
1219   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1220       !D->getDeclContext()->getRedeclContext()->Equals(
1221         D->getLexicalDeclContext()->getRedeclContext()) &&
1222       !D->getLexicalDeclContext()->isFunctionOrMethod())
1223     return;
1224 
1225   // Template instantiations should also not be pushed into scope.
1226   if (isa<FunctionDecl>(D) &&
1227       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1228     return;
1229 
1230   // If this replaces anything in the current scope,
1231   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1232                                IEnd = IdResolver.end();
1233   for (; I != IEnd; ++I) {
1234     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1235       S->RemoveDecl(*I);
1236       IdResolver.RemoveDecl(*I);
1237 
1238       // Should only need to replace one decl.
1239       break;
1240     }
1241   }
1242 
1243   S->AddDecl(D);
1244 
1245   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1246     // Implicitly-generated labels may end up getting generated in an order that
1247     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1248     // the label at the appropriate place in the identifier chain.
1249     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1250       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1251       if (IDC == CurContext) {
1252         if (!S->isDeclScope(*I))
1253           continue;
1254       } else if (IDC->Encloses(CurContext))
1255         break;
1256     }
1257 
1258     IdResolver.InsertDeclAfter(I, D);
1259   } else {
1260     IdResolver.AddDecl(D);
1261   }
1262 }
1263 
1264 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1265   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1266     TUScope->AddDecl(D);
1267 }
1268 
1269 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1270                          bool AllowInlineNamespace) {
1271   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1272 }
1273 
1274 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1275   DeclContext *TargetDC = DC->getPrimaryContext();
1276   do {
1277     if (DeclContext *ScopeDC = S->getEntity())
1278       if (ScopeDC->getPrimaryContext() == TargetDC)
1279         return S;
1280   } while ((S = S->getParent()));
1281 
1282   return nullptr;
1283 }
1284 
1285 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1286                                             DeclContext*,
1287                                             ASTContext&);
1288 
1289 /// Filters out lookup results that don't fall within the given scope
1290 /// as determined by isDeclInScope.
1291 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1292                                 bool ConsiderLinkage,
1293                                 bool AllowInlineNamespace) {
1294   LookupResult::Filter F = R.makeFilter();
1295   while (F.hasNext()) {
1296     NamedDecl *D = F.next();
1297 
1298     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1299       continue;
1300 
1301     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1302       continue;
1303 
1304     F.erase();
1305   }
1306 
1307   F.done();
1308 }
1309 
1310 static bool isUsingDecl(NamedDecl *D) {
1311   return isa<UsingShadowDecl>(D) ||
1312          isa<UnresolvedUsingTypenameDecl>(D) ||
1313          isa<UnresolvedUsingValueDecl>(D);
1314 }
1315 
1316 /// Removes using shadow declarations from the lookup results.
1317 static void RemoveUsingDecls(LookupResult &R) {
1318   LookupResult::Filter F = R.makeFilter();
1319   while (F.hasNext())
1320     if (isUsingDecl(F.next()))
1321       F.erase();
1322 
1323   F.done();
1324 }
1325 
1326 /// \brief Check for this common pattern:
1327 /// @code
1328 /// class S {
1329 ///   S(const S&); // DO NOT IMPLEMENT
1330 ///   void operator=(const S&); // DO NOT IMPLEMENT
1331 /// };
1332 /// @endcode
1333 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1334   // FIXME: Should check for private access too but access is set after we get
1335   // the decl here.
1336   if (D->doesThisDeclarationHaveABody())
1337     return false;
1338 
1339   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1340     return CD->isCopyConstructor();
1341   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1342     return Method->isCopyAssignmentOperator();
1343   return false;
1344 }
1345 
1346 // We need this to handle
1347 //
1348 // typedef struct {
1349 //   void *foo() { return 0; }
1350 // } A;
1351 //
1352 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1353 // for example. If 'A', foo will have external linkage. If we have '*A',
1354 // foo will have no linkage. Since we can't know until we get to the end
1355 // of the typedef, this function finds out if D might have non-external linkage.
1356 // Callers should verify at the end of the TU if it D has external linkage or
1357 // not.
1358 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1359   const DeclContext *DC = D->getDeclContext();
1360   while (!DC->isTranslationUnit()) {
1361     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1362       if (!RD->hasNameForLinkage())
1363         return true;
1364     }
1365     DC = DC->getParent();
1366   }
1367 
1368   return !D->isExternallyVisible();
1369 }
1370 
1371 // FIXME: This needs to be refactored; some other isInMainFile users want
1372 // these semantics.
1373 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1374   if (S.TUKind != TU_Complete)
1375     return false;
1376   return S.SourceMgr.isInMainFile(Loc);
1377 }
1378 
1379 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1380   assert(D);
1381 
1382   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1383     return false;
1384 
1385   // Ignore all entities declared within templates, and out-of-line definitions
1386   // of members of class templates.
1387   if (D->getDeclContext()->isDependentContext() ||
1388       D->getLexicalDeclContext()->isDependentContext())
1389     return false;
1390 
1391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1392     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1393       return false;
1394 
1395     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1396       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1397         return false;
1398     } else {
1399       // 'static inline' functions are defined in headers; don't warn.
1400       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1401         return false;
1402     }
1403 
1404     if (FD->doesThisDeclarationHaveABody() &&
1405         Context.DeclMustBeEmitted(FD))
1406       return false;
1407   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1408     // Constants and utility variables are defined in headers with internal
1409     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1410     // like "inline".)
1411     if (!isMainFileLoc(*this, VD->getLocation()))
1412       return false;
1413 
1414     if (Context.DeclMustBeEmitted(VD))
1415       return false;
1416 
1417     if (VD->isStaticDataMember() &&
1418         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1419       return false;
1420   } else {
1421     return false;
1422   }
1423 
1424   // Only warn for unused decls internal to the translation unit.
1425   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1426   // for inline functions defined in the main source file, for instance.
1427   return mightHaveNonExternalLinkage(D);
1428 }
1429 
1430 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1431   if (!D)
1432     return;
1433 
1434   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1435     const FunctionDecl *First = FD->getFirstDecl();
1436     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1437       return; // First should already be in the vector.
1438   }
1439 
1440   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1441     const VarDecl *First = VD->getFirstDecl();
1442     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1443       return; // First should already be in the vector.
1444   }
1445 
1446   if (ShouldWarnIfUnusedFileScopedDecl(D))
1447     UnusedFileScopedDecls.push_back(D);
1448 }
1449 
1450 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1451   if (D->isInvalidDecl())
1452     return false;
1453 
1454   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1455       D->hasAttr<ObjCPreciseLifetimeAttr>())
1456     return false;
1457 
1458   if (isa<LabelDecl>(D))
1459     return true;
1460 
1461   // Except for labels, we only care about unused decls that are local to
1462   // functions.
1463   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1464   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1465     // For dependent types, the diagnostic is deferred.
1466     WithinFunction =
1467         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1468   if (!WithinFunction)
1469     return false;
1470 
1471   if (isa<TypedefNameDecl>(D))
1472     return true;
1473 
1474   // White-list anything that isn't a local variable.
1475   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1476     return false;
1477 
1478   // Types of valid local variables should be complete, so this should succeed.
1479   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1480 
1481     // White-list anything with an __attribute__((unused)) type.
1482     QualType Ty = VD->getType();
1483 
1484     // Only look at the outermost level of typedef.
1485     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1486       if (TT->getDecl()->hasAttr<UnusedAttr>())
1487         return false;
1488     }
1489 
1490     // If we failed to complete the type for some reason, or if the type is
1491     // dependent, don't diagnose the variable.
1492     if (Ty->isIncompleteType() || Ty->isDependentType())
1493       return false;
1494 
1495     if (const TagType *TT = Ty->getAs<TagType>()) {
1496       const TagDecl *Tag = TT->getDecl();
1497       if (Tag->hasAttr<UnusedAttr>())
1498         return false;
1499 
1500       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1501         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1502           return false;
1503 
1504         if (const Expr *Init = VD->getInit()) {
1505           if (const ExprWithCleanups *Cleanups =
1506                   dyn_cast<ExprWithCleanups>(Init))
1507             Init = Cleanups->getSubExpr();
1508           const CXXConstructExpr *Construct =
1509             dyn_cast<CXXConstructExpr>(Init);
1510           if (Construct && !Construct->isElidable()) {
1511             CXXConstructorDecl *CD = Construct->getConstructor();
1512             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1513               return false;
1514           }
1515         }
1516       }
1517     }
1518 
1519     // TODO: __attribute__((unused)) templates?
1520   }
1521 
1522   return true;
1523 }
1524 
1525 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1526                                      FixItHint &Hint) {
1527   if (isa<LabelDecl>(D)) {
1528     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1529                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1530     if (AfterColon.isInvalid())
1531       return;
1532     Hint = FixItHint::CreateRemoval(CharSourceRange::
1533                                     getCharRange(D->getLocStart(), AfterColon));
1534   }
1535   return;
1536 }
1537 
1538 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1539   if (D->getTypeForDecl()->isDependentType())
1540     return;
1541 
1542   for (auto *TmpD : D->decls()) {
1543     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1544       DiagnoseUnusedDecl(T);
1545     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1546       DiagnoseUnusedNestedTypedefs(R);
1547   }
1548 }
1549 
1550 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1551 /// unless they are marked attr(unused).
1552 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1553   if (!ShouldDiagnoseUnusedDecl(D))
1554     return;
1555 
1556   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1557     // typedefs can be referenced later on, so the diagnostics are emitted
1558     // at end-of-translation-unit.
1559     UnusedLocalTypedefNameCandidates.insert(TD);
1560     return;
1561   }
1562 
1563   FixItHint Hint;
1564   GenerateFixForUnusedDecl(D, Context, Hint);
1565 
1566   unsigned DiagID;
1567   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1568     DiagID = diag::warn_unused_exception_param;
1569   else if (isa<LabelDecl>(D))
1570     DiagID = diag::warn_unused_label;
1571   else
1572     DiagID = diag::warn_unused_variable;
1573 
1574   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1575 }
1576 
1577 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1578   // Verify that we have no forward references left.  If so, there was a goto
1579   // or address of a label taken, but no definition of it.  Label fwd
1580   // definitions are indicated with a null substmt which is also not a resolved
1581   // MS inline assembly label name.
1582   bool Diagnose = false;
1583   if (L->isMSAsmLabel())
1584     Diagnose = !L->isResolvedMSAsmLabel();
1585   else
1586     Diagnose = L->getStmt() == nullptr;
1587   if (Diagnose)
1588     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1589 }
1590 
1591 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1592   S->mergeNRVOIntoParent();
1593 
1594   if (S->decl_empty()) return;
1595   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1596          "Scope shouldn't contain decls!");
1597 
1598   for (auto *TmpD : S->decls()) {
1599     assert(TmpD && "This decl didn't get pushed??");
1600 
1601     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1602     NamedDecl *D = cast<NamedDecl>(TmpD);
1603 
1604     if (!D->getDeclName()) continue;
1605 
1606     // Diagnose unused variables in this scope.
1607     if (!S->hasUnrecoverableErrorOccurred()) {
1608       DiagnoseUnusedDecl(D);
1609       if (const auto *RD = dyn_cast<RecordDecl>(D))
1610         DiagnoseUnusedNestedTypedefs(RD);
1611     }
1612 
1613     // If this was a forward reference to a label, verify it was defined.
1614     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1615       CheckPoppedLabel(LD, *this);
1616 
1617     // Remove this name from our lexical scope.
1618     IdResolver.RemoveDecl(D);
1619   }
1620 }
1621 
1622 /// \brief Look for an Objective-C class in the translation unit.
1623 ///
1624 /// \param Id The name of the Objective-C class we're looking for. If
1625 /// typo-correction fixes this name, the Id will be updated
1626 /// to the fixed name.
1627 ///
1628 /// \param IdLoc The location of the name in the translation unit.
1629 ///
1630 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1631 /// if there is no class with the given name.
1632 ///
1633 /// \returns The declaration of the named Objective-C class, or NULL if the
1634 /// class could not be found.
1635 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1636                                               SourceLocation IdLoc,
1637                                               bool DoTypoCorrection) {
1638   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1639   // creation from this context.
1640   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1641 
1642   if (!IDecl && DoTypoCorrection) {
1643     // Perform typo correction at the given location, but only if we
1644     // find an Objective-C class name.
1645     if (TypoCorrection C = CorrectTypo(
1646             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1647             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1648             CTK_ErrorRecovery)) {
1649       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1650       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1651       Id = IDecl->getIdentifier();
1652     }
1653   }
1654   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1655   // This routine must always return a class definition, if any.
1656   if (Def && Def->getDefinition())
1657       Def = Def->getDefinition();
1658   return Def;
1659 }
1660 
1661 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1662 /// from S, where a non-field would be declared. This routine copes
1663 /// with the difference between C and C++ scoping rules in structs and
1664 /// unions. For example, the following code is well-formed in C but
1665 /// ill-formed in C++:
1666 /// @code
1667 /// struct S6 {
1668 ///   enum { BAR } e;
1669 /// };
1670 ///
1671 /// void test_S6() {
1672 ///   struct S6 a;
1673 ///   a.e = BAR;
1674 /// }
1675 /// @endcode
1676 /// For the declaration of BAR, this routine will return a different
1677 /// scope. The scope S will be the scope of the unnamed enumeration
1678 /// within S6. In C++, this routine will return the scope associated
1679 /// with S6, because the enumeration's scope is a transparent
1680 /// context but structures can contain non-field names. In C, this
1681 /// routine will return the translation unit scope, since the
1682 /// enumeration's scope is a transparent context and structures cannot
1683 /// contain non-field names.
1684 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1685   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1686          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1687          (S->isClassScope() && !getLangOpts().CPlusPlus))
1688     S = S->getParent();
1689   return S;
1690 }
1691 
1692 /// \brief Looks up the declaration of "struct objc_super" and
1693 /// saves it for later use in building builtin declaration of
1694 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1695 /// pre-existing declaration exists no action takes place.
1696 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1697                                         IdentifierInfo *II) {
1698   if (!II->isStr("objc_msgSendSuper"))
1699     return;
1700   ASTContext &Context = ThisSema.Context;
1701 
1702   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1703                       SourceLocation(), Sema::LookupTagName);
1704   ThisSema.LookupName(Result, S);
1705   if (Result.getResultKind() == LookupResult::Found)
1706     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1707       Context.setObjCSuperType(Context.getTagDeclType(TD));
1708 }
1709 
1710 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1711   switch (Error) {
1712   case ASTContext::GE_None:
1713     return "";
1714   case ASTContext::GE_Missing_stdio:
1715     return "stdio.h";
1716   case ASTContext::GE_Missing_setjmp:
1717     return "setjmp.h";
1718   case ASTContext::GE_Missing_ucontext:
1719     return "ucontext.h";
1720   }
1721   llvm_unreachable("unhandled error kind");
1722 }
1723 
1724 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1725 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1726 /// if we're creating this built-in in anticipation of redeclaring the
1727 /// built-in.
1728 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1729                                      Scope *S, bool ForRedeclaration,
1730                                      SourceLocation Loc) {
1731   LookupPredefedObjCSuperType(*this, S, II);
1732 
1733   ASTContext::GetBuiltinTypeError Error;
1734   QualType R = Context.GetBuiltinType(ID, Error);
1735   if (Error) {
1736     if (ForRedeclaration)
1737       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1738           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1739     return nullptr;
1740   }
1741 
1742   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1743     Diag(Loc, diag::ext_implicit_lib_function_decl)
1744         << Context.BuiltinInfo.getName(ID) << R;
1745     if (Context.BuiltinInfo.getHeaderName(ID) &&
1746         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1747       Diag(Loc, diag::note_include_header_or_declare)
1748           << Context.BuiltinInfo.getHeaderName(ID)
1749           << Context.BuiltinInfo.getName(ID);
1750   }
1751 
1752   DeclContext *Parent = Context.getTranslationUnitDecl();
1753   if (getLangOpts().CPlusPlus) {
1754     LinkageSpecDecl *CLinkageDecl =
1755         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1756                                 LinkageSpecDecl::lang_c, false);
1757     CLinkageDecl->setImplicit();
1758     Parent->addDecl(CLinkageDecl);
1759     Parent = CLinkageDecl;
1760   }
1761 
1762   FunctionDecl *New = FunctionDecl::Create(Context,
1763                                            Parent,
1764                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1765                                            SC_Extern,
1766                                            false,
1767                                            R->isFunctionProtoType());
1768   New->setImplicit();
1769 
1770   // Create Decl objects for each parameter, adding them to the
1771   // FunctionDecl.
1772   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1773     SmallVector<ParmVarDecl*, 16> Params;
1774     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775       ParmVarDecl *parm =
1776           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1777                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778                               SC_None, nullptr);
1779       parm->setScopeInfo(0, i);
1780       Params.push_back(parm);
1781     }
1782     New->setParams(Params);
1783   }
1784 
1785   AddKnownFunctionAttributes(New);
1786   RegisterLocallyScopedExternCDecl(New, S);
1787 
1788   // TUScope is the translation-unit scope to insert this function into.
1789   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1790   // relate Scopes to DeclContexts, and probably eliminate CurContext
1791   // entirely, but we're not there yet.
1792   DeclContext *SavedContext = CurContext;
1793   CurContext = Parent;
1794   PushOnScopeChains(New, TUScope);
1795   CurContext = SavedContext;
1796   return New;
1797 }
1798 
1799 /// Typedef declarations don't have linkage, but they still denote the same
1800 /// entity if their types are the same.
1801 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1802 /// isSameEntity.
1803 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1804                                                      TypedefNameDecl *Decl,
1805                                                      LookupResult &Previous) {
1806   // This is only interesting when modules are enabled.
1807   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1808     return;
1809 
1810   // Empty sets are uninteresting.
1811   if (Previous.empty())
1812     return;
1813 
1814   LookupResult::Filter Filter = Previous.makeFilter();
1815   while (Filter.hasNext()) {
1816     NamedDecl *Old = Filter.next();
1817 
1818     // Non-hidden declarations are never ignored.
1819     if (S.isVisible(Old))
1820       continue;
1821 
1822     // Declarations of the same entity are not ignored, even if they have
1823     // different linkages.
1824     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1825       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1826                                 Decl->getUnderlyingType()))
1827         continue;
1828 
1829       // If both declarations give a tag declaration a typedef name for linkage
1830       // purposes, then they declare the same entity.
1831       if (S.getLangOpts().CPlusPlus &&
1832           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1833           Decl->getAnonDeclWithTypedefName())
1834         continue;
1835     }
1836 
1837     Filter.erase();
1838   }
1839 
1840   Filter.done();
1841 }
1842 
1843 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1844   QualType OldType;
1845   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1846     OldType = OldTypedef->getUnderlyingType();
1847   else
1848     OldType = Context.getTypeDeclType(Old);
1849   QualType NewType = New->getUnderlyingType();
1850 
1851   if (NewType->isVariablyModifiedType()) {
1852     // Must not redefine a typedef with a variably-modified type.
1853     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1854     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1855       << Kind << NewType;
1856     if (Old->getLocation().isValid())
1857       Diag(Old->getLocation(), diag::note_previous_definition);
1858     New->setInvalidDecl();
1859     return true;
1860   }
1861 
1862   if (OldType != NewType &&
1863       !OldType->isDependentType() &&
1864       !NewType->isDependentType() &&
1865       !Context.hasSameType(OldType, NewType)) {
1866     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1867     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1868       << Kind << NewType << OldType;
1869     if (Old->getLocation().isValid())
1870       Diag(Old->getLocation(), diag::note_previous_definition);
1871     New->setInvalidDecl();
1872     return true;
1873   }
1874   return false;
1875 }
1876 
1877 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1878 /// same name and scope as a previous declaration 'Old'.  Figure out
1879 /// how to resolve this situation, merging decls or emitting
1880 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1881 ///
1882 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1883                                 LookupResult &OldDecls) {
1884   // If the new decl is known invalid already, don't bother doing any
1885   // merging checks.
1886   if (New->isInvalidDecl()) return;
1887 
1888   // Allow multiple definitions for ObjC built-in typedefs.
1889   // FIXME: Verify the underlying types are equivalent!
1890   if (getLangOpts().ObjC1) {
1891     const IdentifierInfo *TypeID = New->getIdentifier();
1892     switch (TypeID->getLength()) {
1893     default: break;
1894     case 2:
1895       {
1896         if (!TypeID->isStr("id"))
1897           break;
1898         QualType T = New->getUnderlyingType();
1899         if (!T->isPointerType())
1900           break;
1901         if (!T->isVoidPointerType()) {
1902           QualType PT = T->getAs<PointerType>()->getPointeeType();
1903           if (!PT->isStructureType())
1904             break;
1905         }
1906         Context.setObjCIdRedefinitionType(T);
1907         // Install the built-in type for 'id', ignoring the current definition.
1908         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1909         return;
1910       }
1911     case 5:
1912       if (!TypeID->isStr("Class"))
1913         break;
1914       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1915       // Install the built-in type for 'Class', ignoring the current definition.
1916       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1917       return;
1918     case 3:
1919       if (!TypeID->isStr("SEL"))
1920         break;
1921       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1922       // Install the built-in type for 'SEL', ignoring the current definition.
1923       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1924       return;
1925     }
1926     // Fall through - the typedef name was not a builtin type.
1927   }
1928 
1929   // Verify the old decl was also a type.
1930   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1931   if (!Old) {
1932     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1933       << New->getDeclName();
1934 
1935     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1936     if (OldD->getLocation().isValid())
1937       Diag(OldD->getLocation(), diag::note_previous_definition);
1938 
1939     return New->setInvalidDecl();
1940   }
1941 
1942   // If the old declaration is invalid, just give up here.
1943   if (Old->isInvalidDecl())
1944     return New->setInvalidDecl();
1945 
1946   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1947     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1948     auto *NewTag = New->getAnonDeclWithTypedefName();
1949     NamedDecl *Hidden = nullptr;
1950     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1951         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1952         !hasVisibleDefinition(OldTag, &Hidden)) {
1953       // There is a definition of this tag, but it is not visible. Use it
1954       // instead of our tag.
1955       New->setTypeForDecl(OldTD->getTypeForDecl());
1956       if (OldTD->isModed())
1957         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1958                                     OldTD->getUnderlyingType());
1959       else
1960         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1961 
1962       // Make the old tag definition visible.
1963       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1964 
1965       // If this was an unscoped enumeration, yank all of its enumerators
1966       // out of the scope.
1967       if (isa<EnumDecl>(NewTag)) {
1968         Scope *EnumScope = getNonFieldDeclScope(S);
1969         for (auto *D : NewTag->decls()) {
1970           auto *ED = cast<EnumConstantDecl>(D);
1971           assert(EnumScope->isDeclScope(ED));
1972           EnumScope->RemoveDecl(ED);
1973           IdResolver.RemoveDecl(ED);
1974           ED->getLexicalDeclContext()->removeDecl(ED);
1975         }
1976       }
1977     }
1978   }
1979 
1980   // If the typedef types are not identical, reject them in all languages and
1981   // with any extensions enabled.
1982   if (isIncompatibleTypedef(Old, New))
1983     return;
1984 
1985   // The types match.  Link up the redeclaration chain and merge attributes if
1986   // the old declaration was a typedef.
1987   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1988     New->setPreviousDecl(Typedef);
1989     mergeDeclAttributes(New, Old);
1990   }
1991 
1992   if (getLangOpts().MicrosoftExt)
1993     return;
1994 
1995   if (getLangOpts().CPlusPlus) {
1996     // C++ [dcl.typedef]p2:
1997     //   In a given non-class scope, a typedef specifier can be used to
1998     //   redefine the name of any type declared in that scope to refer
1999     //   to the type to which it already refers.
2000     if (!isa<CXXRecordDecl>(CurContext))
2001       return;
2002 
2003     // C++0x [dcl.typedef]p4:
2004     //   In a given class scope, a typedef specifier can be used to redefine
2005     //   any class-name declared in that scope that is not also a typedef-name
2006     //   to refer to the type to which it already refers.
2007     //
2008     // This wording came in via DR424, which was a correction to the
2009     // wording in DR56, which accidentally banned code like:
2010     //
2011     //   struct S {
2012     //     typedef struct A { } A;
2013     //   };
2014     //
2015     // in the C++03 standard. We implement the C++0x semantics, which
2016     // allow the above but disallow
2017     //
2018     //   struct S {
2019     //     typedef int I;
2020     //     typedef int I;
2021     //   };
2022     //
2023     // since that was the intent of DR56.
2024     if (!isa<TypedefNameDecl>(Old))
2025       return;
2026 
2027     Diag(New->getLocation(), diag::err_redefinition)
2028       << New->getDeclName();
2029     Diag(Old->getLocation(), diag::note_previous_definition);
2030     return New->setInvalidDecl();
2031   }
2032 
2033   // Modules always permit redefinition of typedefs, as does C11.
2034   if (getLangOpts().Modules || getLangOpts().C11)
2035     return;
2036 
2037   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2038   // is normally mapped to an error, but can be controlled with
2039   // -Wtypedef-redefinition.  If either the original or the redefinition is
2040   // in a system header, don't emit this for compatibility with GCC.
2041   if (getDiagnostics().getSuppressSystemWarnings() &&
2042       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2043        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2044     return;
2045 
2046   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2047     << New->getDeclName();
2048   Diag(Old->getLocation(), diag::note_previous_definition);
2049 }
2050 
2051 /// DeclhasAttr - returns true if decl Declaration already has the target
2052 /// attribute.
2053 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2054   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2055   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2056   for (const auto *i : D->attrs())
2057     if (i->getKind() == A->getKind()) {
2058       if (Ann) {
2059         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2060           return true;
2061         continue;
2062       }
2063       // FIXME: Don't hardcode this check
2064       if (OA && isa<OwnershipAttr>(i))
2065         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2066       return true;
2067     }
2068 
2069   return false;
2070 }
2071 
2072 static bool isAttributeTargetADefinition(Decl *D) {
2073   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2074     return VD->isThisDeclarationADefinition();
2075   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2076     return TD->isCompleteDefinition() || TD->isBeingDefined();
2077   return true;
2078 }
2079 
2080 /// Merge alignment attributes from \p Old to \p New, taking into account the
2081 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2082 ///
2083 /// \return \c true if any attributes were added to \p New.
2084 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2085   // Look for alignas attributes on Old, and pick out whichever attribute
2086   // specifies the strictest alignment requirement.
2087   AlignedAttr *OldAlignasAttr = nullptr;
2088   AlignedAttr *OldStrictestAlignAttr = nullptr;
2089   unsigned OldAlign = 0;
2090   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2091     // FIXME: We have no way of representing inherited dependent alignments
2092     // in a case like:
2093     //   template<int A, int B> struct alignas(A) X;
2094     //   template<int A, int B> struct alignas(B) X {};
2095     // For now, we just ignore any alignas attributes which are not on the
2096     // definition in such a case.
2097     if (I->isAlignmentDependent())
2098       return false;
2099 
2100     if (I->isAlignas())
2101       OldAlignasAttr = I;
2102 
2103     unsigned Align = I->getAlignment(S.Context);
2104     if (Align > OldAlign) {
2105       OldAlign = Align;
2106       OldStrictestAlignAttr = I;
2107     }
2108   }
2109 
2110   // Look for alignas attributes on New.
2111   AlignedAttr *NewAlignasAttr = nullptr;
2112   unsigned NewAlign = 0;
2113   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2114     if (I->isAlignmentDependent())
2115       return false;
2116 
2117     if (I->isAlignas())
2118       NewAlignasAttr = I;
2119 
2120     unsigned Align = I->getAlignment(S.Context);
2121     if (Align > NewAlign)
2122       NewAlign = Align;
2123   }
2124 
2125   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2126     // Both declarations have 'alignas' attributes. We require them to match.
2127     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2128     // fall short. (If two declarations both have alignas, they must both match
2129     // every definition, and so must match each other if there is a definition.)
2130 
2131     // If either declaration only contains 'alignas(0)' specifiers, then it
2132     // specifies the natural alignment for the type.
2133     if (OldAlign == 0 || NewAlign == 0) {
2134       QualType Ty;
2135       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2136         Ty = VD->getType();
2137       else
2138         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2139 
2140       if (OldAlign == 0)
2141         OldAlign = S.Context.getTypeAlign(Ty);
2142       if (NewAlign == 0)
2143         NewAlign = S.Context.getTypeAlign(Ty);
2144     }
2145 
2146     if (OldAlign != NewAlign) {
2147       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2148         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2149         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2150       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2151     }
2152   }
2153 
2154   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2155     // C++11 [dcl.align]p6:
2156     //   if any declaration of an entity has an alignment-specifier,
2157     //   every defining declaration of that entity shall specify an
2158     //   equivalent alignment.
2159     // C11 6.7.5/7:
2160     //   If the definition of an object does not have an alignment
2161     //   specifier, any other declaration of that object shall also
2162     //   have no alignment specifier.
2163     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2164       << OldAlignasAttr;
2165     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2166       << OldAlignasAttr;
2167   }
2168 
2169   bool AnyAdded = false;
2170 
2171   // Ensure we have an attribute representing the strictest alignment.
2172   if (OldAlign > NewAlign) {
2173     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2174     Clone->setInherited(true);
2175     New->addAttr(Clone);
2176     AnyAdded = true;
2177   }
2178 
2179   // Ensure we have an alignas attribute if the old declaration had one.
2180   if (OldAlignasAttr && !NewAlignasAttr &&
2181       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2182     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2183     Clone->setInherited(true);
2184     New->addAttr(Clone);
2185     AnyAdded = true;
2186   }
2187 
2188   return AnyAdded;
2189 }
2190 
2191 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2192                                const InheritableAttr *Attr,
2193                                Sema::AvailabilityMergeKind AMK) {
2194   InheritableAttr *NewAttr = nullptr;
2195   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2196   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2197     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2198                                       AA->getIntroduced(), AA->getDeprecated(),
2199                                       AA->getObsoleted(), AA->getUnavailable(),
2200                                       AA->getMessage(), AMK,
2201                                       AttrSpellingListIndex);
2202   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2203     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2204                                     AttrSpellingListIndex);
2205   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2206     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2207                                         AttrSpellingListIndex);
2208   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2209     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2210                                    AttrSpellingListIndex);
2211   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2212     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2213                                    AttrSpellingListIndex);
2214   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2215     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2216                                 FA->getFormatIdx(), FA->getFirstArg(),
2217                                 AttrSpellingListIndex);
2218   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2219     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2220                                  AttrSpellingListIndex);
2221   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2222     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2223                                        AttrSpellingListIndex,
2224                                        IA->getSemanticSpelling());
2225   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2226     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2227                                       &S.Context.Idents.get(AA->getSpelling()),
2228                                       AttrSpellingListIndex);
2229   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2230     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2231   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2232     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2233   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2234     NewAttr = S.mergeInternalLinkageAttr(
2235         D, InternalLinkageA->getRange(),
2236         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2237         AttrSpellingListIndex);
2238   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2239     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2240                                 &S.Context.Idents.get(CommonA->getSpelling()),
2241                                 AttrSpellingListIndex);
2242   else if (isa<AlignedAttr>(Attr))
2243     // AlignedAttrs are handled separately, because we need to handle all
2244     // such attributes on a declaration at the same time.
2245     NewAttr = nullptr;
2246   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2247            (AMK == Sema::AMK_Override ||
2248             AMK == Sema::AMK_ProtocolImplementation))
2249     NewAttr = nullptr;
2250   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2251     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2252 
2253   if (NewAttr) {
2254     NewAttr->setInherited(true);
2255     D->addAttr(NewAttr);
2256     return true;
2257   }
2258 
2259   return false;
2260 }
2261 
2262 static const Decl *getDefinition(const Decl *D) {
2263   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2264     return TD->getDefinition();
2265   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2266     const VarDecl *Def = VD->getDefinition();
2267     if (Def)
2268       return Def;
2269     return VD->getActingDefinition();
2270   }
2271   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2272     const FunctionDecl* Def;
2273     if (FD->isDefined(Def))
2274       return Def;
2275   }
2276   return nullptr;
2277 }
2278 
2279 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2280   for (const auto *Attribute : D->attrs())
2281     if (Attribute->getKind() == Kind)
2282       return true;
2283   return false;
2284 }
2285 
2286 /// checkNewAttributesAfterDef - If we already have a definition, check that
2287 /// there are no new attributes in this declaration.
2288 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2289   if (!New->hasAttrs())
2290     return;
2291 
2292   const Decl *Def = getDefinition(Old);
2293   if (!Def || Def == New)
2294     return;
2295 
2296   AttrVec &NewAttributes = New->getAttrs();
2297   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2298     const Attr *NewAttribute = NewAttributes[I];
2299 
2300     if (isa<AliasAttr>(NewAttribute)) {
2301       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2302         Sema::SkipBodyInfo SkipBody;
2303         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2304 
2305         // If we're skipping this definition, drop the "alias" attribute.
2306         if (SkipBody.ShouldSkip) {
2307           NewAttributes.erase(NewAttributes.begin() + I);
2308           --E;
2309           continue;
2310         }
2311       } else {
2312         VarDecl *VD = cast<VarDecl>(New);
2313         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2314                                 VarDecl::TentativeDefinition
2315                             ? diag::err_alias_after_tentative
2316                             : diag::err_redefinition;
2317         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2318         S.Diag(Def->getLocation(), diag::note_previous_definition);
2319         VD->setInvalidDecl();
2320       }
2321       ++I;
2322       continue;
2323     }
2324 
2325     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2326       // Tentative definitions are only interesting for the alias check above.
2327       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2328         ++I;
2329         continue;
2330       }
2331     }
2332 
2333     if (hasAttribute(Def, NewAttribute->getKind())) {
2334       ++I;
2335       continue; // regular attr merging will take care of validating this.
2336     }
2337 
2338     if (isa<C11NoReturnAttr>(NewAttribute)) {
2339       // C's _Noreturn is allowed to be added to a function after it is defined.
2340       ++I;
2341       continue;
2342     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2343       if (AA->isAlignas()) {
2344         // C++11 [dcl.align]p6:
2345         //   if any declaration of an entity has an alignment-specifier,
2346         //   every defining declaration of that entity shall specify an
2347         //   equivalent alignment.
2348         // C11 6.7.5/7:
2349         //   If the definition of an object does not have an alignment
2350         //   specifier, any other declaration of that object shall also
2351         //   have no alignment specifier.
2352         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2353           << AA;
2354         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2355           << AA;
2356         NewAttributes.erase(NewAttributes.begin() + I);
2357         --E;
2358         continue;
2359       }
2360     }
2361 
2362     S.Diag(NewAttribute->getLocation(),
2363            diag::warn_attribute_precede_definition);
2364     S.Diag(Def->getLocation(), diag::note_previous_definition);
2365     NewAttributes.erase(NewAttributes.begin() + I);
2366     --E;
2367   }
2368 }
2369 
2370 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2371 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2372                                AvailabilityMergeKind AMK) {
2373   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2374     UsedAttr *NewAttr = OldAttr->clone(Context);
2375     NewAttr->setInherited(true);
2376     New->addAttr(NewAttr);
2377   }
2378 
2379   if (!Old->hasAttrs() && !New->hasAttrs())
2380     return;
2381 
2382   // attributes declared post-definition are currently ignored
2383   checkNewAttributesAfterDef(*this, New, Old);
2384 
2385   if (!Old->hasAttrs())
2386     return;
2387 
2388   bool foundAny = New->hasAttrs();
2389 
2390   // Ensure that any moving of objects within the allocated map is done before
2391   // we process them.
2392   if (!foundAny) New->setAttrs(AttrVec());
2393 
2394   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2395     // Ignore deprecated/unavailable/availability attributes if requested.
2396     AvailabilityMergeKind LocalAMK = AMK_None;
2397     if (isa<DeprecatedAttr>(I) ||
2398         isa<UnavailableAttr>(I) ||
2399         isa<AvailabilityAttr>(I)) {
2400       switch (AMK) {
2401       case AMK_None:
2402         continue;
2403 
2404       case AMK_Redeclaration:
2405       case AMK_Override:
2406       case AMK_ProtocolImplementation:
2407         LocalAMK = AMK;
2408         break;
2409       }
2410     }
2411 
2412     // Already handled.
2413     if (isa<UsedAttr>(I))
2414       continue;
2415 
2416     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2417       foundAny = true;
2418   }
2419 
2420   if (mergeAlignedAttrs(*this, New, Old))
2421     foundAny = true;
2422 
2423   if (!foundAny) New->dropAttrs();
2424 }
2425 
2426 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2427 /// to the new one.
2428 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2429                                      const ParmVarDecl *oldDecl,
2430                                      Sema &S) {
2431   // C++11 [dcl.attr.depend]p2:
2432   //   The first declaration of a function shall specify the
2433   //   carries_dependency attribute for its declarator-id if any declaration
2434   //   of the function specifies the carries_dependency attribute.
2435   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2436   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2437     S.Diag(CDA->getLocation(),
2438            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2439     // Find the first declaration of the parameter.
2440     // FIXME: Should we build redeclaration chains for function parameters?
2441     const FunctionDecl *FirstFD =
2442       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2443     const ParmVarDecl *FirstVD =
2444       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2445     S.Diag(FirstVD->getLocation(),
2446            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2447   }
2448 
2449   if (!oldDecl->hasAttrs())
2450     return;
2451 
2452   bool foundAny = newDecl->hasAttrs();
2453 
2454   // Ensure that any moving of objects within the allocated map is
2455   // done before we process them.
2456   if (!foundAny) newDecl->setAttrs(AttrVec());
2457 
2458   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2459     if (!DeclHasAttr(newDecl, I)) {
2460       InheritableAttr *newAttr =
2461         cast<InheritableParamAttr>(I->clone(S.Context));
2462       newAttr->setInherited(true);
2463       newDecl->addAttr(newAttr);
2464       foundAny = true;
2465     }
2466   }
2467 
2468   if (!foundAny) newDecl->dropAttrs();
2469 }
2470 
2471 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2472                                 const ParmVarDecl *OldParam,
2473                                 Sema &S) {
2474   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2475     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2476       if (*Oldnullability != *Newnullability) {
2477         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2478           << DiagNullabilityKind(
2479                *Newnullability,
2480                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2481                 != 0))
2482           << DiagNullabilityKind(
2483                *Oldnullability,
2484                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2485                 != 0));
2486         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2487       }
2488     } else {
2489       QualType NewT = NewParam->getType();
2490       NewT = S.Context.getAttributedType(
2491                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2492                          NewT, NewT);
2493       NewParam->setType(NewT);
2494     }
2495   }
2496 }
2497 
2498 namespace {
2499 
2500 /// Used in MergeFunctionDecl to keep track of function parameters in
2501 /// C.
2502 struct GNUCompatibleParamWarning {
2503   ParmVarDecl *OldParm;
2504   ParmVarDecl *NewParm;
2505   QualType PromotedType;
2506 };
2507 
2508 }
2509 
2510 /// getSpecialMember - get the special member enum for a method.
2511 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2512   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2513     if (Ctor->isDefaultConstructor())
2514       return Sema::CXXDefaultConstructor;
2515 
2516     if (Ctor->isCopyConstructor())
2517       return Sema::CXXCopyConstructor;
2518 
2519     if (Ctor->isMoveConstructor())
2520       return Sema::CXXMoveConstructor;
2521   } else if (isa<CXXDestructorDecl>(MD)) {
2522     return Sema::CXXDestructor;
2523   } else if (MD->isCopyAssignmentOperator()) {
2524     return Sema::CXXCopyAssignment;
2525   } else if (MD->isMoveAssignmentOperator()) {
2526     return Sema::CXXMoveAssignment;
2527   }
2528 
2529   return Sema::CXXInvalid;
2530 }
2531 
2532 // Determine whether the previous declaration was a definition, implicit
2533 // declaration, or a declaration.
2534 template <typename T>
2535 static std::pair<diag::kind, SourceLocation>
2536 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2537   diag::kind PrevDiag;
2538   SourceLocation OldLocation = Old->getLocation();
2539   if (Old->isThisDeclarationADefinition())
2540     PrevDiag = diag::note_previous_definition;
2541   else if (Old->isImplicit()) {
2542     PrevDiag = diag::note_previous_implicit_declaration;
2543     if (OldLocation.isInvalid())
2544       OldLocation = New->getLocation();
2545   } else
2546     PrevDiag = diag::note_previous_declaration;
2547   return std::make_pair(PrevDiag, OldLocation);
2548 }
2549 
2550 /// canRedefineFunction - checks if a function can be redefined. Currently,
2551 /// only extern inline functions can be redefined, and even then only in
2552 /// GNU89 mode.
2553 static bool canRedefineFunction(const FunctionDecl *FD,
2554                                 const LangOptions& LangOpts) {
2555   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2556           !LangOpts.CPlusPlus &&
2557           FD->isInlineSpecified() &&
2558           FD->getStorageClass() == SC_Extern);
2559 }
2560 
2561 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2562   const AttributedType *AT = T->getAs<AttributedType>();
2563   while (AT && !AT->isCallingConv())
2564     AT = AT->getModifiedType()->getAs<AttributedType>();
2565   return AT;
2566 }
2567 
2568 template <typename T>
2569 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2570   const DeclContext *DC = Old->getDeclContext();
2571   if (DC->isRecord())
2572     return false;
2573 
2574   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2575   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2576     return true;
2577   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2578     return true;
2579   return false;
2580 }
2581 
2582 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2583 static bool isExternC(VarTemplateDecl *) { return false; }
2584 
2585 /// \brief Check whether a redeclaration of an entity introduced by a
2586 /// using-declaration is valid, given that we know it's not an overload
2587 /// (nor a hidden tag declaration).
2588 template<typename ExpectedDecl>
2589 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2590                                    ExpectedDecl *New) {
2591   // C++11 [basic.scope.declarative]p4:
2592   //   Given a set of declarations in a single declarative region, each of
2593   //   which specifies the same unqualified name,
2594   //   -- they shall all refer to the same entity, or all refer to functions
2595   //      and function templates; or
2596   //   -- exactly one declaration shall declare a class name or enumeration
2597   //      name that is not a typedef name and the other declarations shall all
2598   //      refer to the same variable or enumerator, or all refer to functions
2599   //      and function templates; in this case the class name or enumeration
2600   //      name is hidden (3.3.10).
2601 
2602   // C++11 [namespace.udecl]p14:
2603   //   If a function declaration in namespace scope or block scope has the
2604   //   same name and the same parameter-type-list as a function introduced
2605   //   by a using-declaration, and the declarations do not declare the same
2606   //   function, the program is ill-formed.
2607 
2608   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2609   if (Old &&
2610       !Old->getDeclContext()->getRedeclContext()->Equals(
2611           New->getDeclContext()->getRedeclContext()) &&
2612       !(isExternC(Old) && isExternC(New)))
2613     Old = nullptr;
2614 
2615   if (!Old) {
2616     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2617     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2618     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2619     return true;
2620   }
2621   return false;
2622 }
2623 
2624 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2625                                             const FunctionDecl *B) {
2626   assert(A->getNumParams() == B->getNumParams());
2627 
2628   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2629     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2630     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2631     if (AttrA == AttrB)
2632       return true;
2633     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2634   };
2635 
2636   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2637 }
2638 
2639 /// MergeFunctionDecl - We just parsed a function 'New' from
2640 /// declarator D which has the same name and scope as a previous
2641 /// declaration 'Old'.  Figure out how to resolve this situation,
2642 /// merging decls or emitting diagnostics as appropriate.
2643 ///
2644 /// In C++, New and Old must be declarations that are not
2645 /// overloaded. Use IsOverload to determine whether New and Old are
2646 /// overloaded, and to select the Old declaration that New should be
2647 /// merged with.
2648 ///
2649 /// Returns true if there was an error, false otherwise.
2650 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2651                              Scope *S, bool MergeTypeWithOld) {
2652   // Verify the old decl was also a function.
2653   FunctionDecl *Old = OldD->getAsFunction();
2654   if (!Old) {
2655     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2656       if (New->getFriendObjectKind()) {
2657         Diag(New->getLocation(), diag::err_using_decl_friend);
2658         Diag(Shadow->getTargetDecl()->getLocation(),
2659              diag::note_using_decl_target);
2660         Diag(Shadow->getUsingDecl()->getLocation(),
2661              diag::note_using_decl) << 0;
2662         return true;
2663       }
2664 
2665       // Check whether the two declarations might declare the same function.
2666       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2667         return true;
2668       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2669     } else {
2670       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2671         << New->getDeclName();
2672       Diag(OldD->getLocation(), diag::note_previous_definition);
2673       return true;
2674     }
2675   }
2676 
2677   // If the old declaration is invalid, just give up here.
2678   if (Old->isInvalidDecl())
2679     return true;
2680 
2681   diag::kind PrevDiag;
2682   SourceLocation OldLocation;
2683   std::tie(PrevDiag, OldLocation) =
2684       getNoteDiagForInvalidRedeclaration(Old, New);
2685 
2686   // Don't complain about this if we're in GNU89 mode and the old function
2687   // is an extern inline function.
2688   // Don't complain about specializations. They are not supposed to have
2689   // storage classes.
2690   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2691       New->getStorageClass() == SC_Static &&
2692       Old->hasExternalFormalLinkage() &&
2693       !New->getTemplateSpecializationInfo() &&
2694       !canRedefineFunction(Old, getLangOpts())) {
2695     if (getLangOpts().MicrosoftExt) {
2696       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2697       Diag(OldLocation, PrevDiag);
2698     } else {
2699       Diag(New->getLocation(), diag::err_static_non_static) << New;
2700       Diag(OldLocation, PrevDiag);
2701       return true;
2702     }
2703   }
2704 
2705   if (New->hasAttr<InternalLinkageAttr>() &&
2706       !Old->hasAttr<InternalLinkageAttr>()) {
2707     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2708         << New->getDeclName();
2709     Diag(Old->getLocation(), diag::note_previous_definition);
2710     New->dropAttr<InternalLinkageAttr>();
2711   }
2712 
2713   // If a function is first declared with a calling convention, but is later
2714   // declared or defined without one, all following decls assume the calling
2715   // convention of the first.
2716   //
2717   // It's OK if a function is first declared without a calling convention,
2718   // but is later declared or defined with the default calling convention.
2719   //
2720   // To test if either decl has an explicit calling convention, we look for
2721   // AttributedType sugar nodes on the type as written.  If they are missing or
2722   // were canonicalized away, we assume the calling convention was implicit.
2723   //
2724   // Note also that we DO NOT return at this point, because we still have
2725   // other tests to run.
2726   QualType OldQType = Context.getCanonicalType(Old->getType());
2727   QualType NewQType = Context.getCanonicalType(New->getType());
2728   const FunctionType *OldType = cast<FunctionType>(OldQType);
2729   const FunctionType *NewType = cast<FunctionType>(NewQType);
2730   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2731   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2732   bool RequiresAdjustment = false;
2733 
2734   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2735     FunctionDecl *First = Old->getFirstDecl();
2736     const FunctionType *FT =
2737         First->getType().getCanonicalType()->castAs<FunctionType>();
2738     FunctionType::ExtInfo FI = FT->getExtInfo();
2739     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2740     if (!NewCCExplicit) {
2741       // Inherit the CC from the previous declaration if it was specified
2742       // there but not here.
2743       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2744       RequiresAdjustment = true;
2745     } else {
2746       // Calling conventions aren't compatible, so complain.
2747       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2748       Diag(New->getLocation(), diag::err_cconv_change)
2749         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2750         << !FirstCCExplicit
2751         << (!FirstCCExplicit ? "" :
2752             FunctionType::getNameForCallConv(FI.getCC()));
2753 
2754       // Put the note on the first decl, since it is the one that matters.
2755       Diag(First->getLocation(), diag::note_previous_declaration);
2756       return true;
2757     }
2758   }
2759 
2760   // FIXME: diagnose the other way around?
2761   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2762     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2763     RequiresAdjustment = true;
2764   }
2765 
2766   // Merge regparm attribute.
2767   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2768       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2769     if (NewTypeInfo.getHasRegParm()) {
2770       Diag(New->getLocation(), diag::err_regparm_mismatch)
2771         << NewType->getRegParmType()
2772         << OldType->getRegParmType();
2773       Diag(OldLocation, diag::note_previous_declaration);
2774       return true;
2775     }
2776 
2777     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2778     RequiresAdjustment = true;
2779   }
2780 
2781   // Merge ns_returns_retained attribute.
2782   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2783     if (NewTypeInfo.getProducesResult()) {
2784       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2785       Diag(OldLocation, diag::note_previous_declaration);
2786       return true;
2787     }
2788 
2789     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2790     RequiresAdjustment = true;
2791   }
2792 
2793   if (RequiresAdjustment) {
2794     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2795     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2796     New->setType(QualType(AdjustedType, 0));
2797     NewQType = Context.getCanonicalType(New->getType());
2798     NewType = cast<FunctionType>(NewQType);
2799   }
2800 
2801   // If this redeclaration makes the function inline, we may need to add it to
2802   // UndefinedButUsed.
2803   if (!Old->isInlined() && New->isInlined() &&
2804       !New->hasAttr<GNUInlineAttr>() &&
2805       !getLangOpts().GNUInline &&
2806       Old->isUsed(false) &&
2807       !Old->isDefined() && !New->isThisDeclarationADefinition())
2808     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2809                                            SourceLocation()));
2810 
2811   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2812   // about it.
2813   if (New->hasAttr<GNUInlineAttr>() &&
2814       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2815     UndefinedButUsed.erase(Old->getCanonicalDecl());
2816   }
2817 
2818   // If pass_object_size params don't match up perfectly, this isn't a valid
2819   // redeclaration.
2820   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2821       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2822     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2823         << New->getDeclName();
2824     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2825     return true;
2826   }
2827 
2828   if (getLangOpts().CPlusPlus) {
2829     // (C++98 13.1p2):
2830     //   Certain function declarations cannot be overloaded:
2831     //     -- Function declarations that differ only in the return type
2832     //        cannot be overloaded.
2833 
2834     // Go back to the type source info to compare the declared return types,
2835     // per C++1y [dcl.type.auto]p13:
2836     //   Redeclarations or specializations of a function or function template
2837     //   with a declared return type that uses a placeholder type shall also
2838     //   use that placeholder, not a deduced type.
2839     QualType OldDeclaredReturnType =
2840         (Old->getTypeSourceInfo()
2841              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2842              : OldType)->getReturnType();
2843     QualType NewDeclaredReturnType =
2844         (New->getTypeSourceInfo()
2845              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2846              : NewType)->getReturnType();
2847     QualType ResQT;
2848     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2849         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2850           New->isLocalExternDecl())) {
2851       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2852           OldDeclaredReturnType->isObjCObjectPointerType())
2853         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2854       if (ResQT.isNull()) {
2855         if (New->isCXXClassMember() && New->isOutOfLine())
2856           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2857               << New << New->getReturnTypeSourceRange();
2858         else
2859           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2860               << New->getReturnTypeSourceRange();
2861         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2862                                     << Old->getReturnTypeSourceRange();
2863         return true;
2864       }
2865       else
2866         NewQType = ResQT;
2867     }
2868 
2869     QualType OldReturnType = OldType->getReturnType();
2870     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2871     if (OldReturnType != NewReturnType) {
2872       // If this function has a deduced return type and has already been
2873       // defined, copy the deduced value from the old declaration.
2874       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2875       if (OldAT && OldAT->isDeduced()) {
2876         New->setType(
2877             SubstAutoType(New->getType(),
2878                           OldAT->isDependentType() ? Context.DependentTy
2879                                                    : OldAT->getDeducedType()));
2880         NewQType = Context.getCanonicalType(
2881             SubstAutoType(NewQType,
2882                           OldAT->isDependentType() ? Context.DependentTy
2883                                                    : OldAT->getDeducedType()));
2884       }
2885     }
2886 
2887     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2888     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2889     if (OldMethod && NewMethod) {
2890       // Preserve triviality.
2891       NewMethod->setTrivial(OldMethod->isTrivial());
2892 
2893       // MSVC allows explicit template specialization at class scope:
2894       // 2 CXXMethodDecls referring to the same function will be injected.
2895       // We don't want a redeclaration error.
2896       bool IsClassScopeExplicitSpecialization =
2897                               OldMethod->isFunctionTemplateSpecialization() &&
2898                               NewMethod->isFunctionTemplateSpecialization();
2899       bool isFriend = NewMethod->getFriendObjectKind();
2900 
2901       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2902           !IsClassScopeExplicitSpecialization) {
2903         //    -- Member function declarations with the same name and the
2904         //       same parameter types cannot be overloaded if any of them
2905         //       is a static member function declaration.
2906         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2907           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2908           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2909           return true;
2910         }
2911 
2912         // C++ [class.mem]p1:
2913         //   [...] A member shall not be declared twice in the
2914         //   member-specification, except that a nested class or member
2915         //   class template can be declared and then later defined.
2916         if (ActiveTemplateInstantiations.empty()) {
2917           unsigned NewDiag;
2918           if (isa<CXXConstructorDecl>(OldMethod))
2919             NewDiag = diag::err_constructor_redeclared;
2920           else if (isa<CXXDestructorDecl>(NewMethod))
2921             NewDiag = diag::err_destructor_redeclared;
2922           else if (isa<CXXConversionDecl>(NewMethod))
2923             NewDiag = diag::err_conv_function_redeclared;
2924           else
2925             NewDiag = diag::err_member_redeclared;
2926 
2927           Diag(New->getLocation(), NewDiag);
2928         } else {
2929           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2930             << New << New->getType();
2931         }
2932         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2933         return true;
2934 
2935       // Complain if this is an explicit declaration of a special
2936       // member that was initially declared implicitly.
2937       //
2938       // As an exception, it's okay to befriend such methods in order
2939       // to permit the implicit constructor/destructor/operator calls.
2940       } else if (OldMethod->isImplicit()) {
2941         if (isFriend) {
2942           NewMethod->setImplicit();
2943         } else {
2944           Diag(NewMethod->getLocation(),
2945                diag::err_definition_of_implicitly_declared_member)
2946             << New << getSpecialMember(OldMethod);
2947           return true;
2948         }
2949       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2950         Diag(NewMethod->getLocation(),
2951              diag::err_definition_of_explicitly_defaulted_member)
2952           << getSpecialMember(OldMethod);
2953         return true;
2954       }
2955     }
2956 
2957     // C++11 [dcl.attr.noreturn]p1:
2958     //   The first declaration of a function shall specify the noreturn
2959     //   attribute if any declaration of that function specifies the noreturn
2960     //   attribute.
2961     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2962     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2963       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2964       Diag(Old->getFirstDecl()->getLocation(),
2965            diag::note_noreturn_missing_first_decl);
2966     }
2967 
2968     // C++11 [dcl.attr.depend]p2:
2969     //   The first declaration of a function shall specify the
2970     //   carries_dependency attribute for its declarator-id if any declaration
2971     //   of the function specifies the carries_dependency attribute.
2972     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2973     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2974       Diag(CDA->getLocation(),
2975            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2976       Diag(Old->getFirstDecl()->getLocation(),
2977            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2978     }
2979 
2980     // (C++98 8.3.5p3):
2981     //   All declarations for a function shall agree exactly in both the
2982     //   return type and the parameter-type-list.
2983     // We also want to respect all the extended bits except noreturn.
2984 
2985     // noreturn should now match unless the old type info didn't have it.
2986     QualType OldQTypeForComparison = OldQType;
2987     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2988       assert(OldQType == QualType(OldType, 0));
2989       const FunctionType *OldTypeForComparison
2990         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2991       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2992       assert(OldQTypeForComparison.isCanonical());
2993     }
2994 
2995     if (haveIncompatibleLanguageLinkages(Old, New)) {
2996       // As a special case, retain the language linkage from previous
2997       // declarations of a friend function as an extension.
2998       //
2999       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3000       // and is useful because there's otherwise no way to specify language
3001       // linkage within class scope.
3002       //
3003       // Check cautiously as the friend object kind isn't yet complete.
3004       if (New->getFriendObjectKind() != Decl::FOK_None) {
3005         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3006         Diag(OldLocation, PrevDiag);
3007       } else {
3008         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3009         Diag(OldLocation, PrevDiag);
3010         return true;
3011       }
3012     }
3013 
3014     if (OldQTypeForComparison == NewQType)
3015       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3016 
3017     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3018         New->isLocalExternDecl()) {
3019       // It's OK if we couldn't merge types for a local function declaraton
3020       // if either the old or new type is dependent. We'll merge the types
3021       // when we instantiate the function.
3022       return false;
3023     }
3024 
3025     // Fall through for conflicting redeclarations and redefinitions.
3026   }
3027 
3028   // C: Function types need to be compatible, not identical. This handles
3029   // duplicate function decls like "void f(int); void f(enum X);" properly.
3030   if (!getLangOpts().CPlusPlus &&
3031       Context.typesAreCompatible(OldQType, NewQType)) {
3032     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3033     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3034     const FunctionProtoType *OldProto = nullptr;
3035     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3036         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3037       // The old declaration provided a function prototype, but the
3038       // new declaration does not. Merge in the prototype.
3039       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3040       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3041       NewQType =
3042           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3043                                   OldProto->getExtProtoInfo());
3044       New->setType(NewQType);
3045       New->setHasInheritedPrototype();
3046 
3047       // Synthesize parameters with the same types.
3048       SmallVector<ParmVarDecl*, 16> Params;
3049       for (const auto &ParamType : OldProto->param_types()) {
3050         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3051                                                  SourceLocation(), nullptr,
3052                                                  ParamType, /*TInfo=*/nullptr,
3053                                                  SC_None, nullptr);
3054         Param->setScopeInfo(0, Params.size());
3055         Param->setImplicit();
3056         Params.push_back(Param);
3057       }
3058 
3059       New->setParams(Params);
3060     }
3061 
3062     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3063   }
3064 
3065   // GNU C permits a K&R definition to follow a prototype declaration
3066   // if the declared types of the parameters in the K&R definition
3067   // match the types in the prototype declaration, even when the
3068   // promoted types of the parameters from the K&R definition differ
3069   // from the types in the prototype. GCC then keeps the types from
3070   // the prototype.
3071   //
3072   // If a variadic prototype is followed by a non-variadic K&R definition,
3073   // the K&R definition becomes variadic.  This is sort of an edge case, but
3074   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3075   // C99 6.9.1p8.
3076   if (!getLangOpts().CPlusPlus &&
3077       Old->hasPrototype() && !New->hasPrototype() &&
3078       New->getType()->getAs<FunctionProtoType>() &&
3079       Old->getNumParams() == New->getNumParams()) {
3080     SmallVector<QualType, 16> ArgTypes;
3081     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3082     const FunctionProtoType *OldProto
3083       = Old->getType()->getAs<FunctionProtoType>();
3084     const FunctionProtoType *NewProto
3085       = New->getType()->getAs<FunctionProtoType>();
3086 
3087     // Determine whether this is the GNU C extension.
3088     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3089                                                NewProto->getReturnType());
3090     bool LooseCompatible = !MergedReturn.isNull();
3091     for (unsigned Idx = 0, End = Old->getNumParams();
3092          LooseCompatible && Idx != End; ++Idx) {
3093       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3094       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3095       if (Context.typesAreCompatible(OldParm->getType(),
3096                                      NewProto->getParamType(Idx))) {
3097         ArgTypes.push_back(NewParm->getType());
3098       } else if (Context.typesAreCompatible(OldParm->getType(),
3099                                             NewParm->getType(),
3100                                             /*CompareUnqualified=*/true)) {
3101         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3102                                            NewProto->getParamType(Idx) };
3103         Warnings.push_back(Warn);
3104         ArgTypes.push_back(NewParm->getType());
3105       } else
3106         LooseCompatible = false;
3107     }
3108 
3109     if (LooseCompatible) {
3110       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3111         Diag(Warnings[Warn].NewParm->getLocation(),
3112              diag::ext_param_promoted_not_compatible_with_prototype)
3113           << Warnings[Warn].PromotedType
3114           << Warnings[Warn].OldParm->getType();
3115         if (Warnings[Warn].OldParm->getLocation().isValid())
3116           Diag(Warnings[Warn].OldParm->getLocation(),
3117                diag::note_previous_declaration);
3118       }
3119 
3120       if (MergeTypeWithOld)
3121         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3122                                              OldProto->getExtProtoInfo()));
3123       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3124     }
3125 
3126     // Fall through to diagnose conflicting types.
3127   }
3128 
3129   // A function that has already been declared has been redeclared or
3130   // defined with a different type; show an appropriate diagnostic.
3131 
3132   // If the previous declaration was an implicitly-generated builtin
3133   // declaration, then at the very least we should use a specialized note.
3134   unsigned BuiltinID;
3135   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3136     // If it's actually a library-defined builtin function like 'malloc'
3137     // or 'printf', just warn about the incompatible redeclaration.
3138     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3139       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3140       Diag(OldLocation, diag::note_previous_builtin_declaration)
3141         << Old << Old->getType();
3142 
3143       // If this is a global redeclaration, just forget hereafter
3144       // about the "builtin-ness" of the function.
3145       //
3146       // Doing this for local extern declarations is problematic.  If
3147       // the builtin declaration remains visible, a second invalid
3148       // local declaration will produce a hard error; if it doesn't
3149       // remain visible, a single bogus local redeclaration (which is
3150       // actually only a warning) could break all the downstream code.
3151       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3152         New->getIdentifier()->revertBuiltin();
3153 
3154       return false;
3155     }
3156 
3157     PrevDiag = diag::note_previous_builtin_declaration;
3158   }
3159 
3160   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3161   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3162   return true;
3163 }
3164 
3165 /// \brief Completes the merge of two function declarations that are
3166 /// known to be compatible.
3167 ///
3168 /// This routine handles the merging of attributes and other
3169 /// properties of function declarations from the old declaration to
3170 /// the new declaration, once we know that New is in fact a
3171 /// redeclaration of Old.
3172 ///
3173 /// \returns false
3174 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3175                                         Scope *S, bool MergeTypeWithOld) {
3176   // Merge the attributes
3177   mergeDeclAttributes(New, Old);
3178 
3179   // Merge "pure" flag.
3180   if (Old->isPure())
3181     New->setPure();
3182 
3183   // Merge "used" flag.
3184   if (Old->getMostRecentDecl()->isUsed(false))
3185     New->setIsUsed();
3186 
3187   // Merge attributes from the parameters.  These can mismatch with K&R
3188   // declarations.
3189   if (New->getNumParams() == Old->getNumParams())
3190       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3191         ParmVarDecl *NewParam = New->getParamDecl(i);
3192         ParmVarDecl *OldParam = Old->getParamDecl(i);
3193         mergeParamDeclAttributes(NewParam, OldParam, *this);
3194         mergeParamDeclTypes(NewParam, OldParam, *this);
3195       }
3196 
3197   if (getLangOpts().CPlusPlus)
3198     return MergeCXXFunctionDecl(New, Old, S);
3199 
3200   // Merge the function types so the we get the composite types for the return
3201   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3202   // was visible.
3203   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3204   if (!Merged.isNull() && MergeTypeWithOld)
3205     New->setType(Merged);
3206 
3207   return false;
3208 }
3209 
3210 
3211 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3212                                 ObjCMethodDecl *oldMethod) {
3213 
3214   // Merge the attributes, including deprecated/unavailable
3215   AvailabilityMergeKind MergeKind =
3216     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3217       ? AMK_ProtocolImplementation
3218       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3219                                                        : AMK_Override;
3220 
3221   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3222 
3223   // Merge attributes from the parameters.
3224   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3225                                        oe = oldMethod->param_end();
3226   for (ObjCMethodDecl::param_iterator
3227          ni = newMethod->param_begin(), ne = newMethod->param_end();
3228        ni != ne && oi != oe; ++ni, ++oi)
3229     mergeParamDeclAttributes(*ni, *oi, *this);
3230 
3231   CheckObjCMethodOverride(newMethod, oldMethod);
3232 }
3233 
3234 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3235 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3236 /// emitting diagnostics as appropriate.
3237 ///
3238 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3239 /// to here in AddInitializerToDecl. We can't check them before the initializer
3240 /// is attached.
3241 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3242                              bool MergeTypeWithOld) {
3243   if (New->isInvalidDecl() || Old->isInvalidDecl())
3244     return;
3245 
3246   QualType MergedT;
3247   if (getLangOpts().CPlusPlus) {
3248     if (New->getType()->isUndeducedType()) {
3249       // We don't know what the new type is until the initializer is attached.
3250       return;
3251     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3252       // These could still be something that needs exception specs checked.
3253       return MergeVarDeclExceptionSpecs(New, Old);
3254     }
3255     // C++ [basic.link]p10:
3256     //   [...] the types specified by all declarations referring to a given
3257     //   object or function shall be identical, except that declarations for an
3258     //   array object can specify array types that differ by the presence or
3259     //   absence of a major array bound (8.3.4).
3260     else if (Old->getType()->isIncompleteArrayType() &&
3261              New->getType()->isArrayType()) {
3262       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3263       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3264       if (Context.hasSameType(OldArray->getElementType(),
3265                               NewArray->getElementType()))
3266         MergedT = New->getType();
3267     } else if (Old->getType()->isArrayType() &&
3268                New->getType()->isIncompleteArrayType()) {
3269       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3270       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3271       if (Context.hasSameType(OldArray->getElementType(),
3272                               NewArray->getElementType()))
3273         MergedT = Old->getType();
3274     } else if (New->getType()->isObjCObjectPointerType() &&
3275                Old->getType()->isObjCObjectPointerType()) {
3276       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3277                                               Old->getType());
3278     }
3279   } else {
3280     // C 6.2.7p2:
3281     //   All declarations that refer to the same object or function shall have
3282     //   compatible type.
3283     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3284   }
3285   if (MergedT.isNull()) {
3286     // It's OK if we couldn't merge types if either type is dependent, for a
3287     // block-scope variable. In other cases (static data members of class
3288     // templates, variable templates, ...), we require the types to be
3289     // equivalent.
3290     // FIXME: The C++ standard doesn't say anything about this.
3291     if ((New->getType()->isDependentType() ||
3292          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3293       // If the old type was dependent, we can't merge with it, so the new type
3294       // becomes dependent for now. We'll reproduce the original type when we
3295       // instantiate the TypeSourceInfo for the variable.
3296       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3297         New->setType(Context.DependentTy);
3298       return;
3299     }
3300 
3301     // FIXME: Even if this merging succeeds, some other non-visible declaration
3302     // of this variable might have an incompatible type. For instance:
3303     //
3304     //   extern int arr[];
3305     //   void f() { extern int arr[2]; }
3306     //   void g() { extern int arr[3]; }
3307     //
3308     // Neither C nor C++ requires a diagnostic for this, but we should still try
3309     // to diagnose it.
3310     Diag(New->getLocation(), New->isThisDeclarationADefinition()
3311                                  ? diag::err_redefinition_different_type
3312                                  : diag::err_redeclaration_different_type)
3313         << New->getDeclName() << New->getType() << Old->getType();
3314 
3315     diag::kind PrevDiag;
3316     SourceLocation OldLocation;
3317     std::tie(PrevDiag, OldLocation) =
3318         getNoteDiagForInvalidRedeclaration(Old, New);
3319     Diag(OldLocation, PrevDiag);
3320     return New->setInvalidDecl();
3321   }
3322 
3323   // Don't actually update the type on the new declaration if the old
3324   // declaration was an extern declaration in a different scope.
3325   if (MergeTypeWithOld)
3326     New->setType(MergedT);
3327 }
3328 
3329 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3330                                   LookupResult &Previous) {
3331   // C11 6.2.7p4:
3332   //   For an identifier with internal or external linkage declared
3333   //   in a scope in which a prior declaration of that identifier is
3334   //   visible, if the prior declaration specifies internal or
3335   //   external linkage, the type of the identifier at the later
3336   //   declaration becomes the composite type.
3337   //
3338   // If the variable isn't visible, we do not merge with its type.
3339   if (Previous.isShadowed())
3340     return false;
3341 
3342   if (S.getLangOpts().CPlusPlus) {
3343     // C++11 [dcl.array]p3:
3344     //   If there is a preceding declaration of the entity in the same
3345     //   scope in which the bound was specified, an omitted array bound
3346     //   is taken to be the same as in that earlier declaration.
3347     return NewVD->isPreviousDeclInSameBlockScope() ||
3348            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3349             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3350   } else {
3351     // If the old declaration was function-local, don't merge with its
3352     // type unless we're in the same function.
3353     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3354            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3355   }
3356 }
3357 
3358 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3359 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3360 /// situation, merging decls or emitting diagnostics as appropriate.
3361 ///
3362 /// Tentative definition rules (C99 6.9.2p2) are checked by
3363 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3364 /// definitions here, since the initializer hasn't been attached.
3365 ///
3366 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3367   // If the new decl is already invalid, don't do any other checking.
3368   if (New->isInvalidDecl())
3369     return;
3370 
3371   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3372     return;
3373 
3374   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3375 
3376   // Verify the old decl was also a variable or variable template.
3377   VarDecl *Old = nullptr;
3378   VarTemplateDecl *OldTemplate = nullptr;
3379   if (Previous.isSingleResult()) {
3380     if (NewTemplate) {
3381       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3382       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3383 
3384       if (auto *Shadow =
3385               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3386         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3387           return New->setInvalidDecl();
3388     } else {
3389       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3390 
3391       if (auto *Shadow =
3392               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3393         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3394           return New->setInvalidDecl();
3395     }
3396   }
3397   if (!Old) {
3398     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3399       << New->getDeclName();
3400     Diag(Previous.getRepresentativeDecl()->getLocation(),
3401          diag::note_previous_definition);
3402     return New->setInvalidDecl();
3403   }
3404 
3405   // Ensure the template parameters are compatible.
3406   if (NewTemplate &&
3407       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3408                                       OldTemplate->getTemplateParameters(),
3409                                       /*Complain=*/true, TPL_TemplateMatch))
3410     return New->setInvalidDecl();
3411 
3412   // C++ [class.mem]p1:
3413   //   A member shall not be declared twice in the member-specification [...]
3414   //
3415   // Here, we need only consider static data members.
3416   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3417     Diag(New->getLocation(), diag::err_duplicate_member)
3418       << New->getIdentifier();
3419     Diag(Old->getLocation(), diag::note_previous_declaration);
3420     New->setInvalidDecl();
3421   }
3422 
3423   mergeDeclAttributes(New, Old);
3424   // Warn if an already-declared variable is made a weak_import in a subsequent
3425   // declaration
3426   if (New->hasAttr<WeakImportAttr>() &&
3427       Old->getStorageClass() == SC_None &&
3428       !Old->hasAttr<WeakImportAttr>()) {
3429     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3430     Diag(Old->getLocation(), diag::note_previous_definition);
3431     // Remove weak_import attribute on new declaration.
3432     New->dropAttr<WeakImportAttr>();
3433   }
3434 
3435   if (New->hasAttr<InternalLinkageAttr>() &&
3436       !Old->hasAttr<InternalLinkageAttr>()) {
3437     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3438         << New->getDeclName();
3439     Diag(Old->getLocation(), diag::note_previous_definition);
3440     New->dropAttr<InternalLinkageAttr>();
3441   }
3442 
3443   // Merge the types.
3444   VarDecl *MostRecent = Old->getMostRecentDecl();
3445   if (MostRecent != Old) {
3446     MergeVarDeclTypes(New, MostRecent,
3447                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3448     if (New->isInvalidDecl())
3449       return;
3450   }
3451 
3452   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3453   if (New->isInvalidDecl())
3454     return;
3455 
3456   diag::kind PrevDiag;
3457   SourceLocation OldLocation;
3458   std::tie(PrevDiag, OldLocation) =
3459       getNoteDiagForInvalidRedeclaration(Old, New);
3460 
3461   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3462   if (New->getStorageClass() == SC_Static &&
3463       !New->isStaticDataMember() &&
3464       Old->hasExternalFormalLinkage()) {
3465     if (getLangOpts().MicrosoftExt) {
3466       Diag(New->getLocation(), diag::ext_static_non_static)
3467           << New->getDeclName();
3468       Diag(OldLocation, PrevDiag);
3469     } else {
3470       Diag(New->getLocation(), diag::err_static_non_static)
3471           << New->getDeclName();
3472       Diag(OldLocation, PrevDiag);
3473       return New->setInvalidDecl();
3474     }
3475   }
3476   // C99 6.2.2p4:
3477   //   For an identifier declared with the storage-class specifier
3478   //   extern in a scope in which a prior declaration of that
3479   //   identifier is visible,23) if the prior declaration specifies
3480   //   internal or external linkage, the linkage of the identifier at
3481   //   the later declaration is the same as the linkage specified at
3482   //   the prior declaration. If no prior declaration is visible, or
3483   //   if the prior declaration specifies no linkage, then the
3484   //   identifier has external linkage.
3485   if (New->hasExternalStorage() && Old->hasLinkage())
3486     /* Okay */;
3487   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3488            !New->isStaticDataMember() &&
3489            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3490     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3491     Diag(OldLocation, PrevDiag);
3492     return New->setInvalidDecl();
3493   }
3494 
3495   // Check if extern is followed by non-extern and vice-versa.
3496   if (New->hasExternalStorage() &&
3497       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3498     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3499     Diag(OldLocation, PrevDiag);
3500     return New->setInvalidDecl();
3501   }
3502   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3503       !New->hasExternalStorage()) {
3504     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3505     Diag(OldLocation, PrevDiag);
3506     return New->setInvalidDecl();
3507   }
3508 
3509   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3510 
3511   // FIXME: The test for external storage here seems wrong? We still
3512   // need to check for mismatches.
3513   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3514       // Don't complain about out-of-line definitions of static members.
3515       !(Old->getLexicalDeclContext()->isRecord() &&
3516         !New->getLexicalDeclContext()->isRecord())) {
3517     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3518     Diag(OldLocation, PrevDiag);
3519     return New->setInvalidDecl();
3520   }
3521 
3522   if (New->getTLSKind() != Old->getTLSKind()) {
3523     if (!Old->getTLSKind()) {
3524       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3525       Diag(OldLocation, PrevDiag);
3526     } else if (!New->getTLSKind()) {
3527       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3528       Diag(OldLocation, PrevDiag);
3529     } else {
3530       // Do not allow redeclaration to change the variable between requiring
3531       // static and dynamic initialization.
3532       // FIXME: GCC allows this, but uses the TLS keyword on the first
3533       // declaration to determine the kind. Do we need to be compatible here?
3534       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3535         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3536       Diag(OldLocation, PrevDiag);
3537     }
3538   }
3539 
3540   // C++ doesn't have tentative definitions, so go right ahead and check here.
3541   VarDecl *Def;
3542   if (getLangOpts().CPlusPlus &&
3543       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3544       (Def = Old->getDefinition())) {
3545     NamedDecl *Hidden = nullptr;
3546     if (!hasVisibleDefinition(Def, &Hidden) &&
3547         (New->getFormalLinkage() == InternalLinkage ||
3548          New->getDescribedVarTemplate() ||
3549          New->getNumTemplateParameterLists() ||
3550          New->getDeclContext()->isDependentContext())) {
3551       // The previous definition is hidden, and multiple definitions are
3552       // permitted (in separate TUs). Form another definition of it.
3553     } else {
3554       Diag(New->getLocation(), diag::err_redefinition) << New;
3555       Diag(Def->getLocation(), diag::note_previous_definition);
3556       New->setInvalidDecl();
3557       return;
3558     }
3559   }
3560 
3561   if (haveIncompatibleLanguageLinkages(Old, New)) {
3562     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3563     Diag(OldLocation, PrevDiag);
3564     New->setInvalidDecl();
3565     return;
3566   }
3567 
3568   // Merge "used" flag.
3569   if (Old->getMostRecentDecl()->isUsed(false))
3570     New->setIsUsed();
3571 
3572   // Keep a chain of previous declarations.
3573   New->setPreviousDecl(Old);
3574   if (NewTemplate)
3575     NewTemplate->setPreviousDecl(OldTemplate);
3576 
3577   // Inherit access appropriately.
3578   New->setAccess(Old->getAccess());
3579   if (NewTemplate)
3580     NewTemplate->setAccess(New->getAccess());
3581 }
3582 
3583 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3584 /// no declarator (e.g. "struct foo;") is parsed.
3585 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3586                                        DeclSpec &DS) {
3587   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3588 }
3589 
3590 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3591 // disambiguate entities defined in different scopes.
3592 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3593 // compatibility.
3594 // We will pick our mangling number depending on which version of MSVC is being
3595 // targeted.
3596 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3597   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3598              ? S->getMSCurManglingNumber()
3599              : S->getMSLastManglingNumber();
3600 }
3601 
3602 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3603   if (!Context.getLangOpts().CPlusPlus)
3604     return;
3605 
3606   if (isa<CXXRecordDecl>(Tag->getParent())) {
3607     // If this tag is the direct child of a class, number it if
3608     // it is anonymous.
3609     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3610       return;
3611     MangleNumberingContext &MCtx =
3612         Context.getManglingNumberContext(Tag->getParent());
3613     Context.setManglingNumber(
3614         Tag, MCtx.getManglingNumber(
3615                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3616     return;
3617   }
3618 
3619   // If this tag isn't a direct child of a class, number it if it is local.
3620   Decl *ManglingContextDecl;
3621   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3622           Tag->getDeclContext(), ManglingContextDecl)) {
3623     Context.setManglingNumber(
3624         Tag, MCtx->getManglingNumber(
3625                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3626   }
3627 }
3628 
3629 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3630                                         TypedefNameDecl *NewTD) {
3631   if (TagFromDeclSpec->isInvalidDecl())
3632     return;
3633 
3634   // Do nothing if the tag already has a name for linkage purposes.
3635   if (TagFromDeclSpec->hasNameForLinkage())
3636     return;
3637 
3638   // A well-formed anonymous tag must always be a TUK_Definition.
3639   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3640 
3641   // The type must match the tag exactly;  no qualifiers allowed.
3642   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3643                            Context.getTagDeclType(TagFromDeclSpec))) {
3644     if (getLangOpts().CPlusPlus)
3645       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3646     return;
3647   }
3648 
3649   // If we've already computed linkage for the anonymous tag, then
3650   // adding a typedef name for the anonymous decl can change that
3651   // linkage, which might be a serious problem.  Diagnose this as
3652   // unsupported and ignore the typedef name.  TODO: we should
3653   // pursue this as a language defect and establish a formal rule
3654   // for how to handle it.
3655   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3656     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3657 
3658     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3659     tagLoc = getLocForEndOfToken(tagLoc);
3660 
3661     llvm::SmallString<40> textToInsert;
3662     textToInsert += ' ';
3663     textToInsert += NewTD->getIdentifier()->getName();
3664     Diag(tagLoc, diag::note_typedef_changes_linkage)
3665         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3666     return;
3667   }
3668 
3669   // Otherwise, set this is the anon-decl typedef for the tag.
3670   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3671 }
3672 
3673 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3674   switch (T) {
3675   case DeclSpec::TST_class:
3676     return 0;
3677   case DeclSpec::TST_struct:
3678     return 1;
3679   case DeclSpec::TST_interface:
3680     return 2;
3681   case DeclSpec::TST_union:
3682     return 3;
3683   case DeclSpec::TST_enum:
3684     return 4;
3685   default:
3686     llvm_unreachable("unexpected type specifier");
3687   }
3688 }
3689 
3690 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3691 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3692 /// parameters to cope with template friend declarations.
3693 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3694                                        DeclSpec &DS,
3695                                        MultiTemplateParamsArg TemplateParams,
3696                                        bool IsExplicitInstantiation) {
3697   Decl *TagD = nullptr;
3698   TagDecl *Tag = nullptr;
3699   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3700       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3701       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3702       DS.getTypeSpecType() == DeclSpec::TST_union ||
3703       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3704     TagD = DS.getRepAsDecl();
3705 
3706     if (!TagD) // We probably had an error
3707       return nullptr;
3708 
3709     // Note that the above type specs guarantee that the
3710     // type rep is a Decl, whereas in many of the others
3711     // it's a Type.
3712     if (isa<TagDecl>(TagD))
3713       Tag = cast<TagDecl>(TagD);
3714     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3715       Tag = CTD->getTemplatedDecl();
3716   }
3717 
3718   if (Tag) {
3719     handleTagNumbering(Tag, S);
3720     Tag->setFreeStanding();
3721     if (Tag->isInvalidDecl())
3722       return Tag;
3723   }
3724 
3725   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3726     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3727     // or incomplete types shall not be restrict-qualified."
3728     if (TypeQuals & DeclSpec::TQ_restrict)
3729       Diag(DS.getRestrictSpecLoc(),
3730            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3731            << DS.getSourceRange();
3732   }
3733 
3734   if (DS.isConstexprSpecified()) {
3735     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3736     // and definitions of functions and variables.
3737     if (Tag)
3738       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3739           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3740     else
3741       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3742     // Don't emit warnings after this error.
3743     return TagD;
3744   }
3745 
3746   if (DS.isConceptSpecified()) {
3747     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3748     // either a function concept and its definition or a variable concept and
3749     // its initializer.
3750     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3751     return TagD;
3752   }
3753 
3754   DiagnoseFunctionSpecifiers(DS);
3755 
3756   if (DS.isFriendSpecified()) {
3757     // If we're dealing with a decl but not a TagDecl, assume that
3758     // whatever routines created it handled the friendship aspect.
3759     if (TagD && !Tag)
3760       return nullptr;
3761     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3762   }
3763 
3764   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3765   bool IsExplicitSpecialization =
3766     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3767   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3768       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3769     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3770     // nested-name-specifier unless it is an explicit instantiation
3771     // or an explicit specialization.
3772     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3773     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3774         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3775     return nullptr;
3776   }
3777 
3778   // Track whether this decl-specifier declares anything.
3779   bool DeclaresAnything = true;
3780 
3781   // Handle anonymous struct definitions.
3782   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3783     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3784         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3785       if (getLangOpts().CPlusPlus ||
3786           Record->getDeclContext()->isRecord())
3787         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3788                                            Context.getPrintingPolicy());
3789 
3790       DeclaresAnything = false;
3791     }
3792   }
3793 
3794   // C11 6.7.2.1p2:
3795   //   A struct-declaration that does not declare an anonymous structure or
3796   //   anonymous union shall contain a struct-declarator-list.
3797   //
3798   // This rule also existed in C89 and C99; the grammar for struct-declaration
3799   // did not permit a struct-declaration without a struct-declarator-list.
3800   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3801       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3802     // Check for Microsoft C extension: anonymous struct/union member.
3803     // Handle 2 kinds of anonymous struct/union:
3804     //   struct STRUCT;
3805     //   union UNION;
3806     // and
3807     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3808     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3809     if ((Tag && Tag->getDeclName()) ||
3810         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3811       RecordDecl *Record = nullptr;
3812       if (Tag)
3813         Record = dyn_cast<RecordDecl>(Tag);
3814       else if (const RecordType *RT =
3815                    DS.getRepAsType().get()->getAsStructureType())
3816         Record = RT->getDecl();
3817       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3818         Record = UT->getDecl();
3819 
3820       if (Record && getLangOpts().MicrosoftExt) {
3821         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3822           << Record->isUnion() << DS.getSourceRange();
3823         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3824       }
3825 
3826       DeclaresAnything = false;
3827     }
3828   }
3829 
3830   // Skip all the checks below if we have a type error.
3831   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3832       (TagD && TagD->isInvalidDecl()))
3833     return TagD;
3834 
3835   if (getLangOpts().CPlusPlus &&
3836       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3837     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3838       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3839           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3840         DeclaresAnything = false;
3841 
3842   if (!DS.isMissingDeclaratorOk()) {
3843     // Customize diagnostic for a typedef missing a name.
3844     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3845       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3846         << DS.getSourceRange();
3847     else
3848       DeclaresAnything = false;
3849   }
3850 
3851   if (DS.isModulePrivateSpecified() &&
3852       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3853     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3854       << Tag->getTagKind()
3855       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3856 
3857   ActOnDocumentableDecl(TagD);
3858 
3859   // C 6.7/2:
3860   //   A declaration [...] shall declare at least a declarator [...], a tag,
3861   //   or the members of an enumeration.
3862   // C++ [dcl.dcl]p3:
3863   //   [If there are no declarators], and except for the declaration of an
3864   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3865   //   names into the program, or shall redeclare a name introduced by a
3866   //   previous declaration.
3867   if (!DeclaresAnything) {
3868     // In C, we allow this as a (popular) extension / bug. Don't bother
3869     // producing further diagnostics for redundant qualifiers after this.
3870     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3871     return TagD;
3872   }
3873 
3874   // C++ [dcl.stc]p1:
3875   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3876   //   init-declarator-list of the declaration shall not be empty.
3877   // C++ [dcl.fct.spec]p1:
3878   //   If a cv-qualifier appears in a decl-specifier-seq, the
3879   //   init-declarator-list of the declaration shall not be empty.
3880   //
3881   // Spurious qualifiers here appear to be valid in C.
3882   unsigned DiagID = diag::warn_standalone_specifier;
3883   if (getLangOpts().CPlusPlus)
3884     DiagID = diag::ext_standalone_specifier;
3885 
3886   // Note that a linkage-specification sets a storage class, but
3887   // 'extern "C" struct foo;' is actually valid and not theoretically
3888   // useless.
3889   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3890     if (SCS == DeclSpec::SCS_mutable)
3891       // Since mutable is not a viable storage class specifier in C, there is
3892       // no reason to treat it as an extension. Instead, diagnose as an error.
3893       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3894     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3895       Diag(DS.getStorageClassSpecLoc(), DiagID)
3896         << DeclSpec::getSpecifierName(SCS);
3897   }
3898 
3899   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3900     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3901       << DeclSpec::getSpecifierName(TSCS);
3902   if (DS.getTypeQualifiers()) {
3903     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3904       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3905     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3906       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3907     // Restrict is covered above.
3908     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3909       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3910   }
3911 
3912   // Warn about ignored type attributes, for example:
3913   // __attribute__((aligned)) struct A;
3914   // Attributes should be placed after tag to apply to type declaration.
3915   if (!DS.getAttributes().empty()) {
3916     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3917     if (TypeSpecType == DeclSpec::TST_class ||
3918         TypeSpecType == DeclSpec::TST_struct ||
3919         TypeSpecType == DeclSpec::TST_interface ||
3920         TypeSpecType == DeclSpec::TST_union ||
3921         TypeSpecType == DeclSpec::TST_enum) {
3922       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3923            attrs = attrs->getNext())
3924         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3925             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3926     }
3927   }
3928 
3929   return TagD;
3930 }
3931 
3932 /// We are trying to inject an anonymous member into the given scope;
3933 /// check if there's an existing declaration that can't be overloaded.
3934 ///
3935 /// \return true if this is a forbidden redeclaration
3936 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3937                                          Scope *S,
3938                                          DeclContext *Owner,
3939                                          DeclarationName Name,
3940                                          SourceLocation NameLoc,
3941                                          bool IsUnion) {
3942   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3943                  Sema::ForRedeclaration);
3944   if (!SemaRef.LookupName(R, S)) return false;
3945 
3946   if (R.getAsSingle<TagDecl>())
3947     return false;
3948 
3949   // Pick a representative declaration.
3950   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3951   assert(PrevDecl && "Expected a non-null Decl");
3952 
3953   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3954     return false;
3955 
3956   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3957     << IsUnion << Name;
3958   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3959 
3960   return true;
3961 }
3962 
3963 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3964 /// anonymous struct or union AnonRecord into the owning context Owner
3965 /// and scope S. This routine will be invoked just after we realize
3966 /// that an unnamed union or struct is actually an anonymous union or
3967 /// struct, e.g.,
3968 ///
3969 /// @code
3970 /// union {
3971 ///   int i;
3972 ///   float f;
3973 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3974 ///    // f into the surrounding scope.x
3975 /// @endcode
3976 ///
3977 /// This routine is recursive, injecting the names of nested anonymous
3978 /// structs/unions into the owning context and scope as well.
3979 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3980                                          DeclContext *Owner,
3981                                          RecordDecl *AnonRecord,
3982                                          AccessSpecifier AS,
3983                                          SmallVectorImpl<NamedDecl *> &Chaining,
3984                                          bool MSAnonStruct) {
3985   bool Invalid = false;
3986 
3987   // Look every FieldDecl and IndirectFieldDecl with a name.
3988   for (auto *D : AnonRecord->decls()) {
3989     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3990         cast<NamedDecl>(D)->getDeclName()) {
3991       ValueDecl *VD = cast<ValueDecl>(D);
3992       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3993                                        VD->getLocation(),
3994                                        AnonRecord->isUnion())) {
3995         // C++ [class.union]p2:
3996         //   The names of the members of an anonymous union shall be
3997         //   distinct from the names of any other entity in the
3998         //   scope in which the anonymous union is declared.
3999         Invalid = true;
4000       } else {
4001         // C++ [class.union]p2:
4002         //   For the purpose of name lookup, after the anonymous union
4003         //   definition, the members of the anonymous union are
4004         //   considered to have been defined in the scope in which the
4005         //   anonymous union is declared.
4006         unsigned OldChainingSize = Chaining.size();
4007         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4008           Chaining.append(IF->chain_begin(), IF->chain_end());
4009         else
4010           Chaining.push_back(VD);
4011 
4012         assert(Chaining.size() >= 2);
4013         NamedDecl **NamedChain =
4014           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4015         for (unsigned i = 0; i < Chaining.size(); i++)
4016           NamedChain[i] = Chaining[i];
4017 
4018         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4019             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4020             VD->getType(), NamedChain, Chaining.size());
4021 
4022         for (const auto *Attr : VD->attrs())
4023           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4024 
4025         IndirectField->setAccess(AS);
4026         IndirectField->setImplicit();
4027         SemaRef.PushOnScopeChains(IndirectField, S);
4028 
4029         // That includes picking up the appropriate access specifier.
4030         if (AS != AS_none) IndirectField->setAccess(AS);
4031 
4032         Chaining.resize(OldChainingSize);
4033       }
4034     }
4035   }
4036 
4037   return Invalid;
4038 }
4039 
4040 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4041 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4042 /// illegal input values are mapped to SC_None.
4043 static StorageClass
4044 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4045   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4046   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4047          "Parser allowed 'typedef' as storage class VarDecl.");
4048   switch (StorageClassSpec) {
4049   case DeclSpec::SCS_unspecified:    return SC_None;
4050   case DeclSpec::SCS_extern:
4051     if (DS.isExternInLinkageSpec())
4052       return SC_None;
4053     return SC_Extern;
4054   case DeclSpec::SCS_static:         return SC_Static;
4055   case DeclSpec::SCS_auto:           return SC_Auto;
4056   case DeclSpec::SCS_register:       return SC_Register;
4057   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4058     // Illegal SCSs map to None: error reporting is up to the caller.
4059   case DeclSpec::SCS_mutable:        // Fall through.
4060   case DeclSpec::SCS_typedef:        return SC_None;
4061   }
4062   llvm_unreachable("unknown storage class specifier");
4063 }
4064 
4065 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4066   assert(Record->hasInClassInitializer());
4067 
4068   for (const auto *I : Record->decls()) {
4069     const auto *FD = dyn_cast<FieldDecl>(I);
4070     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4071       FD = IFD->getAnonField();
4072     if (FD && FD->hasInClassInitializer())
4073       return FD->getLocation();
4074   }
4075 
4076   llvm_unreachable("couldn't find in-class initializer");
4077 }
4078 
4079 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4080                                       SourceLocation DefaultInitLoc) {
4081   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4082     return;
4083 
4084   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4085   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4086 }
4087 
4088 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4089                                       CXXRecordDecl *AnonUnion) {
4090   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4091     return;
4092 
4093   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4094 }
4095 
4096 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4097 /// anonymous structure or union. Anonymous unions are a C++ feature
4098 /// (C++ [class.union]) and a C11 feature; anonymous structures
4099 /// are a C11 feature and GNU C++ extension.
4100 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4101                                         AccessSpecifier AS,
4102                                         RecordDecl *Record,
4103                                         const PrintingPolicy &Policy) {
4104   DeclContext *Owner = Record->getDeclContext();
4105 
4106   // Diagnose whether this anonymous struct/union is an extension.
4107   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4108     Diag(Record->getLocation(), diag::ext_anonymous_union);
4109   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4110     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4111   else if (!Record->isUnion() && !getLangOpts().C11)
4112     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4113 
4114   // C and C++ require different kinds of checks for anonymous
4115   // structs/unions.
4116   bool Invalid = false;
4117   if (getLangOpts().CPlusPlus) {
4118     const char *PrevSpec = nullptr;
4119     unsigned DiagID;
4120     if (Record->isUnion()) {
4121       // C++ [class.union]p6:
4122       //   Anonymous unions declared in a named namespace or in the
4123       //   global namespace shall be declared static.
4124       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4125           (isa<TranslationUnitDecl>(Owner) ||
4126            (isa<NamespaceDecl>(Owner) &&
4127             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4128         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4129           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4130 
4131         // Recover by adding 'static'.
4132         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4133                                PrevSpec, DiagID, Policy);
4134       }
4135       // C++ [class.union]p6:
4136       //   A storage class is not allowed in a declaration of an
4137       //   anonymous union in a class scope.
4138       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4139                isa<RecordDecl>(Owner)) {
4140         Diag(DS.getStorageClassSpecLoc(),
4141              diag::err_anonymous_union_with_storage_spec)
4142           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4143 
4144         // Recover by removing the storage specifier.
4145         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4146                                SourceLocation(),
4147                                PrevSpec, DiagID, Context.getPrintingPolicy());
4148       }
4149     }
4150 
4151     // Ignore const/volatile/restrict qualifiers.
4152     if (DS.getTypeQualifiers()) {
4153       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4154         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4155           << Record->isUnion() << "const"
4156           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4157       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4158         Diag(DS.getVolatileSpecLoc(),
4159              diag::ext_anonymous_struct_union_qualified)
4160           << Record->isUnion() << "volatile"
4161           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4162       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4163         Diag(DS.getRestrictSpecLoc(),
4164              diag::ext_anonymous_struct_union_qualified)
4165           << Record->isUnion() << "restrict"
4166           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4167       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4168         Diag(DS.getAtomicSpecLoc(),
4169              diag::ext_anonymous_struct_union_qualified)
4170           << Record->isUnion() << "_Atomic"
4171           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4172 
4173       DS.ClearTypeQualifiers();
4174     }
4175 
4176     // C++ [class.union]p2:
4177     //   The member-specification of an anonymous union shall only
4178     //   define non-static data members. [Note: nested types and
4179     //   functions cannot be declared within an anonymous union. ]
4180     for (auto *Mem : Record->decls()) {
4181       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4182         // C++ [class.union]p3:
4183         //   An anonymous union shall not have private or protected
4184         //   members (clause 11).
4185         assert(FD->getAccess() != AS_none);
4186         if (FD->getAccess() != AS_public) {
4187           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4188             << Record->isUnion() << (FD->getAccess() == AS_protected);
4189           Invalid = true;
4190         }
4191 
4192         // C++ [class.union]p1
4193         //   An object of a class with a non-trivial constructor, a non-trivial
4194         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4195         //   assignment operator cannot be a member of a union, nor can an
4196         //   array of such objects.
4197         if (CheckNontrivialField(FD))
4198           Invalid = true;
4199       } else if (Mem->isImplicit()) {
4200         // Any implicit members are fine.
4201       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4202         // This is a type that showed up in an
4203         // elaborated-type-specifier inside the anonymous struct or
4204         // union, but which actually declares a type outside of the
4205         // anonymous struct or union. It's okay.
4206       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4207         if (!MemRecord->isAnonymousStructOrUnion() &&
4208             MemRecord->getDeclName()) {
4209           // Visual C++ allows type definition in anonymous struct or union.
4210           if (getLangOpts().MicrosoftExt)
4211             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4212               << Record->isUnion();
4213           else {
4214             // This is a nested type declaration.
4215             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4216               << Record->isUnion();
4217             Invalid = true;
4218           }
4219         } else {
4220           // This is an anonymous type definition within another anonymous type.
4221           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4222           // not part of standard C++.
4223           Diag(MemRecord->getLocation(),
4224                diag::ext_anonymous_record_with_anonymous_type)
4225             << Record->isUnion();
4226         }
4227       } else if (isa<AccessSpecDecl>(Mem)) {
4228         // Any access specifier is fine.
4229       } else if (isa<StaticAssertDecl>(Mem)) {
4230         // In C++1z, static_assert declarations are also fine.
4231       } else {
4232         // We have something that isn't a non-static data
4233         // member. Complain about it.
4234         unsigned DK = diag::err_anonymous_record_bad_member;
4235         if (isa<TypeDecl>(Mem))
4236           DK = diag::err_anonymous_record_with_type;
4237         else if (isa<FunctionDecl>(Mem))
4238           DK = diag::err_anonymous_record_with_function;
4239         else if (isa<VarDecl>(Mem))
4240           DK = diag::err_anonymous_record_with_static;
4241 
4242         // Visual C++ allows type definition in anonymous struct or union.
4243         if (getLangOpts().MicrosoftExt &&
4244             DK == diag::err_anonymous_record_with_type)
4245           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4246             << Record->isUnion();
4247         else {
4248           Diag(Mem->getLocation(), DK) << Record->isUnion();
4249           Invalid = true;
4250         }
4251       }
4252     }
4253 
4254     // C++11 [class.union]p8 (DR1460):
4255     //   At most one variant member of a union may have a
4256     //   brace-or-equal-initializer.
4257     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4258         Owner->isRecord())
4259       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4260                                 cast<CXXRecordDecl>(Record));
4261   }
4262 
4263   if (!Record->isUnion() && !Owner->isRecord()) {
4264     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4265       << getLangOpts().CPlusPlus;
4266     Invalid = true;
4267   }
4268 
4269   // Mock up a declarator.
4270   Declarator Dc(DS, Declarator::MemberContext);
4271   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4272   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4273 
4274   // Create a declaration for this anonymous struct/union.
4275   NamedDecl *Anon = nullptr;
4276   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4277     Anon = FieldDecl::Create(Context, OwningClass,
4278                              DS.getLocStart(),
4279                              Record->getLocation(),
4280                              /*IdentifierInfo=*/nullptr,
4281                              Context.getTypeDeclType(Record),
4282                              TInfo,
4283                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4284                              /*InitStyle=*/ICIS_NoInit);
4285     Anon->setAccess(AS);
4286     if (getLangOpts().CPlusPlus)
4287       FieldCollector->Add(cast<FieldDecl>(Anon));
4288   } else {
4289     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4290     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4291     if (SCSpec == DeclSpec::SCS_mutable) {
4292       // mutable can only appear on non-static class members, so it's always
4293       // an error here
4294       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4295       Invalid = true;
4296       SC = SC_None;
4297     }
4298 
4299     Anon = VarDecl::Create(Context, Owner,
4300                            DS.getLocStart(),
4301                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4302                            Context.getTypeDeclType(Record),
4303                            TInfo, SC);
4304 
4305     // Default-initialize the implicit variable. This initialization will be
4306     // trivial in almost all cases, except if a union member has an in-class
4307     // initializer:
4308     //   union { int n = 0; };
4309     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4310   }
4311   Anon->setImplicit();
4312 
4313   // Mark this as an anonymous struct/union type.
4314   Record->setAnonymousStructOrUnion(true);
4315 
4316   // Add the anonymous struct/union object to the current
4317   // context. We'll be referencing this object when we refer to one of
4318   // its members.
4319   Owner->addDecl(Anon);
4320 
4321   // Inject the members of the anonymous struct/union into the owning
4322   // context and into the identifier resolver chain for name lookup
4323   // purposes.
4324   SmallVector<NamedDecl*, 2> Chain;
4325   Chain.push_back(Anon);
4326 
4327   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4328                                           Chain, false))
4329     Invalid = true;
4330 
4331   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4332     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4333       Decl *ManglingContextDecl;
4334       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4335               NewVD->getDeclContext(), ManglingContextDecl)) {
4336         Context.setManglingNumber(
4337             NewVD, MCtx->getManglingNumber(
4338                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4339         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4340       }
4341     }
4342   }
4343 
4344   if (Invalid)
4345     Anon->setInvalidDecl();
4346 
4347   return Anon;
4348 }
4349 
4350 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4351 /// Microsoft C anonymous structure.
4352 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4353 /// Example:
4354 ///
4355 /// struct A { int a; };
4356 /// struct B { struct A; int b; };
4357 ///
4358 /// void foo() {
4359 ///   B var;
4360 ///   var.a = 3;
4361 /// }
4362 ///
4363 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4364                                            RecordDecl *Record) {
4365   assert(Record && "expected a record!");
4366 
4367   // Mock up a declarator.
4368   Declarator Dc(DS, Declarator::TypeNameContext);
4369   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4370   assert(TInfo && "couldn't build declarator info for anonymous struct");
4371 
4372   auto *ParentDecl = cast<RecordDecl>(CurContext);
4373   QualType RecTy = Context.getTypeDeclType(Record);
4374 
4375   // Create a declaration for this anonymous struct.
4376   NamedDecl *Anon = FieldDecl::Create(Context,
4377                              ParentDecl,
4378                              DS.getLocStart(),
4379                              DS.getLocStart(),
4380                              /*IdentifierInfo=*/nullptr,
4381                              RecTy,
4382                              TInfo,
4383                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4384                              /*InitStyle=*/ICIS_NoInit);
4385   Anon->setImplicit();
4386 
4387   // Add the anonymous struct object to the current context.
4388   CurContext->addDecl(Anon);
4389 
4390   // Inject the members of the anonymous struct into the current
4391   // context and into the identifier resolver chain for name lookup
4392   // purposes.
4393   SmallVector<NamedDecl*, 2> Chain;
4394   Chain.push_back(Anon);
4395 
4396   RecordDecl *RecordDef = Record->getDefinition();
4397   if (RequireCompleteType(Anon->getLocation(), RecTy,
4398                           diag::err_field_incomplete) ||
4399       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4400                                           AS_none, Chain, true)) {
4401     Anon->setInvalidDecl();
4402     ParentDecl->setInvalidDecl();
4403   }
4404 
4405   return Anon;
4406 }
4407 
4408 /// GetNameForDeclarator - Determine the full declaration name for the
4409 /// given Declarator.
4410 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4411   return GetNameFromUnqualifiedId(D.getName());
4412 }
4413 
4414 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4415 DeclarationNameInfo
4416 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4417   DeclarationNameInfo NameInfo;
4418   NameInfo.setLoc(Name.StartLocation);
4419 
4420   switch (Name.getKind()) {
4421 
4422   case UnqualifiedId::IK_ImplicitSelfParam:
4423   case UnqualifiedId::IK_Identifier:
4424     NameInfo.setName(Name.Identifier);
4425     NameInfo.setLoc(Name.StartLocation);
4426     return NameInfo;
4427 
4428   case UnqualifiedId::IK_OperatorFunctionId:
4429     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4430                                            Name.OperatorFunctionId.Operator));
4431     NameInfo.setLoc(Name.StartLocation);
4432     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4433       = Name.OperatorFunctionId.SymbolLocations[0];
4434     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4435       = Name.EndLocation.getRawEncoding();
4436     return NameInfo;
4437 
4438   case UnqualifiedId::IK_LiteralOperatorId:
4439     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4440                                                            Name.Identifier));
4441     NameInfo.setLoc(Name.StartLocation);
4442     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4443     return NameInfo;
4444 
4445   case UnqualifiedId::IK_ConversionFunctionId: {
4446     TypeSourceInfo *TInfo;
4447     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4448     if (Ty.isNull())
4449       return DeclarationNameInfo();
4450     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4451                                                Context.getCanonicalType(Ty)));
4452     NameInfo.setLoc(Name.StartLocation);
4453     NameInfo.setNamedTypeInfo(TInfo);
4454     return NameInfo;
4455   }
4456 
4457   case UnqualifiedId::IK_ConstructorName: {
4458     TypeSourceInfo *TInfo;
4459     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4460     if (Ty.isNull())
4461       return DeclarationNameInfo();
4462     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4463                                               Context.getCanonicalType(Ty)));
4464     NameInfo.setLoc(Name.StartLocation);
4465     NameInfo.setNamedTypeInfo(TInfo);
4466     return NameInfo;
4467   }
4468 
4469   case UnqualifiedId::IK_ConstructorTemplateId: {
4470     // In well-formed code, we can only have a constructor
4471     // template-id that refers to the current context, so go there
4472     // to find the actual type being constructed.
4473     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4474     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4475       return DeclarationNameInfo();
4476 
4477     // Determine the type of the class being constructed.
4478     QualType CurClassType = Context.getTypeDeclType(CurClass);
4479 
4480     // FIXME: Check two things: that the template-id names the same type as
4481     // CurClassType, and that the template-id does not occur when the name
4482     // was qualified.
4483 
4484     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4485                                     Context.getCanonicalType(CurClassType)));
4486     NameInfo.setLoc(Name.StartLocation);
4487     // FIXME: should we retrieve TypeSourceInfo?
4488     NameInfo.setNamedTypeInfo(nullptr);
4489     return NameInfo;
4490   }
4491 
4492   case UnqualifiedId::IK_DestructorName: {
4493     TypeSourceInfo *TInfo;
4494     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4495     if (Ty.isNull())
4496       return DeclarationNameInfo();
4497     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4498                                               Context.getCanonicalType(Ty)));
4499     NameInfo.setLoc(Name.StartLocation);
4500     NameInfo.setNamedTypeInfo(TInfo);
4501     return NameInfo;
4502   }
4503 
4504   case UnqualifiedId::IK_TemplateId: {
4505     TemplateName TName = Name.TemplateId->Template.get();
4506     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4507     return Context.getNameForTemplate(TName, TNameLoc);
4508   }
4509 
4510   } // switch (Name.getKind())
4511 
4512   llvm_unreachable("Unknown name kind");
4513 }
4514 
4515 static QualType getCoreType(QualType Ty) {
4516   do {
4517     if (Ty->isPointerType() || Ty->isReferenceType())
4518       Ty = Ty->getPointeeType();
4519     else if (Ty->isArrayType())
4520       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4521     else
4522       return Ty.withoutLocalFastQualifiers();
4523   } while (true);
4524 }
4525 
4526 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4527 /// and Definition have "nearly" matching parameters. This heuristic is
4528 /// used to improve diagnostics in the case where an out-of-line function
4529 /// definition doesn't match any declaration within the class or namespace.
4530 /// Also sets Params to the list of indices to the parameters that differ
4531 /// between the declaration and the definition. If hasSimilarParameters
4532 /// returns true and Params is empty, then all of the parameters match.
4533 static bool hasSimilarParameters(ASTContext &Context,
4534                                      FunctionDecl *Declaration,
4535                                      FunctionDecl *Definition,
4536                                      SmallVectorImpl<unsigned> &Params) {
4537   Params.clear();
4538   if (Declaration->param_size() != Definition->param_size())
4539     return false;
4540   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4541     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4542     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4543 
4544     // The parameter types are identical
4545     if (Context.hasSameType(DefParamTy, DeclParamTy))
4546       continue;
4547 
4548     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4549     QualType DefParamBaseTy = getCoreType(DefParamTy);
4550     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4551     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4552 
4553     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4554         (DeclTyName && DeclTyName == DefTyName))
4555       Params.push_back(Idx);
4556     else  // The two parameters aren't even close
4557       return false;
4558   }
4559 
4560   return true;
4561 }
4562 
4563 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4564 /// declarator needs to be rebuilt in the current instantiation.
4565 /// Any bits of declarator which appear before the name are valid for
4566 /// consideration here.  That's specifically the type in the decl spec
4567 /// and the base type in any member-pointer chunks.
4568 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4569                                                     DeclarationName Name) {
4570   // The types we specifically need to rebuild are:
4571   //   - typenames, typeofs, and decltypes
4572   //   - types which will become injected class names
4573   // Of course, we also need to rebuild any type referencing such a
4574   // type.  It's safest to just say "dependent", but we call out a
4575   // few cases here.
4576 
4577   DeclSpec &DS = D.getMutableDeclSpec();
4578   switch (DS.getTypeSpecType()) {
4579   case DeclSpec::TST_typename:
4580   case DeclSpec::TST_typeofType:
4581   case DeclSpec::TST_underlyingType:
4582   case DeclSpec::TST_atomic: {
4583     // Grab the type from the parser.
4584     TypeSourceInfo *TSI = nullptr;
4585     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4586     if (T.isNull() || !T->isDependentType()) break;
4587 
4588     // Make sure there's a type source info.  This isn't really much
4589     // of a waste; most dependent types should have type source info
4590     // attached already.
4591     if (!TSI)
4592       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4593 
4594     // Rebuild the type in the current instantiation.
4595     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4596     if (!TSI) return true;
4597 
4598     // Store the new type back in the decl spec.
4599     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4600     DS.UpdateTypeRep(LocType);
4601     break;
4602   }
4603 
4604   case DeclSpec::TST_decltype:
4605   case DeclSpec::TST_typeofExpr: {
4606     Expr *E = DS.getRepAsExpr();
4607     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4608     if (Result.isInvalid()) return true;
4609     DS.UpdateExprRep(Result.get());
4610     break;
4611   }
4612 
4613   default:
4614     // Nothing to do for these decl specs.
4615     break;
4616   }
4617 
4618   // It doesn't matter what order we do this in.
4619   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4620     DeclaratorChunk &Chunk = D.getTypeObject(I);
4621 
4622     // The only type information in the declarator which can come
4623     // before the declaration name is the base type of a member
4624     // pointer.
4625     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4626       continue;
4627 
4628     // Rebuild the scope specifier in-place.
4629     CXXScopeSpec &SS = Chunk.Mem.Scope();
4630     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4631       return true;
4632   }
4633 
4634   return false;
4635 }
4636 
4637 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4638   D.setFunctionDefinitionKind(FDK_Declaration);
4639   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4640 
4641   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4642       Dcl && Dcl->getDeclContext()->isFileContext())
4643     Dcl->setTopLevelDeclInObjCContainer();
4644 
4645   return Dcl;
4646 }
4647 
4648 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4649 ///   If T is the name of a class, then each of the following shall have a
4650 ///   name different from T:
4651 ///     - every static data member of class T;
4652 ///     - every member function of class T
4653 ///     - every member of class T that is itself a type;
4654 /// \returns true if the declaration name violates these rules.
4655 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4656                                    DeclarationNameInfo NameInfo) {
4657   DeclarationName Name = NameInfo.getName();
4658 
4659   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4660     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4661       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4662       return true;
4663     }
4664 
4665   return false;
4666 }
4667 
4668 /// \brief Diagnose a declaration whose declarator-id has the given
4669 /// nested-name-specifier.
4670 ///
4671 /// \param SS The nested-name-specifier of the declarator-id.
4672 ///
4673 /// \param DC The declaration context to which the nested-name-specifier
4674 /// resolves.
4675 ///
4676 /// \param Name The name of the entity being declared.
4677 ///
4678 /// \param Loc The location of the name of the entity being declared.
4679 ///
4680 /// \returns true if we cannot safely recover from this error, false otherwise.
4681 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4682                                         DeclarationName Name,
4683                                         SourceLocation Loc) {
4684   DeclContext *Cur = CurContext;
4685   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4686     Cur = Cur->getParent();
4687 
4688   // If the user provided a superfluous scope specifier that refers back to the
4689   // class in which the entity is already declared, diagnose and ignore it.
4690   //
4691   // class X {
4692   //   void X::f();
4693   // };
4694   //
4695   // Note, it was once ill-formed to give redundant qualification in all
4696   // contexts, but that rule was removed by DR482.
4697   if (Cur->Equals(DC)) {
4698     if (Cur->isRecord()) {
4699       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4700                                       : diag::err_member_extra_qualification)
4701         << Name << FixItHint::CreateRemoval(SS.getRange());
4702       SS.clear();
4703     } else {
4704       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4705     }
4706     return false;
4707   }
4708 
4709   // Check whether the qualifying scope encloses the scope of the original
4710   // declaration.
4711   if (!Cur->Encloses(DC)) {
4712     if (Cur->isRecord())
4713       Diag(Loc, diag::err_member_qualification)
4714         << Name << SS.getRange();
4715     else if (isa<TranslationUnitDecl>(DC))
4716       Diag(Loc, diag::err_invalid_declarator_global_scope)
4717         << Name << SS.getRange();
4718     else if (isa<FunctionDecl>(Cur))
4719       Diag(Loc, diag::err_invalid_declarator_in_function)
4720         << Name << SS.getRange();
4721     else if (isa<BlockDecl>(Cur))
4722       Diag(Loc, diag::err_invalid_declarator_in_block)
4723         << Name << SS.getRange();
4724     else
4725       Diag(Loc, diag::err_invalid_declarator_scope)
4726       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4727 
4728     return true;
4729   }
4730 
4731   if (Cur->isRecord()) {
4732     // Cannot qualify members within a class.
4733     Diag(Loc, diag::err_member_qualification)
4734       << Name << SS.getRange();
4735     SS.clear();
4736 
4737     // C++ constructors and destructors with incorrect scopes can break
4738     // our AST invariants by having the wrong underlying types. If
4739     // that's the case, then drop this declaration entirely.
4740     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4741          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4742         !Context.hasSameType(Name.getCXXNameType(),
4743                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4744       return true;
4745 
4746     return false;
4747   }
4748 
4749   // C++11 [dcl.meaning]p1:
4750   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4751   //   not begin with a decltype-specifer"
4752   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4753   while (SpecLoc.getPrefix())
4754     SpecLoc = SpecLoc.getPrefix();
4755   if (dyn_cast_or_null<DecltypeType>(
4756         SpecLoc.getNestedNameSpecifier()->getAsType()))
4757     Diag(Loc, diag::err_decltype_in_declarator)
4758       << SpecLoc.getTypeLoc().getSourceRange();
4759 
4760   return false;
4761 }
4762 
4763 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4764                                   MultiTemplateParamsArg TemplateParamLists) {
4765   // TODO: consider using NameInfo for diagnostic.
4766   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4767   DeclarationName Name = NameInfo.getName();
4768 
4769   // All of these full declarators require an identifier.  If it doesn't have
4770   // one, the ParsedFreeStandingDeclSpec action should be used.
4771   if (!Name) {
4772     if (!D.isInvalidType())  // Reject this if we think it is valid.
4773       Diag(D.getDeclSpec().getLocStart(),
4774            diag::err_declarator_need_ident)
4775         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4776     return nullptr;
4777   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4778     return nullptr;
4779 
4780   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4781   // we find one that is.
4782   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4783          (S->getFlags() & Scope::TemplateParamScope) != 0)
4784     S = S->getParent();
4785 
4786   DeclContext *DC = CurContext;
4787   if (D.getCXXScopeSpec().isInvalid())
4788     D.setInvalidType();
4789   else if (D.getCXXScopeSpec().isSet()) {
4790     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4791                                         UPPC_DeclarationQualifier))
4792       return nullptr;
4793 
4794     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4795     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4796     if (!DC || isa<EnumDecl>(DC)) {
4797       // If we could not compute the declaration context, it's because the
4798       // declaration context is dependent but does not refer to a class,
4799       // class template, or class template partial specialization. Complain
4800       // and return early, to avoid the coming semantic disaster.
4801       Diag(D.getIdentifierLoc(),
4802            diag::err_template_qualified_declarator_no_match)
4803         << D.getCXXScopeSpec().getScopeRep()
4804         << D.getCXXScopeSpec().getRange();
4805       return nullptr;
4806     }
4807     bool IsDependentContext = DC->isDependentContext();
4808 
4809     if (!IsDependentContext &&
4810         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4811       return nullptr;
4812 
4813     // If a class is incomplete, do not parse entities inside it.
4814     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4815       Diag(D.getIdentifierLoc(),
4816            diag::err_member_def_undefined_record)
4817         << Name << DC << D.getCXXScopeSpec().getRange();
4818       return nullptr;
4819     }
4820     if (!D.getDeclSpec().isFriendSpecified()) {
4821       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4822                                       Name, D.getIdentifierLoc())) {
4823         if (DC->isRecord())
4824           return nullptr;
4825 
4826         D.setInvalidType();
4827       }
4828     }
4829 
4830     // Check whether we need to rebuild the type of the given
4831     // declaration in the current instantiation.
4832     if (EnteringContext && IsDependentContext &&
4833         TemplateParamLists.size() != 0) {
4834       ContextRAII SavedContext(*this, DC);
4835       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4836         D.setInvalidType();
4837     }
4838   }
4839 
4840   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4841   QualType R = TInfo->getType();
4842 
4843   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4844     // If this is a typedef, we'll end up spewing multiple diagnostics.
4845     // Just return early; it's safer. If this is a function, let the
4846     // "constructor cannot have a return type" diagnostic handle it.
4847     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4848       return nullptr;
4849 
4850   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4851                                       UPPC_DeclarationType))
4852     D.setInvalidType();
4853 
4854   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4855                         ForRedeclaration);
4856 
4857   // See if this is a redefinition of a variable in the same scope.
4858   if (!D.getCXXScopeSpec().isSet()) {
4859     bool IsLinkageLookup = false;
4860     bool CreateBuiltins = false;
4861 
4862     // If the declaration we're planning to build will be a function
4863     // or object with linkage, then look for another declaration with
4864     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4865     //
4866     // If the declaration we're planning to build will be declared with
4867     // external linkage in the translation unit, create any builtin with
4868     // the same name.
4869     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4870       /* Do nothing*/;
4871     else if (CurContext->isFunctionOrMethod() &&
4872              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4873               R->isFunctionType())) {
4874       IsLinkageLookup = true;
4875       CreateBuiltins =
4876           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4877     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4878                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4879       CreateBuiltins = true;
4880 
4881     if (IsLinkageLookup)
4882       Previous.clear(LookupRedeclarationWithLinkage);
4883 
4884     LookupName(Previous, S, CreateBuiltins);
4885   } else { // Something like "int foo::x;"
4886     LookupQualifiedName(Previous, DC);
4887 
4888     // C++ [dcl.meaning]p1:
4889     //   When the declarator-id is qualified, the declaration shall refer to a
4890     //  previously declared member of the class or namespace to which the
4891     //  qualifier refers (or, in the case of a namespace, of an element of the
4892     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4893     //  thereof; [...]
4894     //
4895     // Note that we already checked the context above, and that we do not have
4896     // enough information to make sure that Previous contains the declaration
4897     // we want to match. For example, given:
4898     //
4899     //   class X {
4900     //     void f();
4901     //     void f(float);
4902     //   };
4903     //
4904     //   void X::f(int) { } // ill-formed
4905     //
4906     // In this case, Previous will point to the overload set
4907     // containing the two f's declared in X, but neither of them
4908     // matches.
4909 
4910     // C++ [dcl.meaning]p1:
4911     //   [...] the member shall not merely have been introduced by a
4912     //   using-declaration in the scope of the class or namespace nominated by
4913     //   the nested-name-specifier of the declarator-id.
4914     RemoveUsingDecls(Previous);
4915   }
4916 
4917   if (Previous.isSingleResult() &&
4918       Previous.getFoundDecl()->isTemplateParameter()) {
4919     // Maybe we will complain about the shadowed template parameter.
4920     if (!D.isInvalidType())
4921       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4922                                       Previous.getFoundDecl());
4923 
4924     // Just pretend that we didn't see the previous declaration.
4925     Previous.clear();
4926   }
4927 
4928   // In C++, the previous declaration we find might be a tag type
4929   // (class or enum). In this case, the new declaration will hide the
4930   // tag type. Note that this does does not apply if we're declaring a
4931   // typedef (C++ [dcl.typedef]p4).
4932   if (Previous.isSingleTagDecl() &&
4933       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4934     Previous.clear();
4935 
4936   // Check that there are no default arguments other than in the parameters
4937   // of a function declaration (C++ only).
4938   if (getLangOpts().CPlusPlus)
4939     CheckExtraCXXDefaultArguments(D);
4940 
4941   if (D.getDeclSpec().isConceptSpecified()) {
4942     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4943     // applied only to the definition of a function template or variable
4944     // template, declared in namespace scope
4945     if (!TemplateParamLists.size()) {
4946       Diag(D.getDeclSpec().getConceptSpecLoc(),
4947            diag:: err_concept_wrong_decl_kind);
4948       return nullptr;
4949     }
4950 
4951     if (!DC->getRedeclContext()->isFileContext()) {
4952       Diag(D.getIdentifierLoc(),
4953            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4954       return nullptr;
4955     }
4956   }
4957 
4958   NamedDecl *New;
4959 
4960   bool AddToScope = true;
4961   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4962     if (TemplateParamLists.size()) {
4963       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4964       return nullptr;
4965     }
4966 
4967     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4968   } else if (R->isFunctionType()) {
4969     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4970                                   TemplateParamLists,
4971                                   AddToScope);
4972   } else {
4973     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4974                                   AddToScope);
4975   }
4976 
4977   if (!New)
4978     return nullptr;
4979 
4980   // If this has an identifier and is not an invalid redeclaration or
4981   // function template specialization, add it to the scope stack.
4982   if (New->getDeclName() && AddToScope &&
4983        !(D.isRedeclaration() && New->isInvalidDecl())) {
4984     // Only make a locally-scoped extern declaration visible if it is the first
4985     // declaration of this entity. Qualified lookup for such an entity should
4986     // only find this declaration if there is no visible declaration of it.
4987     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4988     PushOnScopeChains(New, S, AddToContext);
4989     if (!AddToContext)
4990       CurContext->addHiddenDecl(New);
4991   }
4992 
4993   return New;
4994 }
4995 
4996 /// Helper method to turn variable array types into constant array
4997 /// types in certain situations which would otherwise be errors (for
4998 /// GCC compatibility).
4999 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5000                                                     ASTContext &Context,
5001                                                     bool &SizeIsNegative,
5002                                                     llvm::APSInt &Oversized) {
5003   // This method tries to turn a variable array into a constant
5004   // array even when the size isn't an ICE.  This is necessary
5005   // for compatibility with code that depends on gcc's buggy
5006   // constant expression folding, like struct {char x[(int)(char*)2];}
5007   SizeIsNegative = false;
5008   Oversized = 0;
5009 
5010   if (T->isDependentType())
5011     return QualType();
5012 
5013   QualifierCollector Qs;
5014   const Type *Ty = Qs.strip(T);
5015 
5016   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5017     QualType Pointee = PTy->getPointeeType();
5018     QualType FixedType =
5019         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5020                                             Oversized);
5021     if (FixedType.isNull()) return FixedType;
5022     FixedType = Context.getPointerType(FixedType);
5023     return Qs.apply(Context, FixedType);
5024   }
5025   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5026     QualType Inner = PTy->getInnerType();
5027     QualType FixedType =
5028         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5029                                             Oversized);
5030     if (FixedType.isNull()) return FixedType;
5031     FixedType = Context.getParenType(FixedType);
5032     return Qs.apply(Context, FixedType);
5033   }
5034 
5035   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5036   if (!VLATy)
5037     return QualType();
5038   // FIXME: We should probably handle this case
5039   if (VLATy->getElementType()->isVariablyModifiedType())
5040     return QualType();
5041 
5042   llvm::APSInt Res;
5043   if (!VLATy->getSizeExpr() ||
5044       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5045     return QualType();
5046 
5047   // Check whether the array size is negative.
5048   if (Res.isSigned() && Res.isNegative()) {
5049     SizeIsNegative = true;
5050     return QualType();
5051   }
5052 
5053   // Check whether the array is too large to be addressed.
5054   unsigned ActiveSizeBits
5055     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5056                                               Res);
5057   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5058     Oversized = Res;
5059     return QualType();
5060   }
5061 
5062   return Context.getConstantArrayType(VLATy->getElementType(),
5063                                       Res, ArrayType::Normal, 0);
5064 }
5065 
5066 static void
5067 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5068   SrcTL = SrcTL.getUnqualifiedLoc();
5069   DstTL = DstTL.getUnqualifiedLoc();
5070   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5071     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5072     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5073                                       DstPTL.getPointeeLoc());
5074     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5075     return;
5076   }
5077   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5078     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5079     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5080                                       DstPTL.getInnerLoc());
5081     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5082     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5083     return;
5084   }
5085   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5086   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5087   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5088   TypeLoc DstElemTL = DstATL.getElementLoc();
5089   DstElemTL.initializeFullCopy(SrcElemTL);
5090   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5091   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5092   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5093 }
5094 
5095 /// Helper method to turn variable array types into constant array
5096 /// types in certain situations which would otherwise be errors (for
5097 /// GCC compatibility).
5098 static TypeSourceInfo*
5099 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5100                                               ASTContext &Context,
5101                                               bool &SizeIsNegative,
5102                                               llvm::APSInt &Oversized) {
5103   QualType FixedTy
5104     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5105                                           SizeIsNegative, Oversized);
5106   if (FixedTy.isNull())
5107     return nullptr;
5108   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5109   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5110                                     FixedTInfo->getTypeLoc());
5111   return FixedTInfo;
5112 }
5113 
5114 /// \brief Register the given locally-scoped extern "C" declaration so
5115 /// that it can be found later for redeclarations. We include any extern "C"
5116 /// declaration that is not visible in the translation unit here, not just
5117 /// function-scope declarations.
5118 void
5119 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5120   if (!getLangOpts().CPlusPlus &&
5121       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5122     // Don't need to track declarations in the TU in C.
5123     return;
5124 
5125   // Note that we have a locally-scoped external with this name.
5126   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5127 }
5128 
5129 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5130   // FIXME: We can have multiple results via __attribute__((overloadable)).
5131   auto Result = Context.getExternCContextDecl()->lookup(Name);
5132   return Result.empty() ? nullptr : *Result.begin();
5133 }
5134 
5135 /// \brief Diagnose function specifiers on a declaration of an identifier that
5136 /// does not identify a function.
5137 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5138   // FIXME: We should probably indicate the identifier in question to avoid
5139   // confusion for constructs like "inline int a(), b;"
5140   if (DS.isInlineSpecified())
5141     Diag(DS.getInlineSpecLoc(),
5142          diag::err_inline_non_function);
5143 
5144   if (DS.isVirtualSpecified())
5145     Diag(DS.getVirtualSpecLoc(),
5146          diag::err_virtual_non_function);
5147 
5148   if (DS.isExplicitSpecified())
5149     Diag(DS.getExplicitSpecLoc(),
5150          diag::err_explicit_non_function);
5151 
5152   if (DS.isNoreturnSpecified())
5153     Diag(DS.getNoreturnSpecLoc(),
5154          diag::err_noreturn_non_function);
5155 }
5156 
5157 NamedDecl*
5158 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5159                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5160   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5161   if (D.getCXXScopeSpec().isSet()) {
5162     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5163       << D.getCXXScopeSpec().getRange();
5164     D.setInvalidType();
5165     // Pretend we didn't see the scope specifier.
5166     DC = CurContext;
5167     Previous.clear();
5168   }
5169 
5170   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5171 
5172   if (D.getDeclSpec().isConstexprSpecified())
5173     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5174       << 1;
5175   if (D.getDeclSpec().isConceptSpecified())
5176     Diag(D.getDeclSpec().getConceptSpecLoc(),
5177          diag::err_concept_wrong_decl_kind);
5178 
5179   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5180     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5181       << D.getName().getSourceRange();
5182     return nullptr;
5183   }
5184 
5185   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5186   if (!NewTD) return nullptr;
5187 
5188   // Handle attributes prior to checking for duplicates in MergeVarDecl
5189   ProcessDeclAttributes(S, NewTD, D);
5190 
5191   CheckTypedefForVariablyModifiedType(S, NewTD);
5192 
5193   bool Redeclaration = D.isRedeclaration();
5194   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5195   D.setRedeclaration(Redeclaration);
5196   return ND;
5197 }
5198 
5199 void
5200 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5201   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5202   // then it shall have block scope.
5203   // Note that variably modified types must be fixed before merging the decl so
5204   // that redeclarations will match.
5205   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5206   QualType T = TInfo->getType();
5207   if (T->isVariablyModifiedType()) {
5208     getCurFunction()->setHasBranchProtectedScope();
5209 
5210     if (S->getFnParent() == nullptr) {
5211       bool SizeIsNegative;
5212       llvm::APSInt Oversized;
5213       TypeSourceInfo *FixedTInfo =
5214         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5215                                                       SizeIsNegative,
5216                                                       Oversized);
5217       if (FixedTInfo) {
5218         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5219         NewTD->setTypeSourceInfo(FixedTInfo);
5220       } else {
5221         if (SizeIsNegative)
5222           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5223         else if (T->isVariableArrayType())
5224           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5225         else if (Oversized.getBoolValue())
5226           Diag(NewTD->getLocation(), diag::err_array_too_large)
5227             << Oversized.toString(10);
5228         else
5229           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5230         NewTD->setInvalidDecl();
5231       }
5232     }
5233   }
5234 }
5235 
5236 
5237 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5238 /// declares a typedef-name, either using the 'typedef' type specifier or via
5239 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5240 NamedDecl*
5241 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5242                            LookupResult &Previous, bool &Redeclaration) {
5243   // Merge the decl with the existing one if appropriate. If the decl is
5244   // in an outer scope, it isn't the same thing.
5245   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5246                        /*AllowInlineNamespace*/false);
5247   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5248   if (!Previous.empty()) {
5249     Redeclaration = true;
5250     MergeTypedefNameDecl(S, NewTD, Previous);
5251   }
5252 
5253   // If this is the C FILE type, notify the AST context.
5254   if (IdentifierInfo *II = NewTD->getIdentifier())
5255     if (!NewTD->isInvalidDecl() &&
5256         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5257       if (II->isStr("FILE"))
5258         Context.setFILEDecl(NewTD);
5259       else if (II->isStr("jmp_buf"))
5260         Context.setjmp_bufDecl(NewTD);
5261       else if (II->isStr("sigjmp_buf"))
5262         Context.setsigjmp_bufDecl(NewTD);
5263       else if (II->isStr("ucontext_t"))
5264         Context.setucontext_tDecl(NewTD);
5265     }
5266 
5267   return NewTD;
5268 }
5269 
5270 /// \brief Determines whether the given declaration is an out-of-scope
5271 /// previous declaration.
5272 ///
5273 /// This routine should be invoked when name lookup has found a
5274 /// previous declaration (PrevDecl) that is not in the scope where a
5275 /// new declaration by the same name is being introduced. If the new
5276 /// declaration occurs in a local scope, previous declarations with
5277 /// linkage may still be considered previous declarations (C99
5278 /// 6.2.2p4-5, C++ [basic.link]p6).
5279 ///
5280 /// \param PrevDecl the previous declaration found by name
5281 /// lookup
5282 ///
5283 /// \param DC the context in which the new declaration is being
5284 /// declared.
5285 ///
5286 /// \returns true if PrevDecl is an out-of-scope previous declaration
5287 /// for a new delcaration with the same name.
5288 static bool
5289 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5290                                 ASTContext &Context) {
5291   if (!PrevDecl)
5292     return false;
5293 
5294   if (!PrevDecl->hasLinkage())
5295     return false;
5296 
5297   if (Context.getLangOpts().CPlusPlus) {
5298     // C++ [basic.link]p6:
5299     //   If there is a visible declaration of an entity with linkage
5300     //   having the same name and type, ignoring entities declared
5301     //   outside the innermost enclosing namespace scope, the block
5302     //   scope declaration declares that same entity and receives the
5303     //   linkage of the previous declaration.
5304     DeclContext *OuterContext = DC->getRedeclContext();
5305     if (!OuterContext->isFunctionOrMethod())
5306       // This rule only applies to block-scope declarations.
5307       return false;
5308 
5309     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5310     if (PrevOuterContext->isRecord())
5311       // We found a member function: ignore it.
5312       return false;
5313 
5314     // Find the innermost enclosing namespace for the new and
5315     // previous declarations.
5316     OuterContext = OuterContext->getEnclosingNamespaceContext();
5317     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5318 
5319     // The previous declaration is in a different namespace, so it
5320     // isn't the same function.
5321     if (!OuterContext->Equals(PrevOuterContext))
5322       return false;
5323   }
5324 
5325   return true;
5326 }
5327 
5328 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5329   CXXScopeSpec &SS = D.getCXXScopeSpec();
5330   if (!SS.isSet()) return;
5331   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5332 }
5333 
5334 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5335   QualType type = decl->getType();
5336   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5337   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5338     // Various kinds of declaration aren't allowed to be __autoreleasing.
5339     unsigned kind = -1U;
5340     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5341       if (var->hasAttr<BlocksAttr>())
5342         kind = 0; // __block
5343       else if (!var->hasLocalStorage())
5344         kind = 1; // global
5345     } else if (isa<ObjCIvarDecl>(decl)) {
5346       kind = 3; // ivar
5347     } else if (isa<FieldDecl>(decl)) {
5348       kind = 2; // field
5349     }
5350 
5351     if (kind != -1U) {
5352       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5353         << kind;
5354     }
5355   } else if (lifetime == Qualifiers::OCL_None) {
5356     // Try to infer lifetime.
5357     if (!type->isObjCLifetimeType())
5358       return false;
5359 
5360     lifetime = type->getObjCARCImplicitLifetime();
5361     type = Context.getLifetimeQualifiedType(type, lifetime);
5362     decl->setType(type);
5363   }
5364 
5365   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5366     // Thread-local variables cannot have lifetime.
5367     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5368         var->getTLSKind()) {
5369       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5370         << var->getType();
5371       return true;
5372     }
5373   }
5374 
5375   return false;
5376 }
5377 
5378 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5379   // Ensure that an auto decl is deduced otherwise the checks below might cache
5380   // the wrong linkage.
5381   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5382 
5383   // 'weak' only applies to declarations with external linkage.
5384   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5385     if (!ND.isExternallyVisible()) {
5386       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5387       ND.dropAttr<WeakAttr>();
5388     }
5389   }
5390   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5391     if (ND.isExternallyVisible()) {
5392       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5393       ND.dropAttr<WeakRefAttr>();
5394       ND.dropAttr<AliasAttr>();
5395     }
5396   }
5397 
5398   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5399     if (VD->hasInit()) {
5400       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5401         assert(VD->isThisDeclarationADefinition() &&
5402                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5403         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5404         VD->dropAttr<AliasAttr>();
5405       }
5406     }
5407   }
5408 
5409   // 'selectany' only applies to externally visible variable declarations.
5410   // It does not apply to functions.
5411   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5412     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5413       S.Diag(Attr->getLocation(),
5414              diag::err_attribute_selectany_non_extern_data);
5415       ND.dropAttr<SelectAnyAttr>();
5416     }
5417   }
5418 
5419   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5420     // dll attributes require external linkage. Static locals may have external
5421     // linkage but still cannot be explicitly imported or exported.
5422     auto *VD = dyn_cast<VarDecl>(&ND);
5423     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5424       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5425         << &ND << Attr;
5426       ND.setInvalidDecl();
5427     }
5428   }
5429 
5430   // Virtual functions cannot be marked as 'notail'.
5431   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5432     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5433       if (MD->isVirtual()) {
5434         S.Diag(ND.getLocation(),
5435                diag::err_invalid_attribute_on_virtual_function)
5436             << Attr;
5437         ND.dropAttr<NotTailCalledAttr>();
5438       }
5439 }
5440 
5441 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5442                                            NamedDecl *NewDecl,
5443                                            bool IsSpecialization) {
5444   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5445     OldDecl = OldTD->getTemplatedDecl();
5446   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5447     NewDecl = NewTD->getTemplatedDecl();
5448 
5449   if (!OldDecl || !NewDecl)
5450     return;
5451 
5452   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5453   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5454   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5455   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5456 
5457   // dllimport and dllexport are inheritable attributes so we have to exclude
5458   // inherited attribute instances.
5459   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5460                     (NewExportAttr && !NewExportAttr->isInherited());
5461 
5462   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5463   // the only exception being explicit specializations.
5464   // Implicitly generated declarations are also excluded for now because there
5465   // is no other way to switch these to use dllimport or dllexport.
5466   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5467 
5468   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5469     // Allow with a warning for free functions and global variables.
5470     bool JustWarn = false;
5471     if (!OldDecl->isCXXClassMember()) {
5472       auto *VD = dyn_cast<VarDecl>(OldDecl);
5473       if (VD && !VD->getDescribedVarTemplate())
5474         JustWarn = true;
5475       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5476       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5477         JustWarn = true;
5478     }
5479 
5480     // We cannot change a declaration that's been used because IR has already
5481     // been emitted. Dllimported functions will still work though (modulo
5482     // address equality) as they can use the thunk.
5483     if (OldDecl->isUsed())
5484       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5485         JustWarn = false;
5486 
5487     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5488                                : diag::err_attribute_dll_redeclaration;
5489     S.Diag(NewDecl->getLocation(), DiagID)
5490         << NewDecl
5491         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5492     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5493     if (!JustWarn) {
5494       NewDecl->setInvalidDecl();
5495       return;
5496     }
5497   }
5498 
5499   // A redeclaration is not allowed to drop a dllimport attribute, the only
5500   // exceptions being inline function definitions, local extern declarations,
5501   // and qualified friend declarations.
5502   // NB: MSVC converts such a declaration to dllexport.
5503   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5504   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5505     // Ignore static data because out-of-line definitions are diagnosed
5506     // separately.
5507     IsStaticDataMember = VD->isStaticDataMember();
5508   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5509     IsInline = FD->isInlined();
5510     IsQualifiedFriend = FD->getQualifier() &&
5511                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5512   }
5513 
5514   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5515       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5516     S.Diag(NewDecl->getLocation(),
5517            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5518       << NewDecl << OldImportAttr;
5519     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5520     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5521     OldDecl->dropAttr<DLLImportAttr>();
5522     NewDecl->dropAttr<DLLImportAttr>();
5523   } else if (IsInline && OldImportAttr &&
5524              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5525     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5526     OldDecl->dropAttr<DLLImportAttr>();
5527     NewDecl->dropAttr<DLLImportAttr>();
5528     S.Diag(NewDecl->getLocation(),
5529            diag::warn_dllimport_dropped_from_inline_function)
5530         << NewDecl << OldImportAttr;
5531   }
5532 }
5533 
5534 /// Given that we are within the definition of the given function,
5535 /// will that definition behave like C99's 'inline', where the
5536 /// definition is discarded except for optimization purposes?
5537 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5538   // Try to avoid calling GetGVALinkageForFunction.
5539 
5540   // All cases of this require the 'inline' keyword.
5541   if (!FD->isInlined()) return false;
5542 
5543   // This is only possible in C++ with the gnu_inline attribute.
5544   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5545     return false;
5546 
5547   // Okay, go ahead and call the relatively-more-expensive function.
5548 
5549 #ifndef NDEBUG
5550   // AST quite reasonably asserts that it's working on a function
5551   // definition.  We don't really have a way to tell it that we're
5552   // currently defining the function, so just lie to it in +Asserts
5553   // builds.  This is an awful hack.
5554   FD->setLazyBody(1);
5555 #endif
5556 
5557   bool isC99Inline =
5558       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5559 
5560 #ifndef NDEBUG
5561   FD->setLazyBody(0);
5562 #endif
5563 
5564   return isC99Inline;
5565 }
5566 
5567 /// Determine whether a variable is extern "C" prior to attaching
5568 /// an initializer. We can't just call isExternC() here, because that
5569 /// will also compute and cache whether the declaration is externally
5570 /// visible, which might change when we attach the initializer.
5571 ///
5572 /// This can only be used if the declaration is known to not be a
5573 /// redeclaration of an internal linkage declaration.
5574 ///
5575 /// For instance:
5576 ///
5577 ///   auto x = []{};
5578 ///
5579 /// Attaching the initializer here makes this declaration not externally
5580 /// visible, because its type has internal linkage.
5581 ///
5582 /// FIXME: This is a hack.
5583 template<typename T>
5584 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5585   if (S.getLangOpts().CPlusPlus) {
5586     // In C++, the overloadable attribute negates the effects of extern "C".
5587     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5588       return false;
5589 
5590     // So do CUDA's host/device attributes if overloading is enabled.
5591     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5592         (D->template hasAttr<CUDADeviceAttr>() ||
5593          D->template hasAttr<CUDAHostAttr>()))
5594       return false;
5595   }
5596   return D->isExternC();
5597 }
5598 
5599 static bool shouldConsiderLinkage(const VarDecl *VD) {
5600   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5601   if (DC->isFunctionOrMethod())
5602     return VD->hasExternalStorage();
5603   if (DC->isFileContext())
5604     return true;
5605   if (DC->isRecord())
5606     return false;
5607   llvm_unreachable("Unexpected context");
5608 }
5609 
5610 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5611   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5612   if (DC->isFileContext() || DC->isFunctionOrMethod())
5613     return true;
5614   if (DC->isRecord())
5615     return false;
5616   llvm_unreachable("Unexpected context");
5617 }
5618 
5619 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5620                           AttributeList::Kind Kind) {
5621   for (const AttributeList *L = AttrList; L; L = L->getNext())
5622     if (L->getKind() == Kind)
5623       return true;
5624   return false;
5625 }
5626 
5627 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5628                           AttributeList::Kind Kind) {
5629   // Check decl attributes on the DeclSpec.
5630   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5631     return true;
5632 
5633   // Walk the declarator structure, checking decl attributes that were in a type
5634   // position to the decl itself.
5635   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5636     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5637       return true;
5638   }
5639 
5640   // Finally, check attributes on the decl itself.
5641   return hasParsedAttr(S, PD.getAttributes(), Kind);
5642 }
5643 
5644 /// Adjust the \c DeclContext for a function or variable that might be a
5645 /// function-local external declaration.
5646 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5647   if (!DC->isFunctionOrMethod())
5648     return false;
5649 
5650   // If this is a local extern function or variable declared within a function
5651   // template, don't add it into the enclosing namespace scope until it is
5652   // instantiated; it might have a dependent type right now.
5653   if (DC->isDependentContext())
5654     return true;
5655 
5656   // C++11 [basic.link]p7:
5657   //   When a block scope declaration of an entity with linkage is not found to
5658   //   refer to some other declaration, then that entity is a member of the
5659   //   innermost enclosing namespace.
5660   //
5661   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5662   // semantically-enclosing namespace, not a lexically-enclosing one.
5663   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5664     DC = DC->getParent();
5665   return true;
5666 }
5667 
5668 /// \brief Returns true if given declaration has external C language linkage.
5669 static bool isDeclExternC(const Decl *D) {
5670   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5671     return FD->isExternC();
5672   if (const auto *VD = dyn_cast<VarDecl>(D))
5673     return VD->isExternC();
5674 
5675   llvm_unreachable("Unknown type of decl!");
5676 }
5677 
5678 NamedDecl *
5679 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5680                               TypeSourceInfo *TInfo, LookupResult &Previous,
5681                               MultiTemplateParamsArg TemplateParamLists,
5682                               bool &AddToScope) {
5683   QualType R = TInfo->getType();
5684   DeclarationName Name = GetNameForDeclarator(D).getName();
5685 
5686   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5687   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5688 
5689   // dllimport globals without explicit storage class are treated as extern. We
5690   // have to change the storage class this early to get the right DeclContext.
5691   if (SC == SC_None && !DC->isRecord() &&
5692       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5693       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5694     SC = SC_Extern;
5695 
5696   DeclContext *OriginalDC = DC;
5697   bool IsLocalExternDecl = SC == SC_Extern &&
5698                            adjustContextForLocalExternDecl(DC);
5699 
5700   if (getLangOpts().OpenCL) {
5701     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5702     QualType NR = R;
5703     while (NR->isPointerType()) {
5704       if (NR->isFunctionPointerType()) {
5705         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5706         D.setInvalidType();
5707         break;
5708       }
5709       NR = NR->getPointeeType();
5710     }
5711 
5712     if (!getOpenCLOptions().cl_khr_fp16) {
5713       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5714       // half array type (unless the cl_khr_fp16 extension is enabled).
5715       if (Context.getBaseElementType(R)->isHalfType()) {
5716         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5717         D.setInvalidType();
5718       }
5719     }
5720   }
5721 
5722   if (SCSpec == DeclSpec::SCS_mutable) {
5723     // mutable can only appear on non-static class members, so it's always
5724     // an error here
5725     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5726     D.setInvalidType();
5727     SC = SC_None;
5728   }
5729 
5730   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5731       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5732                               D.getDeclSpec().getStorageClassSpecLoc())) {
5733     // In C++11, the 'register' storage class specifier is deprecated.
5734     // Suppress the warning in system macros, it's used in macros in some
5735     // popular C system headers, such as in glibc's htonl() macro.
5736     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5737          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5738                                    : diag::warn_deprecated_register)
5739       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5740   }
5741 
5742   IdentifierInfo *II = Name.getAsIdentifierInfo();
5743   if (!II) {
5744     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5745       << Name;
5746     return nullptr;
5747   }
5748 
5749   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5750 
5751   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5752     // C99 6.9p2: The storage-class specifiers auto and register shall not
5753     // appear in the declaration specifiers in an external declaration.
5754     // Global Register+Asm is a GNU extension we support.
5755     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5756       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5757       D.setInvalidType();
5758     }
5759   }
5760 
5761   if (getLangOpts().OpenCL) {
5762     // OpenCL v1.2 s6.9.b p4:
5763     // The sampler type cannot be used with the __local and __global address
5764     // space qualifiers.
5765     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5766       R.getAddressSpace() == LangAS::opencl_global)) {
5767       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5768     }
5769 
5770     // OpenCL 1.2 spec, p6.9 r:
5771     // The event type cannot be used to declare a program scope variable.
5772     // The event type cannot be used with the __local, __constant and __global
5773     // address space qualifiers.
5774     if (R->isEventT()) {
5775       if (S->getParent() == nullptr) {
5776         Diag(D.getLocStart(), diag::err_event_t_global_var);
5777         D.setInvalidType();
5778       }
5779 
5780       if (R.getAddressSpace()) {
5781         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5782         D.setInvalidType();
5783       }
5784     }
5785   }
5786 
5787   bool IsExplicitSpecialization = false;
5788   bool IsVariableTemplateSpecialization = false;
5789   bool IsPartialSpecialization = false;
5790   bool IsVariableTemplate = false;
5791   VarDecl *NewVD = nullptr;
5792   VarTemplateDecl *NewTemplate = nullptr;
5793   TemplateParameterList *TemplateParams = nullptr;
5794   if (!getLangOpts().CPlusPlus) {
5795     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5796                             D.getIdentifierLoc(), II,
5797                             R, TInfo, SC);
5798 
5799     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5800       ParsingInitForAutoVars.insert(NewVD);
5801 
5802     if (D.isInvalidType())
5803       NewVD->setInvalidDecl();
5804   } else {
5805     bool Invalid = false;
5806 
5807     if (DC->isRecord() && !CurContext->isRecord()) {
5808       // This is an out-of-line definition of a static data member.
5809       switch (SC) {
5810       case SC_None:
5811         break;
5812       case SC_Static:
5813         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5814              diag::err_static_out_of_line)
5815           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5816         break;
5817       case SC_Auto:
5818       case SC_Register:
5819       case SC_Extern:
5820         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5821         // to names of variables declared in a block or to function parameters.
5822         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5823         // of class members
5824 
5825         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5826              diag::err_storage_class_for_static_member)
5827           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5828         break;
5829       case SC_PrivateExtern:
5830         llvm_unreachable("C storage class in c++!");
5831       }
5832     }
5833 
5834     if (SC == SC_Static && CurContext->isRecord()) {
5835       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5836         if (RD->isLocalClass())
5837           Diag(D.getIdentifierLoc(),
5838                diag::err_static_data_member_not_allowed_in_local_class)
5839             << Name << RD->getDeclName();
5840 
5841         // C++98 [class.union]p1: If a union contains a static data member,
5842         // the program is ill-formed. C++11 drops this restriction.
5843         if (RD->isUnion())
5844           Diag(D.getIdentifierLoc(),
5845                getLangOpts().CPlusPlus11
5846                  ? diag::warn_cxx98_compat_static_data_member_in_union
5847                  : diag::ext_static_data_member_in_union) << Name;
5848         // We conservatively disallow static data members in anonymous structs.
5849         else if (!RD->getDeclName())
5850           Diag(D.getIdentifierLoc(),
5851                diag::err_static_data_member_not_allowed_in_anon_struct)
5852             << Name << RD->isUnion();
5853       }
5854     }
5855 
5856     // Match up the template parameter lists with the scope specifier, then
5857     // determine whether we have a template or a template specialization.
5858     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5859         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5860         D.getCXXScopeSpec(),
5861         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5862             ? D.getName().TemplateId
5863             : nullptr,
5864         TemplateParamLists,
5865         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5866 
5867     if (TemplateParams) {
5868       if (!TemplateParams->size() &&
5869           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5870         // There is an extraneous 'template<>' for this variable. Complain
5871         // about it, but allow the declaration of the variable.
5872         Diag(TemplateParams->getTemplateLoc(),
5873              diag::err_template_variable_noparams)
5874           << II
5875           << SourceRange(TemplateParams->getTemplateLoc(),
5876                          TemplateParams->getRAngleLoc());
5877         TemplateParams = nullptr;
5878       } else {
5879         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5880           // This is an explicit specialization or a partial specialization.
5881           // FIXME: Check that we can declare a specialization here.
5882           IsVariableTemplateSpecialization = true;
5883           IsPartialSpecialization = TemplateParams->size() > 0;
5884         } else { // if (TemplateParams->size() > 0)
5885           // This is a template declaration.
5886           IsVariableTemplate = true;
5887 
5888           // Check that we can declare a template here.
5889           if (CheckTemplateDeclScope(S, TemplateParams))
5890             return nullptr;
5891 
5892           // Only C++1y supports variable templates (N3651).
5893           Diag(D.getIdentifierLoc(),
5894                getLangOpts().CPlusPlus14
5895                    ? diag::warn_cxx11_compat_variable_template
5896                    : diag::ext_variable_template);
5897         }
5898       }
5899     } else {
5900       assert(
5901           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5902           "should have a 'template<>' for this decl");
5903     }
5904 
5905     if (IsVariableTemplateSpecialization) {
5906       SourceLocation TemplateKWLoc =
5907           TemplateParamLists.size() > 0
5908               ? TemplateParamLists[0]->getTemplateLoc()
5909               : SourceLocation();
5910       DeclResult Res = ActOnVarTemplateSpecialization(
5911           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5912           IsPartialSpecialization);
5913       if (Res.isInvalid())
5914         return nullptr;
5915       NewVD = cast<VarDecl>(Res.get());
5916       AddToScope = false;
5917     } else
5918       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5919                               D.getIdentifierLoc(), II, R, TInfo, SC);
5920 
5921     // If this is supposed to be a variable template, create it as such.
5922     if (IsVariableTemplate) {
5923       NewTemplate =
5924           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5925                                   TemplateParams, NewVD);
5926       NewVD->setDescribedVarTemplate(NewTemplate);
5927     }
5928 
5929     // If this decl has an auto type in need of deduction, make a note of the
5930     // Decl so we can diagnose uses of it in its own initializer.
5931     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5932       ParsingInitForAutoVars.insert(NewVD);
5933 
5934     if (D.isInvalidType() || Invalid) {
5935       NewVD->setInvalidDecl();
5936       if (NewTemplate)
5937         NewTemplate->setInvalidDecl();
5938     }
5939 
5940     SetNestedNameSpecifier(NewVD, D);
5941 
5942     // If we have any template parameter lists that don't directly belong to
5943     // the variable (matching the scope specifier), store them.
5944     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5945     if (TemplateParamLists.size() > VDTemplateParamLists)
5946       NewVD->setTemplateParameterListsInfo(
5947           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5948 
5949     if (D.getDeclSpec().isConstexprSpecified())
5950       NewVD->setConstexpr(true);
5951 
5952     if (D.getDeclSpec().isConceptSpecified()) {
5953       NewVD->setConcept(true);
5954 
5955       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5956       // be declared with the thread_local, inline, friend, or constexpr
5957       // specifiers, [...]
5958       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5959         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5960              diag::err_concept_decl_invalid_specifiers)
5961             << 0 << 0;
5962         NewVD->setInvalidDecl(true);
5963       }
5964 
5965       if (D.getDeclSpec().isConstexprSpecified()) {
5966         Diag(D.getDeclSpec().getConstexprSpecLoc(),
5967              diag::err_concept_decl_invalid_specifiers)
5968             << 0 << 3;
5969         NewVD->setInvalidDecl(true);
5970       }
5971     }
5972   }
5973 
5974   // Set the lexical context. If the declarator has a C++ scope specifier, the
5975   // lexical context will be different from the semantic context.
5976   NewVD->setLexicalDeclContext(CurContext);
5977   if (NewTemplate)
5978     NewTemplate->setLexicalDeclContext(CurContext);
5979 
5980   if (IsLocalExternDecl)
5981     NewVD->setLocalExternDecl();
5982 
5983   bool EmitTLSUnsupportedError = false;
5984   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5985     // C++11 [dcl.stc]p4:
5986     //   When thread_local is applied to a variable of block scope the
5987     //   storage-class-specifier static is implied if it does not appear
5988     //   explicitly.
5989     // Core issue: 'static' is not implied if the variable is declared
5990     //   'extern'.
5991     if (NewVD->hasLocalStorage() &&
5992         (SCSpec != DeclSpec::SCS_unspecified ||
5993          TSCS != DeclSpec::TSCS_thread_local ||
5994          !DC->isFunctionOrMethod()))
5995       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5996            diag::err_thread_non_global)
5997         << DeclSpec::getSpecifierName(TSCS);
5998     else if (!Context.getTargetInfo().isTLSSupported()) {
5999       if (getLangOpts().CUDA) {
6000         // Postpone error emission until we've collected attributes required to
6001         // figure out whether it's a host or device variable and whether the
6002         // error should be ignored.
6003         EmitTLSUnsupportedError = true;
6004         // We still need to mark the variable as TLS so it shows up in AST with
6005         // proper storage class for other tools to use even if we're not going
6006         // to emit any code for it.
6007         NewVD->setTSCSpec(TSCS);
6008       } else
6009         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6010              diag::err_thread_unsupported);
6011     } else
6012       NewVD->setTSCSpec(TSCS);
6013   }
6014 
6015   // C99 6.7.4p3
6016   //   An inline definition of a function with external linkage shall
6017   //   not contain a definition of a modifiable object with static or
6018   //   thread storage duration...
6019   // We only apply this when the function is required to be defined
6020   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6021   // that a local variable with thread storage duration still has to
6022   // be marked 'static'.  Also note that it's possible to get these
6023   // semantics in C++ using __attribute__((gnu_inline)).
6024   if (SC == SC_Static && S->getFnParent() != nullptr &&
6025       !NewVD->getType().isConstQualified()) {
6026     FunctionDecl *CurFD = getCurFunctionDecl();
6027     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6028       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6029            diag::warn_static_local_in_extern_inline);
6030       MaybeSuggestAddingStaticToDecl(CurFD);
6031     }
6032   }
6033 
6034   if (D.getDeclSpec().isModulePrivateSpecified()) {
6035     if (IsVariableTemplateSpecialization)
6036       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6037           << (IsPartialSpecialization ? 1 : 0)
6038           << FixItHint::CreateRemoval(
6039                  D.getDeclSpec().getModulePrivateSpecLoc());
6040     else if (IsExplicitSpecialization)
6041       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6042         << 2
6043         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6044     else if (NewVD->hasLocalStorage())
6045       Diag(NewVD->getLocation(), diag::err_module_private_local)
6046         << 0 << NewVD->getDeclName()
6047         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6048         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6049     else {
6050       NewVD->setModulePrivate();
6051       if (NewTemplate)
6052         NewTemplate->setModulePrivate();
6053     }
6054   }
6055 
6056   // Handle attributes prior to checking for duplicates in MergeVarDecl
6057   ProcessDeclAttributes(S, NewVD, D);
6058 
6059   if (getLangOpts().CUDA) {
6060     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6061       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6062            diag::err_thread_unsupported);
6063     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6064     // storage [duration]."
6065     if (SC == SC_None && S->getFnParent() != nullptr &&
6066         (NewVD->hasAttr<CUDASharedAttr>() ||
6067          NewVD->hasAttr<CUDAConstantAttr>())) {
6068       NewVD->setStorageClass(SC_Static);
6069     }
6070   }
6071 
6072   // Ensure that dllimport globals without explicit storage class are treated as
6073   // extern. The storage class is set above using parsed attributes. Now we can
6074   // check the VarDecl itself.
6075   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6076          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6077          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6078 
6079   // In auto-retain/release, infer strong retension for variables of
6080   // retainable type.
6081   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6082     NewVD->setInvalidDecl();
6083 
6084   // Handle GNU asm-label extension (encoded as an attribute).
6085   if (Expr *E = (Expr*)D.getAsmLabel()) {
6086     // The parser guarantees this is a string.
6087     StringLiteral *SE = cast<StringLiteral>(E);
6088     StringRef Label = SE->getString();
6089     if (S->getFnParent() != nullptr) {
6090       switch (SC) {
6091       case SC_None:
6092       case SC_Auto:
6093         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6094         break;
6095       case SC_Register:
6096         // Local Named register
6097         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6098             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6099           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6100         break;
6101       case SC_Static:
6102       case SC_Extern:
6103       case SC_PrivateExtern:
6104         break;
6105       }
6106     } else if (SC == SC_Register) {
6107       // Global Named register
6108       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6109         const auto &TI = Context.getTargetInfo();
6110         bool HasSizeMismatch;
6111 
6112         if (!TI.isValidGCCRegisterName(Label))
6113           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6114         else if (!TI.validateGlobalRegisterVariable(Label,
6115                                                     Context.getTypeSize(R),
6116                                                     HasSizeMismatch))
6117           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6118         else if (HasSizeMismatch)
6119           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6120       }
6121 
6122       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6123         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6124         NewVD->setInvalidDecl(true);
6125       }
6126     }
6127 
6128     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6129                                                 Context, Label, 0));
6130   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6131     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6132       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6133     if (I != ExtnameUndeclaredIdentifiers.end()) {
6134       if (isDeclExternC(NewVD)) {
6135         NewVD->addAttr(I->second);
6136         ExtnameUndeclaredIdentifiers.erase(I);
6137       } else
6138         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6139             << /*Variable*/1 << NewVD;
6140     }
6141   }
6142 
6143   // Diagnose shadowed variables before filtering for scope.
6144   if (D.getCXXScopeSpec().isEmpty())
6145     CheckShadow(S, NewVD, Previous);
6146 
6147   // Don't consider existing declarations that are in a different
6148   // scope and are out-of-semantic-context declarations (if the new
6149   // declaration has linkage).
6150   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6151                        D.getCXXScopeSpec().isNotEmpty() ||
6152                        IsExplicitSpecialization ||
6153                        IsVariableTemplateSpecialization);
6154 
6155   // Check whether the previous declaration is in the same block scope. This
6156   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6157   if (getLangOpts().CPlusPlus &&
6158       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6159     NewVD->setPreviousDeclInSameBlockScope(
6160         Previous.isSingleResult() && !Previous.isShadowed() &&
6161         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6162 
6163   if (!getLangOpts().CPlusPlus) {
6164     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6165   } else {
6166     // If this is an explicit specialization of a static data member, check it.
6167     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6168         CheckMemberSpecialization(NewVD, Previous))
6169       NewVD->setInvalidDecl();
6170 
6171     // Merge the decl with the existing one if appropriate.
6172     if (!Previous.empty()) {
6173       if (Previous.isSingleResult() &&
6174           isa<FieldDecl>(Previous.getFoundDecl()) &&
6175           D.getCXXScopeSpec().isSet()) {
6176         // The user tried to define a non-static data member
6177         // out-of-line (C++ [dcl.meaning]p1).
6178         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6179           << D.getCXXScopeSpec().getRange();
6180         Previous.clear();
6181         NewVD->setInvalidDecl();
6182       }
6183     } else if (D.getCXXScopeSpec().isSet()) {
6184       // No previous declaration in the qualifying scope.
6185       Diag(D.getIdentifierLoc(), diag::err_no_member)
6186         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6187         << D.getCXXScopeSpec().getRange();
6188       NewVD->setInvalidDecl();
6189     }
6190 
6191     if (!IsVariableTemplateSpecialization)
6192       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6193 
6194     if (NewTemplate) {
6195       VarTemplateDecl *PrevVarTemplate =
6196           NewVD->getPreviousDecl()
6197               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6198               : nullptr;
6199 
6200       // Check the template parameter list of this declaration, possibly
6201       // merging in the template parameter list from the previous variable
6202       // template declaration.
6203       if (CheckTemplateParameterList(
6204               TemplateParams,
6205               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6206                               : nullptr,
6207               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6208                DC->isDependentContext())
6209                   ? TPC_ClassTemplateMember
6210                   : TPC_VarTemplate))
6211         NewVD->setInvalidDecl();
6212 
6213       // If we are providing an explicit specialization of a static variable
6214       // template, make a note of that.
6215       if (PrevVarTemplate &&
6216           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6217         PrevVarTemplate->setMemberSpecialization();
6218     }
6219   }
6220 
6221   ProcessPragmaWeak(S, NewVD);
6222 
6223   // If this is the first declaration of an extern C variable, update
6224   // the map of such variables.
6225   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6226       isIncompleteDeclExternC(*this, NewVD))
6227     RegisterLocallyScopedExternCDecl(NewVD, S);
6228 
6229   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6230     Decl *ManglingContextDecl;
6231     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6232             NewVD->getDeclContext(), ManglingContextDecl)) {
6233       Context.setManglingNumber(
6234           NewVD, MCtx->getManglingNumber(
6235                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6236       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6237     }
6238   }
6239 
6240   // Special handling of variable named 'main'.
6241   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6242       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6243       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6244 
6245     // C++ [basic.start.main]p3
6246     // A program that declares a variable main at global scope is ill-formed.
6247     if (getLangOpts().CPlusPlus)
6248       Diag(D.getLocStart(), diag::err_main_global_variable);
6249 
6250     // In C, and external-linkage variable named main results in undefined
6251     // behavior.
6252     else if (NewVD->hasExternalFormalLinkage())
6253       Diag(D.getLocStart(), diag::warn_main_redefined);
6254   }
6255 
6256   if (D.isRedeclaration() && !Previous.empty()) {
6257     checkDLLAttributeRedeclaration(
6258         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6259         IsExplicitSpecialization);
6260   }
6261 
6262   if (NewTemplate) {
6263     if (NewVD->isInvalidDecl())
6264       NewTemplate->setInvalidDecl();
6265     ActOnDocumentableDecl(NewTemplate);
6266     return NewTemplate;
6267   }
6268 
6269   return NewVD;
6270 }
6271 
6272 /// \brief Diagnose variable or built-in function shadowing.  Implements
6273 /// -Wshadow.
6274 ///
6275 /// This method is called whenever a VarDecl is added to a "useful"
6276 /// scope.
6277 ///
6278 /// \param S the scope in which the shadowing name is being declared
6279 /// \param R the lookup of the name
6280 ///
6281 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6282   // Return if warning is ignored.
6283   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6284     return;
6285 
6286   // Don't diagnose declarations at file scope.
6287   if (D->hasGlobalStorage())
6288     return;
6289 
6290   DeclContext *NewDC = D->getDeclContext();
6291 
6292   // Only diagnose if we're shadowing an unambiguous field or variable.
6293   if (R.getResultKind() != LookupResult::Found)
6294     return;
6295 
6296   NamedDecl* ShadowedDecl = R.getFoundDecl();
6297   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6298     return;
6299 
6300   // Fields are not shadowed by variables in C++ static methods.
6301   if (isa<FieldDecl>(ShadowedDecl))
6302     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6303       if (MD->isStatic())
6304         return;
6305 
6306   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6307     if (shadowedVar->isExternC()) {
6308       // For shadowing external vars, make sure that we point to the global
6309       // declaration, not a locally scoped extern declaration.
6310       for (auto I : shadowedVar->redecls())
6311         if (I->isFileVarDecl()) {
6312           ShadowedDecl = I;
6313           break;
6314         }
6315     }
6316 
6317   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6318 
6319   // Only warn about certain kinds of shadowing for class members.
6320   if (NewDC && NewDC->isRecord()) {
6321     // In particular, don't warn about shadowing non-class members.
6322     if (!OldDC->isRecord())
6323       return;
6324 
6325     // TODO: should we warn about static data members shadowing
6326     // static data members from base classes?
6327 
6328     // TODO: don't diagnose for inaccessible shadowed members.
6329     // This is hard to do perfectly because we might friend the
6330     // shadowing context, but that's just a false negative.
6331   }
6332 
6333   // Determine what kind of declaration we're shadowing.
6334   unsigned Kind;
6335   if (isa<RecordDecl>(OldDC)) {
6336     if (isa<FieldDecl>(ShadowedDecl))
6337       Kind = 3; // field
6338     else
6339       Kind = 2; // static data member
6340   } else if (OldDC->isFileContext())
6341     Kind = 1; // global
6342   else
6343     Kind = 0; // local
6344 
6345   DeclarationName Name = R.getLookupName();
6346 
6347   // Emit warning and note.
6348   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6349     return;
6350   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6351   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6352 }
6353 
6354 /// \brief Check -Wshadow without the advantage of a previous lookup.
6355 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6356   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6357     return;
6358 
6359   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6360                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6361   LookupName(R, S);
6362   CheckShadow(S, D, R);
6363 }
6364 
6365 /// Check for conflict between this global or extern "C" declaration and
6366 /// previous global or extern "C" declarations. This is only used in C++.
6367 template<typename T>
6368 static bool checkGlobalOrExternCConflict(
6369     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6370   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6371   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6372 
6373   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6374     // The common case: this global doesn't conflict with any extern "C"
6375     // declaration.
6376     return false;
6377   }
6378 
6379   if (Prev) {
6380     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6381       // Both the old and new declarations have C language linkage. This is a
6382       // redeclaration.
6383       Previous.clear();
6384       Previous.addDecl(Prev);
6385       return true;
6386     }
6387 
6388     // This is a global, non-extern "C" declaration, and there is a previous
6389     // non-global extern "C" declaration. Diagnose if this is a variable
6390     // declaration.
6391     if (!isa<VarDecl>(ND))
6392       return false;
6393   } else {
6394     // The declaration is extern "C". Check for any declaration in the
6395     // translation unit which might conflict.
6396     if (IsGlobal) {
6397       // We have already performed the lookup into the translation unit.
6398       IsGlobal = false;
6399       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6400            I != E; ++I) {
6401         if (isa<VarDecl>(*I)) {
6402           Prev = *I;
6403           break;
6404         }
6405       }
6406     } else {
6407       DeclContext::lookup_result R =
6408           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6409       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6410            I != E; ++I) {
6411         if (isa<VarDecl>(*I)) {
6412           Prev = *I;
6413           break;
6414         }
6415         // FIXME: If we have any other entity with this name in global scope,
6416         // the declaration is ill-formed, but that is a defect: it breaks the
6417         // 'stat' hack, for instance. Only variables can have mangled name
6418         // clashes with extern "C" declarations, so only they deserve a
6419         // diagnostic.
6420       }
6421     }
6422 
6423     if (!Prev)
6424       return false;
6425   }
6426 
6427   // Use the first declaration's location to ensure we point at something which
6428   // is lexically inside an extern "C" linkage-spec.
6429   assert(Prev && "should have found a previous declaration to diagnose");
6430   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6431     Prev = FD->getFirstDecl();
6432   else
6433     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6434 
6435   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6436     << IsGlobal << ND;
6437   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6438     << IsGlobal;
6439   return false;
6440 }
6441 
6442 /// Apply special rules for handling extern "C" declarations. Returns \c true
6443 /// if we have found that this is a redeclaration of some prior entity.
6444 ///
6445 /// Per C++ [dcl.link]p6:
6446 ///   Two declarations [for a function or variable] with C language linkage
6447 ///   with the same name that appear in different scopes refer to the same
6448 ///   [entity]. An entity with C language linkage shall not be declared with
6449 ///   the same name as an entity in global scope.
6450 template<typename T>
6451 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6452                                                   LookupResult &Previous) {
6453   if (!S.getLangOpts().CPlusPlus) {
6454     // In C, when declaring a global variable, look for a corresponding 'extern'
6455     // variable declared in function scope. We don't need this in C++, because
6456     // we find local extern decls in the surrounding file-scope DeclContext.
6457     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6458       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6459         Previous.clear();
6460         Previous.addDecl(Prev);
6461         return true;
6462       }
6463     }
6464     return false;
6465   }
6466 
6467   // A declaration in the translation unit can conflict with an extern "C"
6468   // declaration.
6469   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6470     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6471 
6472   // An extern "C" declaration can conflict with a declaration in the
6473   // translation unit or can be a redeclaration of an extern "C" declaration
6474   // in another scope.
6475   if (isIncompleteDeclExternC(S,ND))
6476     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6477 
6478   // Neither global nor extern "C": nothing to do.
6479   return false;
6480 }
6481 
6482 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6483   // If the decl is already known invalid, don't check it.
6484   if (NewVD->isInvalidDecl())
6485     return;
6486 
6487   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6488   QualType T = TInfo->getType();
6489 
6490   // Defer checking an 'auto' type until its initializer is attached.
6491   if (T->isUndeducedType())
6492     return;
6493 
6494   if (NewVD->hasAttrs())
6495     CheckAlignasUnderalignment(NewVD);
6496 
6497   if (T->isObjCObjectType()) {
6498     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6499       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6500     T = Context.getObjCObjectPointerType(T);
6501     NewVD->setType(T);
6502   }
6503 
6504   // Emit an error if an address space was applied to decl with local storage.
6505   // This includes arrays of objects with address space qualifiers, but not
6506   // automatic variables that point to other address spaces.
6507   // ISO/IEC TR 18037 S5.1.2
6508   if (!getLangOpts().OpenCL
6509       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6510     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6511     NewVD->setInvalidDecl();
6512     return;
6513   }
6514 
6515   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6516   // scope.
6517   if (getLangOpts().OpenCLVersion == 120 &&
6518       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6519       NewVD->isStaticLocal()) {
6520     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6521     NewVD->setInvalidDecl();
6522     return;
6523   }
6524 
6525   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6526   // __constant address space.
6527   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6528   // variables inside a function can also be declared in the global
6529   // address space.
6530   if (getLangOpts().OpenCL) {
6531     if (NewVD->isFileVarDecl()) {
6532       if (!T->isSamplerT() &&
6533           !(T.getAddressSpace() == LangAS::opencl_constant ||
6534             (T.getAddressSpace() == LangAS::opencl_global &&
6535              getLangOpts().OpenCLVersion == 200))) {
6536         if (getLangOpts().OpenCLVersion == 200)
6537           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6538               << "global or constant";
6539         else
6540           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6541               << "constant";
6542         NewVD->setInvalidDecl();
6543         return;
6544       }
6545     } else {
6546       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6547       // variables inside a function can also be declared in the global
6548       // address space.
6549       if (NewVD->isStaticLocal() &&
6550           !(T.getAddressSpace() == LangAS::opencl_constant ||
6551             (T.getAddressSpace() == LangAS::opencl_global &&
6552              getLangOpts().OpenCLVersion == 200))) {
6553         if (getLangOpts().OpenCLVersion == 200)
6554           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6555               << "global or constant";
6556         else
6557           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6558               << "constant";
6559         NewVD->setInvalidDecl();
6560         return;
6561       }
6562       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6563       // in functions.
6564       if (T.getAddressSpace() == LangAS::opencl_constant ||
6565           T.getAddressSpace() == LangAS::opencl_local) {
6566         FunctionDecl *FD = getCurFunctionDecl();
6567         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6568           if (T.getAddressSpace() == LangAS::opencl_constant)
6569             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6570                 << "constant";
6571           else
6572             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6573                 << "local";
6574           NewVD->setInvalidDecl();
6575           return;
6576         }
6577       }
6578     }
6579   }
6580 
6581   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6582       && !NewVD->hasAttr<BlocksAttr>()) {
6583     if (getLangOpts().getGC() != LangOptions::NonGC)
6584       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6585     else {
6586       assert(!getLangOpts().ObjCAutoRefCount);
6587       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6588     }
6589   }
6590 
6591   bool isVM = T->isVariablyModifiedType();
6592   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6593       NewVD->hasAttr<BlocksAttr>())
6594     getCurFunction()->setHasBranchProtectedScope();
6595 
6596   if ((isVM && NewVD->hasLinkage()) ||
6597       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6598     bool SizeIsNegative;
6599     llvm::APSInt Oversized;
6600     TypeSourceInfo *FixedTInfo =
6601       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6602                                                     SizeIsNegative, Oversized);
6603     if (!FixedTInfo && T->isVariableArrayType()) {
6604       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6605       // FIXME: This won't give the correct result for
6606       // int a[10][n];
6607       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6608 
6609       if (NewVD->isFileVarDecl())
6610         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6611         << SizeRange;
6612       else if (NewVD->isStaticLocal())
6613         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6614         << SizeRange;
6615       else
6616         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6617         << SizeRange;
6618       NewVD->setInvalidDecl();
6619       return;
6620     }
6621 
6622     if (!FixedTInfo) {
6623       if (NewVD->isFileVarDecl())
6624         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6625       else
6626         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6627       NewVD->setInvalidDecl();
6628       return;
6629     }
6630 
6631     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6632     NewVD->setType(FixedTInfo->getType());
6633     NewVD->setTypeSourceInfo(FixedTInfo);
6634   }
6635 
6636   if (T->isVoidType()) {
6637     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6638     //                    of objects and functions.
6639     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6640       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6641         << T;
6642       NewVD->setInvalidDecl();
6643       return;
6644     }
6645   }
6646 
6647   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6648     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6649     NewVD->setInvalidDecl();
6650     return;
6651   }
6652 
6653   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6654     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6655     NewVD->setInvalidDecl();
6656     return;
6657   }
6658 
6659   if (NewVD->isConstexpr() && !T->isDependentType() &&
6660       RequireLiteralType(NewVD->getLocation(), T,
6661                          diag::err_constexpr_var_non_literal)) {
6662     NewVD->setInvalidDecl();
6663     return;
6664   }
6665 }
6666 
6667 /// \brief Perform semantic checking on a newly-created variable
6668 /// declaration.
6669 ///
6670 /// This routine performs all of the type-checking required for a
6671 /// variable declaration once it has been built. It is used both to
6672 /// check variables after they have been parsed and their declarators
6673 /// have been translated into a declaration, and to check variables
6674 /// that have been instantiated from a template.
6675 ///
6676 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6677 ///
6678 /// Returns true if the variable declaration is a redeclaration.
6679 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6680   CheckVariableDeclarationType(NewVD);
6681 
6682   // If the decl is already known invalid, don't check it.
6683   if (NewVD->isInvalidDecl())
6684     return false;
6685 
6686   // If we did not find anything by this name, look for a non-visible
6687   // extern "C" declaration with the same name.
6688   if (Previous.empty() &&
6689       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6690     Previous.setShadowed();
6691 
6692   if (!Previous.empty()) {
6693     MergeVarDecl(NewVD, Previous);
6694     return true;
6695   }
6696   return false;
6697 }
6698 
6699 namespace {
6700 struct FindOverriddenMethod {
6701   Sema *S;
6702   CXXMethodDecl *Method;
6703 
6704   /// Member lookup function that determines whether a given C++
6705   /// method overrides a method in a base class, to be used with
6706   /// CXXRecordDecl::lookupInBases().
6707   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6708     RecordDecl *BaseRecord =
6709         Specifier->getType()->getAs<RecordType>()->getDecl();
6710 
6711     DeclarationName Name = Method->getDeclName();
6712 
6713     // FIXME: Do we care about other names here too?
6714     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6715       // We really want to find the base class destructor here.
6716       QualType T = S->Context.getTypeDeclType(BaseRecord);
6717       CanQualType CT = S->Context.getCanonicalType(T);
6718 
6719       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6720     }
6721 
6722     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6723          Path.Decls = Path.Decls.slice(1)) {
6724       NamedDecl *D = Path.Decls.front();
6725       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6726         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6727           return true;
6728       }
6729     }
6730 
6731     return false;
6732   }
6733 };
6734 
6735 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6736 } // end anonymous namespace
6737 
6738 /// \brief Report an error regarding overriding, along with any relevant
6739 /// overriden methods.
6740 ///
6741 /// \param DiagID the primary error to report.
6742 /// \param MD the overriding method.
6743 /// \param OEK which overrides to include as notes.
6744 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6745                             OverrideErrorKind OEK = OEK_All) {
6746   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6747   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6748                                       E = MD->end_overridden_methods();
6749        I != E; ++I) {
6750     // This check (& the OEK parameter) could be replaced by a predicate, but
6751     // without lambdas that would be overkill. This is still nicer than writing
6752     // out the diag loop 3 times.
6753     if ((OEK == OEK_All) ||
6754         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6755         (OEK == OEK_Deleted && (*I)->isDeleted()))
6756       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6757   }
6758 }
6759 
6760 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6761 /// and if so, check that it's a valid override and remember it.
6762 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6763   // Look for methods in base classes that this method might override.
6764   CXXBasePaths Paths;
6765   FindOverriddenMethod FOM;
6766   FOM.Method = MD;
6767   FOM.S = this;
6768   bool hasDeletedOverridenMethods = false;
6769   bool hasNonDeletedOverridenMethods = false;
6770   bool AddedAny = false;
6771   if (DC->lookupInBases(FOM, Paths)) {
6772     for (auto *I : Paths.found_decls()) {
6773       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6774         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6775         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6776             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6777             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6778             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6779           hasDeletedOverridenMethods |= OldMD->isDeleted();
6780           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6781           AddedAny = true;
6782         }
6783       }
6784     }
6785   }
6786 
6787   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6788     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6789   }
6790   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6791     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6792   }
6793 
6794   return AddedAny;
6795 }
6796 
6797 namespace {
6798   // Struct for holding all of the extra arguments needed by
6799   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6800   struct ActOnFDArgs {
6801     Scope *S;
6802     Declarator &D;
6803     MultiTemplateParamsArg TemplateParamLists;
6804     bool AddToScope;
6805   };
6806 }
6807 
6808 namespace {
6809 
6810 // Callback to only accept typo corrections that have a non-zero edit distance.
6811 // Also only accept corrections that have the same parent decl.
6812 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6813  public:
6814   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6815                             CXXRecordDecl *Parent)
6816       : Context(Context), OriginalFD(TypoFD),
6817         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6818 
6819   bool ValidateCandidate(const TypoCorrection &candidate) override {
6820     if (candidate.getEditDistance() == 0)
6821       return false;
6822 
6823     SmallVector<unsigned, 1> MismatchedParams;
6824     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6825                                           CDeclEnd = candidate.end();
6826          CDecl != CDeclEnd; ++CDecl) {
6827       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6828 
6829       if (FD && !FD->hasBody() &&
6830           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6831         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6832           CXXRecordDecl *Parent = MD->getParent();
6833           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6834             return true;
6835         } else if (!ExpectedParent) {
6836           return true;
6837         }
6838       }
6839     }
6840 
6841     return false;
6842   }
6843 
6844  private:
6845   ASTContext &Context;
6846   FunctionDecl *OriginalFD;
6847   CXXRecordDecl *ExpectedParent;
6848 };
6849 
6850 }
6851 
6852 /// \brief Generate diagnostics for an invalid function redeclaration.
6853 ///
6854 /// This routine handles generating the diagnostic messages for an invalid
6855 /// function redeclaration, including finding possible similar declarations
6856 /// or performing typo correction if there are no previous declarations with
6857 /// the same name.
6858 ///
6859 /// Returns a NamedDecl iff typo correction was performed and substituting in
6860 /// the new declaration name does not cause new errors.
6861 static NamedDecl *DiagnoseInvalidRedeclaration(
6862     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6863     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6864   DeclarationName Name = NewFD->getDeclName();
6865   DeclContext *NewDC = NewFD->getDeclContext();
6866   SmallVector<unsigned, 1> MismatchedParams;
6867   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6868   TypoCorrection Correction;
6869   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6870   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6871                                    : diag::err_member_decl_does_not_match;
6872   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6873                     IsLocalFriend ? Sema::LookupLocalFriendName
6874                                   : Sema::LookupOrdinaryName,
6875                     Sema::ForRedeclaration);
6876 
6877   NewFD->setInvalidDecl();
6878   if (IsLocalFriend)
6879     SemaRef.LookupName(Prev, S);
6880   else
6881     SemaRef.LookupQualifiedName(Prev, NewDC);
6882   assert(!Prev.isAmbiguous() &&
6883          "Cannot have an ambiguity in previous-declaration lookup");
6884   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6885   if (!Prev.empty()) {
6886     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6887          Func != FuncEnd; ++Func) {
6888       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6889       if (FD &&
6890           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6891         // Add 1 to the index so that 0 can mean the mismatch didn't
6892         // involve a parameter
6893         unsigned ParamNum =
6894             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6895         NearMatches.push_back(std::make_pair(FD, ParamNum));
6896       }
6897     }
6898   // If the qualified name lookup yielded nothing, try typo correction
6899   } else if ((Correction = SemaRef.CorrectTypo(
6900                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6901                   &ExtraArgs.D.getCXXScopeSpec(),
6902                   llvm::make_unique<DifferentNameValidatorCCC>(
6903                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6904                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6905     // Set up everything for the call to ActOnFunctionDeclarator
6906     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6907                               ExtraArgs.D.getIdentifierLoc());
6908     Previous.clear();
6909     Previous.setLookupName(Correction.getCorrection());
6910     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6911                                     CDeclEnd = Correction.end();
6912          CDecl != CDeclEnd; ++CDecl) {
6913       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6914       if (FD && !FD->hasBody() &&
6915           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6916         Previous.addDecl(FD);
6917       }
6918     }
6919     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6920 
6921     NamedDecl *Result;
6922     // Retry building the function declaration with the new previous
6923     // declarations, and with errors suppressed.
6924     {
6925       // Trap errors.
6926       Sema::SFINAETrap Trap(SemaRef);
6927 
6928       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6929       // pieces need to verify the typo-corrected C++ declaration and hopefully
6930       // eliminate the need for the parameter pack ExtraArgs.
6931       Result = SemaRef.ActOnFunctionDeclarator(
6932           ExtraArgs.S, ExtraArgs.D,
6933           Correction.getCorrectionDecl()->getDeclContext(),
6934           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6935           ExtraArgs.AddToScope);
6936 
6937       if (Trap.hasErrorOccurred())
6938         Result = nullptr;
6939     }
6940 
6941     if (Result) {
6942       // Determine which correction we picked.
6943       Decl *Canonical = Result->getCanonicalDecl();
6944       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6945            I != E; ++I)
6946         if ((*I)->getCanonicalDecl() == Canonical)
6947           Correction.setCorrectionDecl(*I);
6948 
6949       SemaRef.diagnoseTypo(
6950           Correction,
6951           SemaRef.PDiag(IsLocalFriend
6952                           ? diag::err_no_matching_local_friend_suggest
6953                           : diag::err_member_decl_does_not_match_suggest)
6954             << Name << NewDC << IsDefinition);
6955       return Result;
6956     }
6957 
6958     // Pretend the typo correction never occurred
6959     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6960                               ExtraArgs.D.getIdentifierLoc());
6961     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6962     Previous.clear();
6963     Previous.setLookupName(Name);
6964   }
6965 
6966   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6967       << Name << NewDC << IsDefinition << NewFD->getLocation();
6968 
6969   bool NewFDisConst = false;
6970   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6971     NewFDisConst = NewMD->isConst();
6972 
6973   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6974        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6975        NearMatch != NearMatchEnd; ++NearMatch) {
6976     FunctionDecl *FD = NearMatch->first;
6977     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6978     bool FDisConst = MD && MD->isConst();
6979     bool IsMember = MD || !IsLocalFriend;
6980 
6981     // FIXME: These notes are poorly worded for the local friend case.
6982     if (unsigned Idx = NearMatch->second) {
6983       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6984       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6985       if (Loc.isInvalid()) Loc = FD->getLocation();
6986       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6987                                  : diag::note_local_decl_close_param_match)
6988         << Idx << FDParam->getType()
6989         << NewFD->getParamDecl(Idx - 1)->getType();
6990     } else if (FDisConst != NewFDisConst) {
6991       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6992           << NewFDisConst << FD->getSourceRange().getEnd();
6993     } else
6994       SemaRef.Diag(FD->getLocation(),
6995                    IsMember ? diag::note_member_def_close_match
6996                             : diag::note_local_decl_close_match);
6997   }
6998   return nullptr;
6999 }
7000 
7001 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7002   switch (D.getDeclSpec().getStorageClassSpec()) {
7003   default: llvm_unreachable("Unknown storage class!");
7004   case DeclSpec::SCS_auto:
7005   case DeclSpec::SCS_register:
7006   case DeclSpec::SCS_mutable:
7007     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7008                  diag::err_typecheck_sclass_func);
7009     D.setInvalidType();
7010     break;
7011   case DeclSpec::SCS_unspecified: break;
7012   case DeclSpec::SCS_extern:
7013     if (D.getDeclSpec().isExternInLinkageSpec())
7014       return SC_None;
7015     return SC_Extern;
7016   case DeclSpec::SCS_static: {
7017     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7018       // C99 6.7.1p5:
7019       //   The declaration of an identifier for a function that has
7020       //   block scope shall have no explicit storage-class specifier
7021       //   other than extern
7022       // See also (C++ [dcl.stc]p4).
7023       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7024                    diag::err_static_block_func);
7025       break;
7026     } else
7027       return SC_Static;
7028   }
7029   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7030   }
7031 
7032   // No explicit storage class has already been returned
7033   return SC_None;
7034 }
7035 
7036 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7037                                            DeclContext *DC, QualType &R,
7038                                            TypeSourceInfo *TInfo,
7039                                            StorageClass SC,
7040                                            bool &IsVirtualOkay) {
7041   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7042   DeclarationName Name = NameInfo.getName();
7043 
7044   FunctionDecl *NewFD = nullptr;
7045   bool isInline = D.getDeclSpec().isInlineSpecified();
7046 
7047   if (!SemaRef.getLangOpts().CPlusPlus) {
7048     // Determine whether the function was written with a
7049     // prototype. This true when:
7050     //   - there is a prototype in the declarator, or
7051     //   - the type R of the function is some kind of typedef or other reference
7052     //     to a type name (which eventually refers to a function type).
7053     bool HasPrototype =
7054       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7055       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7056 
7057     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7058                                  D.getLocStart(), NameInfo, R,
7059                                  TInfo, SC, isInline,
7060                                  HasPrototype, false);
7061     if (D.isInvalidType())
7062       NewFD->setInvalidDecl();
7063 
7064     return NewFD;
7065   }
7066 
7067   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7068   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7069 
7070   // Check that the return type is not an abstract class type.
7071   // For record types, this is done by the AbstractClassUsageDiagnoser once
7072   // the class has been completely parsed.
7073   if (!DC->isRecord() &&
7074       SemaRef.RequireNonAbstractType(
7075           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7076           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7077     D.setInvalidType();
7078 
7079   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7080     // This is a C++ constructor declaration.
7081     assert(DC->isRecord() &&
7082            "Constructors can only be declared in a member context");
7083 
7084     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7085     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7086                                       D.getLocStart(), NameInfo,
7087                                       R, TInfo, isExplicit, isInline,
7088                                       /*isImplicitlyDeclared=*/false,
7089                                       isConstexpr);
7090 
7091   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7092     // This is a C++ destructor declaration.
7093     if (DC->isRecord()) {
7094       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7095       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7096       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7097                                         SemaRef.Context, Record,
7098                                         D.getLocStart(),
7099                                         NameInfo, R, TInfo, isInline,
7100                                         /*isImplicitlyDeclared=*/false);
7101 
7102       // If the class is complete, then we now create the implicit exception
7103       // specification. If the class is incomplete or dependent, we can't do
7104       // it yet.
7105       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7106           Record->getDefinition() && !Record->isBeingDefined() &&
7107           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7108         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7109       }
7110 
7111       IsVirtualOkay = true;
7112       return NewDD;
7113 
7114     } else {
7115       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7116       D.setInvalidType();
7117 
7118       // Create a FunctionDecl to satisfy the function definition parsing
7119       // code path.
7120       return FunctionDecl::Create(SemaRef.Context, DC,
7121                                   D.getLocStart(),
7122                                   D.getIdentifierLoc(), Name, R, TInfo,
7123                                   SC, isInline,
7124                                   /*hasPrototype=*/true, isConstexpr);
7125     }
7126 
7127   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7128     if (!DC->isRecord()) {
7129       SemaRef.Diag(D.getIdentifierLoc(),
7130            diag::err_conv_function_not_member);
7131       return nullptr;
7132     }
7133 
7134     SemaRef.CheckConversionDeclarator(D, R, SC);
7135     IsVirtualOkay = true;
7136     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7137                                      D.getLocStart(), NameInfo,
7138                                      R, TInfo, isInline, isExplicit,
7139                                      isConstexpr, SourceLocation());
7140 
7141   } else if (DC->isRecord()) {
7142     // If the name of the function is the same as the name of the record,
7143     // then this must be an invalid constructor that has a return type.
7144     // (The parser checks for a return type and makes the declarator a
7145     // constructor if it has no return type).
7146     if (Name.getAsIdentifierInfo() &&
7147         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7148       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7149         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7150         << SourceRange(D.getIdentifierLoc());
7151       return nullptr;
7152     }
7153 
7154     // This is a C++ method declaration.
7155     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7156                                                cast<CXXRecordDecl>(DC),
7157                                                D.getLocStart(), NameInfo, R,
7158                                                TInfo, SC, isInline,
7159                                                isConstexpr, SourceLocation());
7160     IsVirtualOkay = !Ret->isStatic();
7161     return Ret;
7162   } else {
7163     bool isFriend =
7164         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7165     if (!isFriend && SemaRef.CurContext->isRecord())
7166       return nullptr;
7167 
7168     // Determine whether the function was written with a
7169     // prototype. This true when:
7170     //   - we're in C++ (where every function has a prototype),
7171     return FunctionDecl::Create(SemaRef.Context, DC,
7172                                 D.getLocStart(),
7173                                 NameInfo, R, TInfo, SC, isInline,
7174                                 true/*HasPrototype*/, isConstexpr);
7175   }
7176 }
7177 
7178 enum OpenCLParamType {
7179   ValidKernelParam,
7180   PtrPtrKernelParam,
7181   PtrKernelParam,
7182   PrivatePtrKernelParam,
7183   InvalidKernelParam,
7184   RecordKernelParam
7185 };
7186 
7187 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7188   if (PT->isPointerType()) {
7189     QualType PointeeType = PT->getPointeeType();
7190     if (PointeeType->isPointerType())
7191       return PtrPtrKernelParam;
7192     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7193                                               : PtrKernelParam;
7194   }
7195 
7196   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7197   // be used as builtin types.
7198 
7199   if (PT->isImageType())
7200     return PtrKernelParam;
7201 
7202   if (PT->isBooleanType())
7203     return InvalidKernelParam;
7204 
7205   if (PT->isEventT())
7206     return InvalidKernelParam;
7207 
7208   if (PT->isHalfType())
7209     return InvalidKernelParam;
7210 
7211   if (PT->isRecordType())
7212     return RecordKernelParam;
7213 
7214   return ValidKernelParam;
7215 }
7216 
7217 static void checkIsValidOpenCLKernelParameter(
7218   Sema &S,
7219   Declarator &D,
7220   ParmVarDecl *Param,
7221   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7222   QualType PT = Param->getType();
7223 
7224   // Cache the valid types we encounter to avoid rechecking structs that are
7225   // used again
7226   if (ValidTypes.count(PT.getTypePtr()))
7227     return;
7228 
7229   switch (getOpenCLKernelParameterType(PT)) {
7230   case PtrPtrKernelParam:
7231     // OpenCL v1.2 s6.9.a:
7232     // A kernel function argument cannot be declared as a
7233     // pointer to a pointer type.
7234     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7235     D.setInvalidType();
7236     return;
7237 
7238   case PrivatePtrKernelParam:
7239     // OpenCL v1.2 s6.9.a:
7240     // A kernel function argument cannot be declared as a
7241     // pointer to the private address space.
7242     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7243     D.setInvalidType();
7244     return;
7245 
7246     // OpenCL v1.2 s6.9.k:
7247     // Arguments to kernel functions in a program cannot be declared with the
7248     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7249     // uintptr_t or a struct and/or union that contain fields declared to be
7250     // one of these built-in scalar types.
7251 
7252   case InvalidKernelParam:
7253     // OpenCL v1.2 s6.8 n:
7254     // A kernel function argument cannot be declared
7255     // of event_t type.
7256     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7257     D.setInvalidType();
7258     return;
7259 
7260   case PtrKernelParam:
7261   case ValidKernelParam:
7262     ValidTypes.insert(PT.getTypePtr());
7263     return;
7264 
7265   case RecordKernelParam:
7266     break;
7267   }
7268 
7269   // Track nested structs we will inspect
7270   SmallVector<const Decl *, 4> VisitStack;
7271 
7272   // Track where we are in the nested structs. Items will migrate from
7273   // VisitStack to HistoryStack as we do the DFS for bad field.
7274   SmallVector<const FieldDecl *, 4> HistoryStack;
7275   HistoryStack.push_back(nullptr);
7276 
7277   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7278   VisitStack.push_back(PD);
7279 
7280   assert(VisitStack.back() && "First decl null?");
7281 
7282   do {
7283     const Decl *Next = VisitStack.pop_back_val();
7284     if (!Next) {
7285       assert(!HistoryStack.empty());
7286       // Found a marker, we have gone up a level
7287       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7288         ValidTypes.insert(Hist->getType().getTypePtr());
7289 
7290       continue;
7291     }
7292 
7293     // Adds everything except the original parameter declaration (which is not a
7294     // field itself) to the history stack.
7295     const RecordDecl *RD;
7296     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7297       HistoryStack.push_back(Field);
7298       RD = Field->getType()->castAs<RecordType>()->getDecl();
7299     } else {
7300       RD = cast<RecordDecl>(Next);
7301     }
7302 
7303     // Add a null marker so we know when we've gone back up a level
7304     VisitStack.push_back(nullptr);
7305 
7306     for (const auto *FD : RD->fields()) {
7307       QualType QT = FD->getType();
7308 
7309       if (ValidTypes.count(QT.getTypePtr()))
7310         continue;
7311 
7312       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7313       if (ParamType == ValidKernelParam)
7314         continue;
7315 
7316       if (ParamType == RecordKernelParam) {
7317         VisitStack.push_back(FD);
7318         continue;
7319       }
7320 
7321       // OpenCL v1.2 s6.9.p:
7322       // Arguments to kernel functions that are declared to be a struct or union
7323       // do not allow OpenCL objects to be passed as elements of the struct or
7324       // union.
7325       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7326           ParamType == PrivatePtrKernelParam) {
7327         S.Diag(Param->getLocation(),
7328                diag::err_record_with_pointers_kernel_param)
7329           << PT->isUnionType()
7330           << PT;
7331       } else {
7332         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7333       }
7334 
7335       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7336         << PD->getDeclName();
7337 
7338       // We have an error, now let's go back up through history and show where
7339       // the offending field came from
7340       for (ArrayRef<const FieldDecl *>::const_iterator
7341                I = HistoryStack.begin() + 1,
7342                E = HistoryStack.end();
7343            I != E; ++I) {
7344         const FieldDecl *OuterField = *I;
7345         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7346           << OuterField->getType();
7347       }
7348 
7349       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7350         << QT->isPointerType()
7351         << QT;
7352       D.setInvalidType();
7353       return;
7354     }
7355   } while (!VisitStack.empty());
7356 }
7357 
7358 NamedDecl*
7359 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7360                               TypeSourceInfo *TInfo, LookupResult &Previous,
7361                               MultiTemplateParamsArg TemplateParamLists,
7362                               bool &AddToScope) {
7363   QualType R = TInfo->getType();
7364 
7365   assert(R.getTypePtr()->isFunctionType());
7366 
7367   // TODO: consider using NameInfo for diagnostic.
7368   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7369   DeclarationName Name = NameInfo.getName();
7370   StorageClass SC = getFunctionStorageClass(*this, D);
7371 
7372   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7373     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7374          diag::err_invalid_thread)
7375       << DeclSpec::getSpecifierName(TSCS);
7376 
7377   if (D.isFirstDeclarationOfMember())
7378     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7379                            D.getIdentifierLoc());
7380 
7381   bool isFriend = false;
7382   FunctionTemplateDecl *FunctionTemplate = nullptr;
7383   bool isExplicitSpecialization = false;
7384   bool isFunctionTemplateSpecialization = false;
7385 
7386   bool isDependentClassScopeExplicitSpecialization = false;
7387   bool HasExplicitTemplateArgs = false;
7388   TemplateArgumentListInfo TemplateArgs;
7389 
7390   bool isVirtualOkay = false;
7391 
7392   DeclContext *OriginalDC = DC;
7393   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7394 
7395   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7396                                               isVirtualOkay);
7397   if (!NewFD) return nullptr;
7398 
7399   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7400     NewFD->setTopLevelDeclInObjCContainer();
7401 
7402   // Set the lexical context. If this is a function-scope declaration, or has a
7403   // C++ scope specifier, or is the object of a friend declaration, the lexical
7404   // context will be different from the semantic context.
7405   NewFD->setLexicalDeclContext(CurContext);
7406 
7407   if (IsLocalExternDecl)
7408     NewFD->setLocalExternDecl();
7409 
7410   if (getLangOpts().CPlusPlus) {
7411     bool isInline = D.getDeclSpec().isInlineSpecified();
7412     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7413     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7414     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7415     bool isConcept = D.getDeclSpec().isConceptSpecified();
7416     isFriend = D.getDeclSpec().isFriendSpecified();
7417     if (isFriend && !isInline && D.isFunctionDefinition()) {
7418       // C++ [class.friend]p5
7419       //   A function can be defined in a friend declaration of a
7420       //   class . . . . Such a function is implicitly inline.
7421       NewFD->setImplicitlyInline();
7422     }
7423 
7424     // If this is a method defined in an __interface, and is not a constructor
7425     // or an overloaded operator, then set the pure flag (isVirtual will already
7426     // return true).
7427     if (const CXXRecordDecl *Parent =
7428           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7429       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7430         NewFD->setPure(true);
7431 
7432       // C++ [class.union]p2
7433       //   A union can have member functions, but not virtual functions.
7434       if (isVirtual && Parent->isUnion())
7435         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7436     }
7437 
7438     SetNestedNameSpecifier(NewFD, D);
7439     isExplicitSpecialization = false;
7440     isFunctionTemplateSpecialization = false;
7441     if (D.isInvalidType())
7442       NewFD->setInvalidDecl();
7443 
7444     // Match up the template parameter lists with the scope specifier, then
7445     // determine whether we have a template or a template specialization.
7446     bool Invalid = false;
7447     if (TemplateParameterList *TemplateParams =
7448             MatchTemplateParametersToScopeSpecifier(
7449                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7450                 D.getCXXScopeSpec(),
7451                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7452                     ? D.getName().TemplateId
7453                     : nullptr,
7454                 TemplateParamLists, isFriend, isExplicitSpecialization,
7455                 Invalid)) {
7456       if (TemplateParams->size() > 0) {
7457         // This is a function template
7458 
7459         // Check that we can declare a template here.
7460         if (CheckTemplateDeclScope(S, TemplateParams))
7461           NewFD->setInvalidDecl();
7462 
7463         // A destructor cannot be a template.
7464         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7465           Diag(NewFD->getLocation(), diag::err_destructor_template);
7466           NewFD->setInvalidDecl();
7467         }
7468 
7469         // If we're adding a template to a dependent context, we may need to
7470         // rebuilding some of the types used within the template parameter list,
7471         // now that we know what the current instantiation is.
7472         if (DC->isDependentContext()) {
7473           ContextRAII SavedContext(*this, DC);
7474           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7475             Invalid = true;
7476         }
7477 
7478 
7479         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7480                                                         NewFD->getLocation(),
7481                                                         Name, TemplateParams,
7482                                                         NewFD);
7483         FunctionTemplate->setLexicalDeclContext(CurContext);
7484         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7485 
7486         // For source fidelity, store the other template param lists.
7487         if (TemplateParamLists.size() > 1) {
7488           NewFD->setTemplateParameterListsInfo(Context,
7489                                                TemplateParamLists.drop_back(1));
7490         }
7491       } else {
7492         // This is a function template specialization.
7493         isFunctionTemplateSpecialization = true;
7494         // For source fidelity, store all the template param lists.
7495         if (TemplateParamLists.size() > 0)
7496           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7497 
7498         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7499         if (isFriend) {
7500           // We want to remove the "template<>", found here.
7501           SourceRange RemoveRange = TemplateParams->getSourceRange();
7502 
7503           // If we remove the template<> and the name is not a
7504           // template-id, we're actually silently creating a problem:
7505           // the friend declaration will refer to an untemplated decl,
7506           // and clearly the user wants a template specialization.  So
7507           // we need to insert '<>' after the name.
7508           SourceLocation InsertLoc;
7509           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7510             InsertLoc = D.getName().getSourceRange().getEnd();
7511             InsertLoc = getLocForEndOfToken(InsertLoc);
7512           }
7513 
7514           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7515             << Name << RemoveRange
7516             << FixItHint::CreateRemoval(RemoveRange)
7517             << FixItHint::CreateInsertion(InsertLoc, "<>");
7518         }
7519       }
7520     }
7521     else {
7522       // All template param lists were matched against the scope specifier:
7523       // this is NOT (an explicit specialization of) a template.
7524       if (TemplateParamLists.size() > 0)
7525         // For source fidelity, store all the template param lists.
7526         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7527     }
7528 
7529     if (Invalid) {
7530       NewFD->setInvalidDecl();
7531       if (FunctionTemplate)
7532         FunctionTemplate->setInvalidDecl();
7533     }
7534 
7535     // C++ [dcl.fct.spec]p5:
7536     //   The virtual specifier shall only be used in declarations of
7537     //   nonstatic class member functions that appear within a
7538     //   member-specification of a class declaration; see 10.3.
7539     //
7540     if (isVirtual && !NewFD->isInvalidDecl()) {
7541       if (!isVirtualOkay) {
7542         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7543              diag::err_virtual_non_function);
7544       } else if (!CurContext->isRecord()) {
7545         // 'virtual' was specified outside of the class.
7546         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7547              diag::err_virtual_out_of_class)
7548           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7549       } else if (NewFD->getDescribedFunctionTemplate()) {
7550         // C++ [temp.mem]p3:
7551         //  A member function template shall not be virtual.
7552         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7553              diag::err_virtual_member_function_template)
7554           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7555       } else {
7556         // Okay: Add virtual to the method.
7557         NewFD->setVirtualAsWritten(true);
7558       }
7559 
7560       if (getLangOpts().CPlusPlus14 &&
7561           NewFD->getReturnType()->isUndeducedType())
7562         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7563     }
7564 
7565     if (getLangOpts().CPlusPlus14 &&
7566         (NewFD->isDependentContext() ||
7567          (isFriend && CurContext->isDependentContext())) &&
7568         NewFD->getReturnType()->isUndeducedType()) {
7569       // If the function template is referenced directly (for instance, as a
7570       // member of the current instantiation), pretend it has a dependent type.
7571       // This is not really justified by the standard, but is the only sane
7572       // thing to do.
7573       // FIXME: For a friend function, we have not marked the function as being
7574       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7575       const FunctionProtoType *FPT =
7576           NewFD->getType()->castAs<FunctionProtoType>();
7577       QualType Result =
7578           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7579       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7580                                              FPT->getExtProtoInfo()));
7581     }
7582 
7583     // C++ [dcl.fct.spec]p3:
7584     //  The inline specifier shall not appear on a block scope function
7585     //  declaration.
7586     if (isInline && !NewFD->isInvalidDecl()) {
7587       if (CurContext->isFunctionOrMethod()) {
7588         // 'inline' is not allowed on block scope function declaration.
7589         Diag(D.getDeclSpec().getInlineSpecLoc(),
7590              diag::err_inline_declaration_block_scope) << Name
7591           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7592       }
7593     }
7594 
7595     // C++ [dcl.fct.spec]p6:
7596     //  The explicit specifier shall be used only in the declaration of a
7597     //  constructor or conversion function within its class definition;
7598     //  see 12.3.1 and 12.3.2.
7599     if (isExplicit && !NewFD->isInvalidDecl()) {
7600       if (!CurContext->isRecord()) {
7601         // 'explicit' was specified outside of the class.
7602         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7603              diag::err_explicit_out_of_class)
7604           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7605       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7606                  !isa<CXXConversionDecl>(NewFD)) {
7607         // 'explicit' was specified on a function that wasn't a constructor
7608         // or conversion function.
7609         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7610              diag::err_explicit_non_ctor_or_conv_function)
7611           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7612       }
7613     }
7614 
7615     if (isConstexpr) {
7616       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7617       // are implicitly inline.
7618       NewFD->setImplicitlyInline();
7619 
7620       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7621       // be either constructors or to return a literal type. Therefore,
7622       // destructors cannot be declared constexpr.
7623       if (isa<CXXDestructorDecl>(NewFD))
7624         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7625     }
7626 
7627     if (isConcept) {
7628       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7629       // applied only to the definition of a function template [...]
7630       if (!D.isFunctionDefinition()) {
7631         Diag(D.getDeclSpec().getConceptSpecLoc(),
7632              diag::err_function_concept_not_defined);
7633         NewFD->setInvalidDecl();
7634       }
7635 
7636       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7637       // have no exception-specification and is treated as if it were specified
7638       // with noexcept(true) (15.4). [...]
7639       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7640         if (FPT->hasExceptionSpec()) {
7641           SourceRange Range;
7642           if (D.isFunctionDeclarator())
7643             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7644           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7645               << FixItHint::CreateRemoval(Range);
7646           NewFD->setInvalidDecl();
7647         } else {
7648           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7649         }
7650 
7651         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7652         // following restrictions:
7653         // - The declaration's parameter list shall be equivalent to an empty
7654         //   parameter list.
7655         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7656           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7657       }
7658 
7659       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7660       // implicity defined to be a constexpr declaration (implicitly inline)
7661       NewFD->setImplicitlyInline();
7662 
7663       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7664       // be declared with the thread_local, inline, friend, or constexpr
7665       // specifiers, [...]
7666       if (isInline) {
7667         Diag(D.getDeclSpec().getInlineSpecLoc(),
7668              diag::err_concept_decl_invalid_specifiers)
7669             << 1 << 1;
7670         NewFD->setInvalidDecl(true);
7671       }
7672 
7673       if (isFriend) {
7674         Diag(D.getDeclSpec().getFriendSpecLoc(),
7675              diag::err_concept_decl_invalid_specifiers)
7676             << 1 << 2;
7677         NewFD->setInvalidDecl(true);
7678       }
7679 
7680       if (isConstexpr) {
7681         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7682              diag::err_concept_decl_invalid_specifiers)
7683             << 1 << 3;
7684         NewFD->setInvalidDecl(true);
7685       }
7686     }
7687 
7688     // If __module_private__ was specified, mark the function accordingly.
7689     if (D.getDeclSpec().isModulePrivateSpecified()) {
7690       if (isFunctionTemplateSpecialization) {
7691         SourceLocation ModulePrivateLoc
7692           = D.getDeclSpec().getModulePrivateSpecLoc();
7693         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7694           << 0
7695           << FixItHint::CreateRemoval(ModulePrivateLoc);
7696       } else {
7697         NewFD->setModulePrivate();
7698         if (FunctionTemplate)
7699           FunctionTemplate->setModulePrivate();
7700       }
7701     }
7702 
7703     if (isFriend) {
7704       if (FunctionTemplate) {
7705         FunctionTemplate->setObjectOfFriendDecl();
7706         FunctionTemplate->setAccess(AS_public);
7707       }
7708       NewFD->setObjectOfFriendDecl();
7709       NewFD->setAccess(AS_public);
7710     }
7711 
7712     // If a function is defined as defaulted or deleted, mark it as such now.
7713     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7714     // definition kind to FDK_Definition.
7715     switch (D.getFunctionDefinitionKind()) {
7716       case FDK_Declaration:
7717       case FDK_Definition:
7718         break;
7719 
7720       case FDK_Defaulted:
7721         NewFD->setDefaulted();
7722         break;
7723 
7724       case FDK_Deleted:
7725         NewFD->setDeletedAsWritten();
7726         break;
7727     }
7728 
7729     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7730         D.isFunctionDefinition()) {
7731       // C++ [class.mfct]p2:
7732       //   A member function may be defined (8.4) in its class definition, in
7733       //   which case it is an inline member function (7.1.2)
7734       NewFD->setImplicitlyInline();
7735     }
7736 
7737     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7738         !CurContext->isRecord()) {
7739       // C++ [class.static]p1:
7740       //   A data or function member of a class may be declared static
7741       //   in a class definition, in which case it is a static member of
7742       //   the class.
7743 
7744       // Complain about the 'static' specifier if it's on an out-of-line
7745       // member function definition.
7746       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7747            diag::err_static_out_of_line)
7748         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7749     }
7750 
7751     // C++11 [except.spec]p15:
7752     //   A deallocation function with no exception-specification is treated
7753     //   as if it were specified with noexcept(true).
7754     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7755     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7756          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7757         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7758       NewFD->setType(Context.getFunctionType(
7759           FPT->getReturnType(), FPT->getParamTypes(),
7760           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7761   }
7762 
7763   // Filter out previous declarations that don't match the scope.
7764   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7765                        D.getCXXScopeSpec().isNotEmpty() ||
7766                        isExplicitSpecialization ||
7767                        isFunctionTemplateSpecialization);
7768 
7769   // Handle GNU asm-label extension (encoded as an attribute).
7770   if (Expr *E = (Expr*) D.getAsmLabel()) {
7771     // The parser guarantees this is a string.
7772     StringLiteral *SE = cast<StringLiteral>(E);
7773     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7774                                                 SE->getString(), 0));
7775   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7776     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7777       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7778     if (I != ExtnameUndeclaredIdentifiers.end()) {
7779       if (isDeclExternC(NewFD)) {
7780         NewFD->addAttr(I->second);
7781         ExtnameUndeclaredIdentifiers.erase(I);
7782       } else
7783         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7784             << /*Variable*/0 << NewFD;
7785     }
7786   }
7787 
7788   // Copy the parameter declarations from the declarator D to the function
7789   // declaration NewFD, if they are available.  First scavenge them into Params.
7790   SmallVector<ParmVarDecl*, 16> Params;
7791   if (D.isFunctionDeclarator()) {
7792     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7793 
7794     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7795     // function that takes no arguments, not a function that takes a
7796     // single void argument.
7797     // We let through "const void" here because Sema::GetTypeForDeclarator
7798     // already checks for that case.
7799     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7800       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7801         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7802         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7803         Param->setDeclContext(NewFD);
7804         Params.push_back(Param);
7805 
7806         if (Param->isInvalidDecl())
7807           NewFD->setInvalidDecl();
7808       }
7809     }
7810 
7811   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7812     // When we're declaring a function with a typedef, typeof, etc as in the
7813     // following example, we'll need to synthesize (unnamed)
7814     // parameters for use in the declaration.
7815     //
7816     // @code
7817     // typedef void fn(int);
7818     // fn f;
7819     // @endcode
7820 
7821     // Synthesize a parameter for each argument type.
7822     for (const auto &AI : FT->param_types()) {
7823       ParmVarDecl *Param =
7824           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7825       Param->setScopeInfo(0, Params.size());
7826       Params.push_back(Param);
7827     }
7828   } else {
7829     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7830            "Should not need args for typedef of non-prototype fn");
7831   }
7832 
7833   // Finally, we know we have the right number of parameters, install them.
7834   NewFD->setParams(Params);
7835 
7836   // Find all anonymous symbols defined during the declaration of this function
7837   // and add to NewFD. This lets us track decls such 'enum Y' in:
7838   //
7839   //   void f(enum Y {AA} x) {}
7840   //
7841   // which would otherwise incorrectly end up in the translation unit scope.
7842   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7843   DeclsInPrototypeScope.clear();
7844 
7845   if (D.getDeclSpec().isNoreturnSpecified())
7846     NewFD->addAttr(
7847         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7848                                        Context, 0));
7849 
7850   // Functions returning a variably modified type violate C99 6.7.5.2p2
7851   // because all functions have linkage.
7852   if (!NewFD->isInvalidDecl() &&
7853       NewFD->getReturnType()->isVariablyModifiedType()) {
7854     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7855     NewFD->setInvalidDecl();
7856   }
7857 
7858   // Apply an implicit SectionAttr if #pragma code_seg is active.
7859   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7860       !NewFD->hasAttr<SectionAttr>()) {
7861     NewFD->addAttr(
7862         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7863                                     CodeSegStack.CurrentValue->getString(),
7864                                     CodeSegStack.CurrentPragmaLocation));
7865     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7866                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7867                          ASTContext::PSF_Read,
7868                      NewFD))
7869       NewFD->dropAttr<SectionAttr>();
7870   }
7871 
7872   // Handle attributes.
7873   ProcessDeclAttributes(S, NewFD, D);
7874 
7875   if (getLangOpts().OpenCL) {
7876     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7877     // type declaration will generate a compilation error.
7878     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7879     if (AddressSpace == LangAS::opencl_local ||
7880         AddressSpace == LangAS::opencl_global ||
7881         AddressSpace == LangAS::opencl_constant) {
7882       Diag(NewFD->getLocation(),
7883            diag::err_opencl_return_value_with_address_space);
7884       NewFD->setInvalidDecl();
7885     }
7886   }
7887 
7888   if (!getLangOpts().CPlusPlus) {
7889     // Perform semantic checking on the function declaration.
7890     bool isExplicitSpecialization=false;
7891     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7892       CheckMain(NewFD, D.getDeclSpec());
7893 
7894     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7895       CheckMSVCRTEntryPoint(NewFD);
7896 
7897     if (!NewFD->isInvalidDecl())
7898       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7899                                                   isExplicitSpecialization));
7900     else if (!Previous.empty())
7901       // Recover gracefully from an invalid redeclaration.
7902       D.setRedeclaration(true);
7903     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7904             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7905            "previous declaration set still overloaded");
7906 
7907     // Diagnose no-prototype function declarations with calling conventions that
7908     // don't support variadic calls. Only do this in C and do it after merging
7909     // possibly prototyped redeclarations.
7910     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7911     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7912       CallingConv CC = FT->getExtInfo().getCC();
7913       if (!supportsVariadicCall(CC)) {
7914         // Windows system headers sometimes accidentally use stdcall without
7915         // (void) parameters, so we relax this to a warning.
7916         int DiagID =
7917             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7918         Diag(NewFD->getLocation(), DiagID)
7919             << FunctionType::getNameForCallConv(CC);
7920       }
7921     }
7922   } else {
7923     // C++11 [replacement.functions]p3:
7924     //  The program's definitions shall not be specified as inline.
7925     //
7926     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7927     //
7928     // Suppress the diagnostic if the function is __attribute__((used)), since
7929     // that forces an external definition to be emitted.
7930     if (D.getDeclSpec().isInlineSpecified() &&
7931         NewFD->isReplaceableGlobalAllocationFunction() &&
7932         !NewFD->hasAttr<UsedAttr>())
7933       Diag(D.getDeclSpec().getInlineSpecLoc(),
7934            diag::ext_operator_new_delete_declared_inline)
7935         << NewFD->getDeclName();
7936 
7937     // If the declarator is a template-id, translate the parser's template
7938     // argument list into our AST format.
7939     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7940       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7941       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7942       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7943       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7944                                          TemplateId->NumArgs);
7945       translateTemplateArguments(TemplateArgsPtr,
7946                                  TemplateArgs);
7947 
7948       HasExplicitTemplateArgs = true;
7949 
7950       if (NewFD->isInvalidDecl()) {
7951         HasExplicitTemplateArgs = false;
7952       } else if (FunctionTemplate) {
7953         // Function template with explicit template arguments.
7954         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7955           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7956 
7957         HasExplicitTemplateArgs = false;
7958       } else {
7959         assert((isFunctionTemplateSpecialization ||
7960                 D.getDeclSpec().isFriendSpecified()) &&
7961                "should have a 'template<>' for this decl");
7962         // "friend void foo<>(int);" is an implicit specialization decl.
7963         isFunctionTemplateSpecialization = true;
7964       }
7965     } else if (isFriend && isFunctionTemplateSpecialization) {
7966       // This combination is only possible in a recovery case;  the user
7967       // wrote something like:
7968       //   template <> friend void foo(int);
7969       // which we're recovering from as if the user had written:
7970       //   friend void foo<>(int);
7971       // Go ahead and fake up a template id.
7972       HasExplicitTemplateArgs = true;
7973       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7974       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7975     }
7976 
7977     // If it's a friend (and only if it's a friend), it's possible
7978     // that either the specialized function type or the specialized
7979     // template is dependent, and therefore matching will fail.  In
7980     // this case, don't check the specialization yet.
7981     bool InstantiationDependent = false;
7982     if (isFunctionTemplateSpecialization && isFriend &&
7983         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7984          TemplateSpecializationType::anyDependentTemplateArguments(
7985             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7986             InstantiationDependent))) {
7987       assert(HasExplicitTemplateArgs &&
7988              "friend function specialization without template args");
7989       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7990                                                        Previous))
7991         NewFD->setInvalidDecl();
7992     } else if (isFunctionTemplateSpecialization) {
7993       if (CurContext->isDependentContext() && CurContext->isRecord()
7994           && !isFriend) {
7995         isDependentClassScopeExplicitSpecialization = true;
7996         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7997           diag::ext_function_specialization_in_class :
7998           diag::err_function_specialization_in_class)
7999           << NewFD->getDeclName();
8000       } else if (CheckFunctionTemplateSpecialization(NewFD,
8001                                   (HasExplicitTemplateArgs ? &TemplateArgs
8002                                                            : nullptr),
8003                                                      Previous))
8004         NewFD->setInvalidDecl();
8005 
8006       // C++ [dcl.stc]p1:
8007       //   A storage-class-specifier shall not be specified in an explicit
8008       //   specialization (14.7.3)
8009       FunctionTemplateSpecializationInfo *Info =
8010           NewFD->getTemplateSpecializationInfo();
8011       if (Info && SC != SC_None) {
8012         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8013           Diag(NewFD->getLocation(),
8014                diag::err_explicit_specialization_inconsistent_storage_class)
8015             << SC
8016             << FixItHint::CreateRemoval(
8017                                       D.getDeclSpec().getStorageClassSpecLoc());
8018 
8019         else
8020           Diag(NewFD->getLocation(),
8021                diag::ext_explicit_specialization_storage_class)
8022             << FixItHint::CreateRemoval(
8023                                       D.getDeclSpec().getStorageClassSpecLoc());
8024       }
8025 
8026     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8027       if (CheckMemberSpecialization(NewFD, Previous))
8028           NewFD->setInvalidDecl();
8029     }
8030 
8031     // Perform semantic checking on the function declaration.
8032     if (!isDependentClassScopeExplicitSpecialization) {
8033       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8034         CheckMain(NewFD, D.getDeclSpec());
8035 
8036       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8037         CheckMSVCRTEntryPoint(NewFD);
8038 
8039       if (!NewFD->isInvalidDecl())
8040         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8041                                                     isExplicitSpecialization));
8042       else if (!Previous.empty())
8043         // Recover gracefully from an invalid redeclaration.
8044         D.setRedeclaration(true);
8045     }
8046 
8047     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8048             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8049            "previous declaration set still overloaded");
8050 
8051     NamedDecl *PrincipalDecl = (FunctionTemplate
8052                                 ? cast<NamedDecl>(FunctionTemplate)
8053                                 : NewFD);
8054 
8055     if (isFriend && D.isRedeclaration()) {
8056       AccessSpecifier Access = AS_public;
8057       if (!NewFD->isInvalidDecl())
8058         Access = NewFD->getPreviousDecl()->getAccess();
8059 
8060       NewFD->setAccess(Access);
8061       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8062     }
8063 
8064     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8065         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8066       PrincipalDecl->setNonMemberOperator();
8067 
8068     // If we have a function template, check the template parameter
8069     // list. This will check and merge default template arguments.
8070     if (FunctionTemplate) {
8071       FunctionTemplateDecl *PrevTemplate =
8072                                      FunctionTemplate->getPreviousDecl();
8073       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8074                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8075                                     : nullptr,
8076                             D.getDeclSpec().isFriendSpecified()
8077                               ? (D.isFunctionDefinition()
8078                                    ? TPC_FriendFunctionTemplateDefinition
8079                                    : TPC_FriendFunctionTemplate)
8080                               : (D.getCXXScopeSpec().isSet() &&
8081                                  DC && DC->isRecord() &&
8082                                  DC->isDependentContext())
8083                                   ? TPC_ClassTemplateMember
8084                                   : TPC_FunctionTemplate);
8085     }
8086 
8087     if (NewFD->isInvalidDecl()) {
8088       // Ignore all the rest of this.
8089     } else if (!D.isRedeclaration()) {
8090       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8091                                        AddToScope };
8092       // Fake up an access specifier if it's supposed to be a class member.
8093       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8094         NewFD->setAccess(AS_public);
8095 
8096       // Qualified decls generally require a previous declaration.
8097       if (D.getCXXScopeSpec().isSet()) {
8098         // ...with the major exception of templated-scope or
8099         // dependent-scope friend declarations.
8100 
8101         // TODO: we currently also suppress this check in dependent
8102         // contexts because (1) the parameter depth will be off when
8103         // matching friend templates and (2) we might actually be
8104         // selecting a friend based on a dependent factor.  But there
8105         // are situations where these conditions don't apply and we
8106         // can actually do this check immediately.
8107         if (isFriend &&
8108             (TemplateParamLists.size() ||
8109              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8110              CurContext->isDependentContext())) {
8111           // ignore these
8112         } else {
8113           // The user tried to provide an out-of-line definition for a
8114           // function that is a member of a class or namespace, but there
8115           // was no such member function declared (C++ [class.mfct]p2,
8116           // C++ [namespace.memdef]p2). For example:
8117           //
8118           // class X {
8119           //   void f() const;
8120           // };
8121           //
8122           // void X::f() { } // ill-formed
8123           //
8124           // Complain about this problem, and attempt to suggest close
8125           // matches (e.g., those that differ only in cv-qualifiers and
8126           // whether the parameter types are references).
8127 
8128           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8129                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8130             AddToScope = ExtraArgs.AddToScope;
8131             return Result;
8132           }
8133         }
8134 
8135         // Unqualified local friend declarations are required to resolve
8136         // to something.
8137       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8138         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8139                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8140           AddToScope = ExtraArgs.AddToScope;
8141           return Result;
8142         }
8143       }
8144 
8145     } else if (!D.isFunctionDefinition() &&
8146                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8147                !isFriend && !isFunctionTemplateSpecialization &&
8148                !isExplicitSpecialization) {
8149       // An out-of-line member function declaration must also be a
8150       // definition (C++ [class.mfct]p2).
8151       // Note that this is not the case for explicit specializations of
8152       // function templates or member functions of class templates, per
8153       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8154       // extension for compatibility with old SWIG code which likes to
8155       // generate them.
8156       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8157         << D.getCXXScopeSpec().getRange();
8158     }
8159   }
8160 
8161   ProcessPragmaWeak(S, NewFD);
8162   checkAttributesAfterMerging(*this, *NewFD);
8163 
8164   AddKnownFunctionAttributes(NewFD);
8165 
8166   if (NewFD->hasAttr<OverloadableAttr>() &&
8167       !NewFD->getType()->getAs<FunctionProtoType>()) {
8168     Diag(NewFD->getLocation(),
8169          diag::err_attribute_overloadable_no_prototype)
8170       << NewFD;
8171 
8172     // Turn this into a variadic function with no parameters.
8173     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8174     FunctionProtoType::ExtProtoInfo EPI(
8175         Context.getDefaultCallingConvention(true, false));
8176     EPI.Variadic = true;
8177     EPI.ExtInfo = FT->getExtInfo();
8178 
8179     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8180     NewFD->setType(R);
8181   }
8182 
8183   // If there's a #pragma GCC visibility in scope, and this isn't a class
8184   // member, set the visibility of this function.
8185   if (!DC->isRecord() && NewFD->isExternallyVisible())
8186     AddPushedVisibilityAttribute(NewFD);
8187 
8188   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8189   // marking the function.
8190   AddCFAuditedAttribute(NewFD);
8191 
8192   // If this is a function definition, check if we have to apply optnone due to
8193   // a pragma.
8194   if(D.isFunctionDefinition())
8195     AddRangeBasedOptnone(NewFD);
8196 
8197   // If this is the first declaration of an extern C variable, update
8198   // the map of such variables.
8199   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8200       isIncompleteDeclExternC(*this, NewFD))
8201     RegisterLocallyScopedExternCDecl(NewFD, S);
8202 
8203   // Set this FunctionDecl's range up to the right paren.
8204   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8205 
8206   if (D.isRedeclaration() && !Previous.empty()) {
8207     checkDLLAttributeRedeclaration(
8208         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8209         isExplicitSpecialization || isFunctionTemplateSpecialization);
8210   }
8211 
8212   if (getLangOpts().CPlusPlus) {
8213     if (FunctionTemplate) {
8214       if (NewFD->isInvalidDecl())
8215         FunctionTemplate->setInvalidDecl();
8216       return FunctionTemplate;
8217     }
8218   }
8219 
8220   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8221     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8222     if ((getLangOpts().OpenCLVersion >= 120)
8223         && (SC == SC_Static)) {
8224       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8225       D.setInvalidType();
8226     }
8227 
8228     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8229     if (!NewFD->getReturnType()->isVoidType()) {
8230       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8231       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8232           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8233                                 : FixItHint());
8234       D.setInvalidType();
8235     }
8236 
8237     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8238     for (auto Param : NewFD->params())
8239       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8240   }
8241 
8242   MarkUnusedFileScopedDecl(NewFD);
8243 
8244   if (getLangOpts().CUDA)
8245     if (IdentifierInfo *II = NewFD->getIdentifier())
8246       if (!NewFD->isInvalidDecl() &&
8247           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8248         if (II->isStr("cudaConfigureCall")) {
8249           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8250             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8251 
8252           Context.setcudaConfigureCallDecl(NewFD);
8253         }
8254       }
8255 
8256   // Here we have an function template explicit specialization at class scope.
8257   // The actually specialization will be postponed to template instatiation
8258   // time via the ClassScopeFunctionSpecializationDecl node.
8259   if (isDependentClassScopeExplicitSpecialization) {
8260     ClassScopeFunctionSpecializationDecl *NewSpec =
8261                          ClassScopeFunctionSpecializationDecl::Create(
8262                                 Context, CurContext, SourceLocation(),
8263                                 cast<CXXMethodDecl>(NewFD),
8264                                 HasExplicitTemplateArgs, TemplateArgs);
8265     CurContext->addDecl(NewSpec);
8266     AddToScope = false;
8267   }
8268 
8269   return NewFD;
8270 }
8271 
8272 /// \brief Perform semantic checking of a new function declaration.
8273 ///
8274 /// Performs semantic analysis of the new function declaration
8275 /// NewFD. This routine performs all semantic checking that does not
8276 /// require the actual declarator involved in the declaration, and is
8277 /// used both for the declaration of functions as they are parsed
8278 /// (called via ActOnDeclarator) and for the declaration of functions
8279 /// that have been instantiated via C++ template instantiation (called
8280 /// via InstantiateDecl).
8281 ///
8282 /// \param IsExplicitSpecialization whether this new function declaration is
8283 /// an explicit specialization of the previous declaration.
8284 ///
8285 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8286 ///
8287 /// \returns true if the function declaration is a redeclaration.
8288 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8289                                     LookupResult &Previous,
8290                                     bool IsExplicitSpecialization) {
8291   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8292          "Variably modified return types are not handled here");
8293 
8294   // Determine whether the type of this function should be merged with
8295   // a previous visible declaration. This never happens for functions in C++,
8296   // and always happens in C if the previous declaration was visible.
8297   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8298                                !Previous.isShadowed();
8299 
8300   bool Redeclaration = false;
8301   NamedDecl *OldDecl = nullptr;
8302 
8303   // Merge or overload the declaration with an existing declaration of
8304   // the same name, if appropriate.
8305   if (!Previous.empty()) {
8306     // Determine whether NewFD is an overload of PrevDecl or
8307     // a declaration that requires merging. If it's an overload,
8308     // there's no more work to do here; we'll just add the new
8309     // function to the scope.
8310     if (!AllowOverloadingOfFunction(Previous, Context)) {
8311       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8312       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8313         Redeclaration = true;
8314         OldDecl = Candidate;
8315       }
8316     } else {
8317       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8318                             /*NewIsUsingDecl*/ false)) {
8319       case Ovl_Match:
8320         Redeclaration = true;
8321         break;
8322 
8323       case Ovl_NonFunction:
8324         Redeclaration = true;
8325         break;
8326 
8327       case Ovl_Overload:
8328         Redeclaration = false;
8329         break;
8330       }
8331 
8332       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8333         // If a function name is overloadable in C, then every function
8334         // with that name must be marked "overloadable".
8335         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8336           << Redeclaration << NewFD;
8337         NamedDecl *OverloadedDecl = nullptr;
8338         if (Redeclaration)
8339           OverloadedDecl = OldDecl;
8340         else if (!Previous.empty())
8341           OverloadedDecl = Previous.getRepresentativeDecl();
8342         if (OverloadedDecl)
8343           Diag(OverloadedDecl->getLocation(),
8344                diag::note_attribute_overloadable_prev_overload);
8345         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8346       }
8347     }
8348   }
8349 
8350   // Check for a previous extern "C" declaration with this name.
8351   if (!Redeclaration &&
8352       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8353     if (!Previous.empty()) {
8354       // This is an extern "C" declaration with the same name as a previous
8355       // declaration, and thus redeclares that entity...
8356       Redeclaration = true;
8357       OldDecl = Previous.getFoundDecl();
8358       MergeTypeWithPrevious = false;
8359 
8360       // ... except in the presence of __attribute__((overloadable)).
8361       if (OldDecl->hasAttr<OverloadableAttr>()) {
8362         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8363           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8364             << Redeclaration << NewFD;
8365           Diag(Previous.getFoundDecl()->getLocation(),
8366                diag::note_attribute_overloadable_prev_overload);
8367           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8368         }
8369         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8370           Redeclaration = false;
8371           OldDecl = nullptr;
8372         }
8373       }
8374     }
8375   }
8376 
8377   // C++11 [dcl.constexpr]p8:
8378   //   A constexpr specifier for a non-static member function that is not
8379   //   a constructor declares that member function to be const.
8380   //
8381   // This needs to be delayed until we know whether this is an out-of-line
8382   // definition of a static member function.
8383   //
8384   // This rule is not present in C++1y, so we produce a backwards
8385   // compatibility warning whenever it happens in C++11.
8386   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8387   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8388       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8389       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8390     CXXMethodDecl *OldMD = nullptr;
8391     if (OldDecl)
8392       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8393     if (!OldMD || !OldMD->isStatic()) {
8394       const FunctionProtoType *FPT =
8395         MD->getType()->castAs<FunctionProtoType>();
8396       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8397       EPI.TypeQuals |= Qualifiers::Const;
8398       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8399                                           FPT->getParamTypes(), EPI));
8400 
8401       // Warn that we did this, if we're not performing template instantiation.
8402       // In that case, we'll have warned already when the template was defined.
8403       if (ActiveTemplateInstantiations.empty()) {
8404         SourceLocation AddConstLoc;
8405         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8406                 .IgnoreParens().getAs<FunctionTypeLoc>())
8407           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8408 
8409         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8410           << FixItHint::CreateInsertion(AddConstLoc, " const");
8411       }
8412     }
8413   }
8414 
8415   if (Redeclaration) {
8416     // NewFD and OldDecl represent declarations that need to be
8417     // merged.
8418     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8419       NewFD->setInvalidDecl();
8420       return Redeclaration;
8421     }
8422 
8423     Previous.clear();
8424     Previous.addDecl(OldDecl);
8425 
8426     if (FunctionTemplateDecl *OldTemplateDecl
8427                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8428       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8429       FunctionTemplateDecl *NewTemplateDecl
8430         = NewFD->getDescribedFunctionTemplate();
8431       assert(NewTemplateDecl && "Template/non-template mismatch");
8432       if (CXXMethodDecl *Method
8433             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8434         Method->setAccess(OldTemplateDecl->getAccess());
8435         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8436       }
8437 
8438       // If this is an explicit specialization of a member that is a function
8439       // template, mark it as a member specialization.
8440       if (IsExplicitSpecialization &&
8441           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8442         NewTemplateDecl->setMemberSpecialization();
8443         assert(OldTemplateDecl->isMemberSpecialization());
8444       }
8445 
8446     } else {
8447       // This needs to happen first so that 'inline' propagates.
8448       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8449 
8450       if (isa<CXXMethodDecl>(NewFD))
8451         NewFD->setAccess(OldDecl->getAccess());
8452     }
8453   }
8454 
8455   // Semantic checking for this function declaration (in isolation).
8456 
8457   if (getLangOpts().CPlusPlus) {
8458     // C++-specific checks.
8459     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8460       CheckConstructor(Constructor);
8461     } else if (CXXDestructorDecl *Destructor =
8462                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8463       CXXRecordDecl *Record = Destructor->getParent();
8464       QualType ClassType = Context.getTypeDeclType(Record);
8465 
8466       // FIXME: Shouldn't we be able to perform this check even when the class
8467       // type is dependent? Both gcc and edg can handle that.
8468       if (!ClassType->isDependentType()) {
8469         DeclarationName Name
8470           = Context.DeclarationNames.getCXXDestructorName(
8471                                         Context.getCanonicalType(ClassType));
8472         if (NewFD->getDeclName() != Name) {
8473           Diag(NewFD->getLocation(), diag::err_destructor_name);
8474           NewFD->setInvalidDecl();
8475           return Redeclaration;
8476         }
8477       }
8478     } else if (CXXConversionDecl *Conversion
8479                = dyn_cast<CXXConversionDecl>(NewFD)) {
8480       ActOnConversionDeclarator(Conversion);
8481     }
8482 
8483     // Find any virtual functions that this function overrides.
8484     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8485       if (!Method->isFunctionTemplateSpecialization() &&
8486           !Method->getDescribedFunctionTemplate() &&
8487           Method->isCanonicalDecl()) {
8488         if (AddOverriddenMethods(Method->getParent(), Method)) {
8489           // If the function was marked as "static", we have a problem.
8490           if (NewFD->getStorageClass() == SC_Static) {
8491             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8492           }
8493         }
8494       }
8495 
8496       if (Method->isStatic())
8497         checkThisInStaticMemberFunctionType(Method);
8498     }
8499 
8500     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8501     if (NewFD->isOverloadedOperator() &&
8502         CheckOverloadedOperatorDeclaration(NewFD)) {
8503       NewFD->setInvalidDecl();
8504       return Redeclaration;
8505     }
8506 
8507     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8508     if (NewFD->getLiteralIdentifier() &&
8509         CheckLiteralOperatorDeclaration(NewFD)) {
8510       NewFD->setInvalidDecl();
8511       return Redeclaration;
8512     }
8513 
8514     // In C++, check default arguments now that we have merged decls. Unless
8515     // the lexical context is the class, because in this case this is done
8516     // during delayed parsing anyway.
8517     if (!CurContext->isRecord())
8518       CheckCXXDefaultArguments(NewFD);
8519 
8520     // If this function declares a builtin function, check the type of this
8521     // declaration against the expected type for the builtin.
8522     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8523       ASTContext::GetBuiltinTypeError Error;
8524       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8525       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8526       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8527         // The type of this function differs from the type of the builtin,
8528         // so forget about the builtin entirely.
8529         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8530       }
8531     }
8532 
8533     // If this function is declared as being extern "C", then check to see if
8534     // the function returns a UDT (class, struct, or union type) that is not C
8535     // compatible, and if it does, warn the user.
8536     // But, issue any diagnostic on the first declaration only.
8537     if (Previous.empty() && NewFD->isExternC()) {
8538       QualType R = NewFD->getReturnType();
8539       if (R->isIncompleteType() && !R->isVoidType())
8540         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8541             << NewFD << R;
8542       else if (!R.isPODType(Context) && !R->isVoidType() &&
8543                !R->isObjCObjectPointerType())
8544         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8545     }
8546   }
8547   return Redeclaration;
8548 }
8549 
8550 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8551   // C++11 [basic.start.main]p3:
8552   //   A program that [...] declares main to be inline, static or
8553   //   constexpr is ill-formed.
8554   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8555   //   appear in a declaration of main.
8556   // static main is not an error under C99, but we should warn about it.
8557   // We accept _Noreturn main as an extension.
8558   if (FD->getStorageClass() == SC_Static)
8559     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8560          ? diag::err_static_main : diag::warn_static_main)
8561       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8562   if (FD->isInlineSpecified())
8563     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8564       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8565   if (DS.isNoreturnSpecified()) {
8566     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8567     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8568     Diag(NoreturnLoc, diag::ext_noreturn_main);
8569     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8570       << FixItHint::CreateRemoval(NoreturnRange);
8571   }
8572   if (FD->isConstexpr()) {
8573     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8574       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8575     FD->setConstexpr(false);
8576   }
8577 
8578   if (getLangOpts().OpenCL) {
8579     Diag(FD->getLocation(), diag::err_opencl_no_main)
8580         << FD->hasAttr<OpenCLKernelAttr>();
8581     FD->setInvalidDecl();
8582     return;
8583   }
8584 
8585   QualType T = FD->getType();
8586   assert(T->isFunctionType() && "function decl is not of function type");
8587   const FunctionType* FT = T->castAs<FunctionType>();
8588 
8589   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8590     // In C with GNU extensions we allow main() to have non-integer return
8591     // type, but we should warn about the extension, and we disable the
8592     // implicit-return-zero rule.
8593 
8594     // GCC in C mode accepts qualified 'int'.
8595     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8596       FD->setHasImplicitReturnZero(true);
8597     else {
8598       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8599       SourceRange RTRange = FD->getReturnTypeSourceRange();
8600       if (RTRange.isValid())
8601         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8602             << FixItHint::CreateReplacement(RTRange, "int");
8603     }
8604   } else {
8605     // In C and C++, main magically returns 0 if you fall off the end;
8606     // set the flag which tells us that.
8607     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8608 
8609     // All the standards say that main() should return 'int'.
8610     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8611       FD->setHasImplicitReturnZero(true);
8612     else {
8613       // Otherwise, this is just a flat-out error.
8614       SourceRange RTRange = FD->getReturnTypeSourceRange();
8615       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8616           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8617                                 : FixItHint());
8618       FD->setInvalidDecl(true);
8619     }
8620   }
8621 
8622   // Treat protoless main() as nullary.
8623   if (isa<FunctionNoProtoType>(FT)) return;
8624 
8625   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8626   unsigned nparams = FTP->getNumParams();
8627   assert(FD->getNumParams() == nparams);
8628 
8629   bool HasExtraParameters = (nparams > 3);
8630 
8631   if (FTP->isVariadic()) {
8632     Diag(FD->getLocation(), diag::ext_variadic_main);
8633     // FIXME: if we had information about the location of the ellipsis, we
8634     // could add a FixIt hint to remove it as a parameter.
8635   }
8636 
8637   // Darwin passes an undocumented fourth argument of type char**.  If
8638   // other platforms start sprouting these, the logic below will start
8639   // getting shifty.
8640   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8641     HasExtraParameters = false;
8642 
8643   if (HasExtraParameters) {
8644     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8645     FD->setInvalidDecl(true);
8646     nparams = 3;
8647   }
8648 
8649   // FIXME: a lot of the following diagnostics would be improved
8650   // if we had some location information about types.
8651 
8652   QualType CharPP =
8653     Context.getPointerType(Context.getPointerType(Context.CharTy));
8654   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8655 
8656   for (unsigned i = 0; i < nparams; ++i) {
8657     QualType AT = FTP->getParamType(i);
8658 
8659     bool mismatch = true;
8660 
8661     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8662       mismatch = false;
8663     else if (Expected[i] == CharPP) {
8664       // As an extension, the following forms are okay:
8665       //   char const **
8666       //   char const * const *
8667       //   char * const *
8668 
8669       QualifierCollector qs;
8670       const PointerType* PT;
8671       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8672           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8673           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8674                               Context.CharTy)) {
8675         qs.removeConst();
8676         mismatch = !qs.empty();
8677       }
8678     }
8679 
8680     if (mismatch) {
8681       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8682       // TODO: suggest replacing given type with expected type
8683       FD->setInvalidDecl(true);
8684     }
8685   }
8686 
8687   if (nparams == 1 && !FD->isInvalidDecl()) {
8688     Diag(FD->getLocation(), diag::warn_main_one_arg);
8689   }
8690 
8691   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8692     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8693     FD->setInvalidDecl();
8694   }
8695 }
8696 
8697 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8698   QualType T = FD->getType();
8699   assert(T->isFunctionType() && "function decl is not of function type");
8700   const FunctionType *FT = T->castAs<FunctionType>();
8701 
8702   // Set an implicit return of 'zero' if the function can return some integral,
8703   // enumeration, pointer or nullptr type.
8704   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8705       FT->getReturnType()->isAnyPointerType() ||
8706       FT->getReturnType()->isNullPtrType())
8707     // DllMain is exempt because a return value of zero means it failed.
8708     if (FD->getName() != "DllMain")
8709       FD->setHasImplicitReturnZero(true);
8710 
8711   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8712     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8713     FD->setInvalidDecl();
8714   }
8715 }
8716 
8717 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8718   // FIXME: Need strict checking.  In C89, we need to check for
8719   // any assignment, increment, decrement, function-calls, or
8720   // commas outside of a sizeof.  In C99, it's the same list,
8721   // except that the aforementioned are allowed in unevaluated
8722   // expressions.  Everything else falls under the
8723   // "may accept other forms of constant expressions" exception.
8724   // (We never end up here for C++, so the constant expression
8725   // rules there don't matter.)
8726   const Expr *Culprit;
8727   if (Init->isConstantInitializer(Context, false, &Culprit))
8728     return false;
8729   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8730     << Culprit->getSourceRange();
8731   return true;
8732 }
8733 
8734 namespace {
8735   // Visits an initialization expression to see if OrigDecl is evaluated in
8736   // its own initialization and throws a warning if it does.
8737   class SelfReferenceChecker
8738       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8739     Sema &S;
8740     Decl *OrigDecl;
8741     bool isRecordType;
8742     bool isPODType;
8743     bool isReferenceType;
8744 
8745     bool isInitList;
8746     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8747   public:
8748     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8749 
8750     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8751                                                     S(S), OrigDecl(OrigDecl) {
8752       isPODType = false;
8753       isRecordType = false;
8754       isReferenceType = false;
8755       isInitList = false;
8756       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8757         isPODType = VD->getType().isPODType(S.Context);
8758         isRecordType = VD->getType()->isRecordType();
8759         isReferenceType = VD->getType()->isReferenceType();
8760       }
8761     }
8762 
8763     // For most expressions, just call the visitor.  For initializer lists,
8764     // track the index of the field being initialized since fields are
8765     // initialized in order allowing use of previously initialized fields.
8766     void CheckExpr(Expr *E) {
8767       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8768       if (!InitList) {
8769         Visit(E);
8770         return;
8771       }
8772 
8773       // Track and increment the index here.
8774       isInitList = true;
8775       InitFieldIndex.push_back(0);
8776       for (auto Child : InitList->children()) {
8777         CheckExpr(cast<Expr>(Child));
8778         ++InitFieldIndex.back();
8779       }
8780       InitFieldIndex.pop_back();
8781     }
8782 
8783     // Returns true if MemberExpr is checked and no futher checking is needed.
8784     // Returns false if additional checking is required.
8785     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8786       llvm::SmallVector<FieldDecl*, 4> Fields;
8787       Expr *Base = E;
8788       bool ReferenceField = false;
8789 
8790       // Get the field memebers used.
8791       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8792         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8793         if (!FD)
8794           return false;
8795         Fields.push_back(FD);
8796         if (FD->getType()->isReferenceType())
8797           ReferenceField = true;
8798         Base = ME->getBase()->IgnoreParenImpCasts();
8799       }
8800 
8801       // Keep checking only if the base Decl is the same.
8802       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8803       if (!DRE || DRE->getDecl() != OrigDecl)
8804         return false;
8805 
8806       // A reference field can be bound to an unininitialized field.
8807       if (CheckReference && !ReferenceField)
8808         return true;
8809 
8810       // Convert FieldDecls to their index number.
8811       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8812       for (const FieldDecl *I : llvm::reverse(Fields))
8813         UsedFieldIndex.push_back(I->getFieldIndex());
8814 
8815       // See if a warning is needed by checking the first difference in index
8816       // numbers.  If field being used has index less than the field being
8817       // initialized, then the use is safe.
8818       for (auto UsedIter = UsedFieldIndex.begin(),
8819                 UsedEnd = UsedFieldIndex.end(),
8820                 OrigIter = InitFieldIndex.begin(),
8821                 OrigEnd = InitFieldIndex.end();
8822            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8823         if (*UsedIter < *OrigIter)
8824           return true;
8825         if (*UsedIter > *OrigIter)
8826           break;
8827       }
8828 
8829       // TODO: Add a different warning which will print the field names.
8830       HandleDeclRefExpr(DRE);
8831       return true;
8832     }
8833 
8834     // For most expressions, the cast is directly above the DeclRefExpr.
8835     // For conditional operators, the cast can be outside the conditional
8836     // operator if both expressions are DeclRefExpr's.
8837     void HandleValue(Expr *E) {
8838       E = E->IgnoreParens();
8839       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8840         HandleDeclRefExpr(DRE);
8841         return;
8842       }
8843 
8844       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8845         Visit(CO->getCond());
8846         HandleValue(CO->getTrueExpr());
8847         HandleValue(CO->getFalseExpr());
8848         return;
8849       }
8850 
8851       if (BinaryConditionalOperator *BCO =
8852               dyn_cast<BinaryConditionalOperator>(E)) {
8853         Visit(BCO->getCond());
8854         HandleValue(BCO->getFalseExpr());
8855         return;
8856       }
8857 
8858       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8859         HandleValue(OVE->getSourceExpr());
8860         return;
8861       }
8862 
8863       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8864         if (BO->getOpcode() == BO_Comma) {
8865           Visit(BO->getLHS());
8866           HandleValue(BO->getRHS());
8867           return;
8868         }
8869       }
8870 
8871       if (isa<MemberExpr>(E)) {
8872         if (isInitList) {
8873           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8874                                       false /*CheckReference*/))
8875             return;
8876         }
8877 
8878         Expr *Base = E->IgnoreParenImpCasts();
8879         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8880           // Check for static member variables and don't warn on them.
8881           if (!isa<FieldDecl>(ME->getMemberDecl()))
8882             return;
8883           Base = ME->getBase()->IgnoreParenImpCasts();
8884         }
8885         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8886           HandleDeclRefExpr(DRE);
8887         return;
8888       }
8889 
8890       Visit(E);
8891     }
8892 
8893     // Reference types not handled in HandleValue are handled here since all
8894     // uses of references are bad, not just r-value uses.
8895     void VisitDeclRefExpr(DeclRefExpr *E) {
8896       if (isReferenceType)
8897         HandleDeclRefExpr(E);
8898     }
8899 
8900     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8901       if (E->getCastKind() == CK_LValueToRValue) {
8902         HandleValue(E->getSubExpr());
8903         return;
8904       }
8905 
8906       Inherited::VisitImplicitCastExpr(E);
8907     }
8908 
8909     void VisitMemberExpr(MemberExpr *E) {
8910       if (isInitList) {
8911         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8912           return;
8913       }
8914 
8915       // Don't warn on arrays since they can be treated as pointers.
8916       if (E->getType()->canDecayToPointerType()) return;
8917 
8918       // Warn when a non-static method call is followed by non-static member
8919       // field accesses, which is followed by a DeclRefExpr.
8920       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8921       bool Warn = (MD && !MD->isStatic());
8922       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8923       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8924         if (!isa<FieldDecl>(ME->getMemberDecl()))
8925           Warn = false;
8926         Base = ME->getBase()->IgnoreParenImpCasts();
8927       }
8928 
8929       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8930         if (Warn)
8931           HandleDeclRefExpr(DRE);
8932         return;
8933       }
8934 
8935       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8936       // Visit that expression.
8937       Visit(Base);
8938     }
8939 
8940     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8941       Expr *Callee = E->getCallee();
8942 
8943       if (isa<UnresolvedLookupExpr>(Callee))
8944         return Inherited::VisitCXXOperatorCallExpr(E);
8945 
8946       Visit(Callee);
8947       for (auto Arg: E->arguments())
8948         HandleValue(Arg->IgnoreParenImpCasts());
8949     }
8950 
8951     void VisitUnaryOperator(UnaryOperator *E) {
8952       // For POD record types, addresses of its own members are well-defined.
8953       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8954           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8955         if (!isPODType)
8956           HandleValue(E->getSubExpr());
8957         return;
8958       }
8959 
8960       if (E->isIncrementDecrementOp()) {
8961         HandleValue(E->getSubExpr());
8962         return;
8963       }
8964 
8965       Inherited::VisitUnaryOperator(E);
8966     }
8967 
8968     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8969 
8970     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8971       if (E->getConstructor()->isCopyConstructor()) {
8972         Expr *ArgExpr = E->getArg(0);
8973         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8974           if (ILE->getNumInits() == 1)
8975             ArgExpr = ILE->getInit(0);
8976         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8977           if (ICE->getCastKind() == CK_NoOp)
8978             ArgExpr = ICE->getSubExpr();
8979         HandleValue(ArgExpr);
8980         return;
8981       }
8982       Inherited::VisitCXXConstructExpr(E);
8983     }
8984 
8985     void VisitCallExpr(CallExpr *E) {
8986       // Treat std::move as a use.
8987       if (E->getNumArgs() == 1) {
8988         if (FunctionDecl *FD = E->getDirectCallee()) {
8989           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8990               FD->getIdentifier()->isStr("move")) {
8991             HandleValue(E->getArg(0));
8992             return;
8993           }
8994         }
8995       }
8996 
8997       Inherited::VisitCallExpr(E);
8998     }
8999 
9000     void VisitBinaryOperator(BinaryOperator *E) {
9001       if (E->isCompoundAssignmentOp()) {
9002         HandleValue(E->getLHS());
9003         Visit(E->getRHS());
9004         return;
9005       }
9006 
9007       Inherited::VisitBinaryOperator(E);
9008     }
9009 
9010     // A custom visitor for BinaryConditionalOperator is needed because the
9011     // regular visitor would check the condition and true expression separately
9012     // but both point to the same place giving duplicate diagnostics.
9013     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9014       Visit(E->getCond());
9015       Visit(E->getFalseExpr());
9016     }
9017 
9018     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9019       Decl* ReferenceDecl = DRE->getDecl();
9020       if (OrigDecl != ReferenceDecl) return;
9021       unsigned diag;
9022       if (isReferenceType) {
9023         diag = diag::warn_uninit_self_reference_in_reference_init;
9024       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9025         diag = diag::warn_static_self_reference_in_init;
9026       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9027                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9028                  DRE->getDecl()->getType()->isRecordType()) {
9029         diag = diag::warn_uninit_self_reference_in_init;
9030       } else {
9031         // Local variables will be handled by the CFG analysis.
9032         return;
9033       }
9034 
9035       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9036                             S.PDiag(diag)
9037                               << DRE->getNameInfo().getName()
9038                               << OrigDecl->getLocation()
9039                               << DRE->getSourceRange());
9040     }
9041   };
9042 
9043   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9044   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9045                                  bool DirectInit) {
9046     // Parameters arguments are occassionially constructed with itself,
9047     // for instance, in recursive functions.  Skip them.
9048     if (isa<ParmVarDecl>(OrigDecl))
9049       return;
9050 
9051     E = E->IgnoreParens();
9052 
9053     // Skip checking T a = a where T is not a record or reference type.
9054     // Doing so is a way to silence uninitialized warnings.
9055     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9056       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9057         if (ICE->getCastKind() == CK_LValueToRValue)
9058           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9059             if (DRE->getDecl() == OrigDecl)
9060               return;
9061 
9062     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9063   }
9064 }
9065 
9066 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9067                                             DeclarationName Name, QualType Type,
9068                                             TypeSourceInfo *TSI,
9069                                             SourceRange Range, bool DirectInit,
9070                                             Expr *Init) {
9071   bool IsInitCapture = !VDecl;
9072   assert((!VDecl || !VDecl->isInitCapture()) &&
9073          "init captures are expected to be deduced prior to initialization");
9074 
9075   ArrayRef<Expr *> DeduceInits = Init;
9076   if (DirectInit) {
9077     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9078       DeduceInits = PL->exprs();
9079     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9080       DeduceInits = IL->inits();
9081   }
9082 
9083   // Deduction only works if we have exactly one source expression.
9084   if (DeduceInits.empty()) {
9085     // It isn't possible to write this directly, but it is possible to
9086     // end up in this situation with "auto x(some_pack...);"
9087     Diag(Init->getLocStart(), IsInitCapture
9088                                   ? diag::err_init_capture_no_expression
9089                                   : diag::err_auto_var_init_no_expression)
9090         << Name << Type << Range;
9091     return QualType();
9092   }
9093 
9094   if (DeduceInits.size() > 1) {
9095     Diag(DeduceInits[1]->getLocStart(),
9096          IsInitCapture ? diag::err_init_capture_multiple_expressions
9097                        : diag::err_auto_var_init_multiple_expressions)
9098         << Name << Type << Range;
9099     return QualType();
9100   }
9101 
9102   Expr *DeduceInit = DeduceInits[0];
9103   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9104     Diag(Init->getLocStart(), IsInitCapture
9105                                   ? diag::err_init_capture_paren_braces
9106                                   : diag::err_auto_var_init_paren_braces)
9107         << isa<InitListExpr>(Init) << Name << Type << Range;
9108     return QualType();
9109   }
9110 
9111   // Expressions default to 'id' when we're in a debugger.
9112   bool DefaultedAnyToId = false;
9113   if (getLangOpts().DebuggerCastResultToId &&
9114       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9115     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9116     if (Result.isInvalid()) {
9117       return QualType();
9118     }
9119     Init = Result.get();
9120     DefaultedAnyToId = true;
9121   }
9122 
9123   QualType DeducedType;
9124   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9125     if (!IsInitCapture)
9126       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9127     else if (isa<InitListExpr>(Init))
9128       Diag(Range.getBegin(),
9129            diag::err_init_capture_deduction_failure_from_init_list)
9130           << Name
9131           << (DeduceInit->getType().isNull() ? TSI->getType()
9132                                              : DeduceInit->getType())
9133           << DeduceInit->getSourceRange();
9134     else
9135       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9136           << Name << TSI->getType()
9137           << (DeduceInit->getType().isNull() ? TSI->getType()
9138                                              : DeduceInit->getType())
9139           << DeduceInit->getSourceRange();
9140   }
9141 
9142   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9143   // 'id' instead of a specific object type prevents most of our usual
9144   // checks.
9145   // We only want to warn outside of template instantiations, though:
9146   // inside a template, the 'id' could have come from a parameter.
9147   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9148       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9149     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9150     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9151   }
9152 
9153   return DeducedType;
9154 }
9155 
9156 /// AddInitializerToDecl - Adds the initializer Init to the
9157 /// declaration dcl. If DirectInit is true, this is C++ direct
9158 /// initialization rather than copy initialization.
9159 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9160                                 bool DirectInit, bool TypeMayContainAuto) {
9161   // If there is no declaration, there was an error parsing it.  Just ignore
9162   // the initializer.
9163   if (!RealDecl || RealDecl->isInvalidDecl()) {
9164     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9165     return;
9166   }
9167 
9168   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9169     // Pure-specifiers are handled in ActOnPureSpecifier.
9170     Diag(Method->getLocation(), diag::err_member_function_initialization)
9171       << Method->getDeclName() << Init->getSourceRange();
9172     Method->setInvalidDecl();
9173     return;
9174   }
9175 
9176   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9177   if (!VDecl) {
9178     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9179     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9180     RealDecl->setInvalidDecl();
9181     return;
9182   }
9183 
9184   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9185   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9186     // Attempt typo correction early so that the type of the init expression can
9187     // be deduced based on the chosen correction if the original init contains a
9188     // TypoExpr.
9189     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9190     if (!Res.isUsable()) {
9191       RealDecl->setInvalidDecl();
9192       return;
9193     }
9194     Init = Res.get();
9195 
9196     QualType DeducedType = deduceVarTypeFromInitializer(
9197         VDecl, VDecl->getDeclName(), VDecl->getType(),
9198         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9199     if (DeducedType.isNull()) {
9200       RealDecl->setInvalidDecl();
9201       return;
9202     }
9203 
9204     VDecl->setType(DeducedType);
9205     assert(VDecl->isLinkageValid());
9206 
9207     // In ARC, infer lifetime.
9208     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9209       VDecl->setInvalidDecl();
9210 
9211     // If this is a redeclaration, check that the type we just deduced matches
9212     // the previously declared type.
9213     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9214       // We never need to merge the type, because we cannot form an incomplete
9215       // array of auto, nor deduce such a type.
9216       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9217     }
9218 
9219     // Check the deduced type is valid for a variable declaration.
9220     CheckVariableDeclarationType(VDecl);
9221     if (VDecl->isInvalidDecl())
9222       return;
9223   }
9224 
9225   // dllimport cannot be used on variable definitions.
9226   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9227     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9228     VDecl->setInvalidDecl();
9229     return;
9230   }
9231 
9232   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9233     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9234     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9235     VDecl->setInvalidDecl();
9236     return;
9237   }
9238 
9239   if (!VDecl->getType()->isDependentType()) {
9240     // A definition must end up with a complete type, which means it must be
9241     // complete with the restriction that an array type might be completed by
9242     // the initializer; note that later code assumes this restriction.
9243     QualType BaseDeclType = VDecl->getType();
9244     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9245       BaseDeclType = Array->getElementType();
9246     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9247                             diag::err_typecheck_decl_incomplete_type)) {
9248       RealDecl->setInvalidDecl();
9249       return;
9250     }
9251 
9252     // The variable can not have an abstract class type.
9253     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9254                                diag::err_abstract_type_in_decl,
9255                                AbstractVariableType))
9256       VDecl->setInvalidDecl();
9257   }
9258 
9259   VarDecl *Def;
9260   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9261     NamedDecl *Hidden = nullptr;
9262     if (!hasVisibleDefinition(Def, &Hidden) &&
9263         (VDecl->getFormalLinkage() == InternalLinkage ||
9264          VDecl->getDescribedVarTemplate() ||
9265          VDecl->getNumTemplateParameterLists() ||
9266          VDecl->getDeclContext()->isDependentContext())) {
9267       // The previous definition is hidden, and multiple definitions are
9268       // permitted (in separate TUs). Form another definition of it.
9269     } else {
9270       Diag(VDecl->getLocation(), diag::err_redefinition)
9271         << VDecl->getDeclName();
9272       Diag(Def->getLocation(), diag::note_previous_definition);
9273       VDecl->setInvalidDecl();
9274       return;
9275     }
9276   }
9277 
9278   if (getLangOpts().CPlusPlus) {
9279     // C++ [class.static.data]p4
9280     //   If a static data member is of const integral or const
9281     //   enumeration type, its declaration in the class definition can
9282     //   specify a constant-initializer which shall be an integral
9283     //   constant expression (5.19). In that case, the member can appear
9284     //   in integral constant expressions. The member shall still be
9285     //   defined in a namespace scope if it is used in the program and the
9286     //   namespace scope definition shall not contain an initializer.
9287     //
9288     // We already performed a redefinition check above, but for static
9289     // data members we also need to check whether there was an in-class
9290     // declaration with an initializer.
9291     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9292       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9293           << VDecl->getDeclName();
9294       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9295            diag::note_previous_initializer)
9296           << 0;
9297       return;
9298     }
9299 
9300     if (VDecl->hasLocalStorage())
9301       getCurFunction()->setHasBranchProtectedScope();
9302 
9303     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9304       VDecl->setInvalidDecl();
9305       return;
9306     }
9307   }
9308 
9309   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9310   // a kernel function cannot be initialized."
9311   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9312     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9313     VDecl->setInvalidDecl();
9314     return;
9315   }
9316 
9317   // Get the decls type and save a reference for later, since
9318   // CheckInitializerTypes may change it.
9319   QualType DclT = VDecl->getType(), SavT = DclT;
9320 
9321   // Expressions default to 'id' when we're in a debugger
9322   // and we are assigning it to a variable of Objective-C pointer type.
9323   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9324       Init->getType() == Context.UnknownAnyTy) {
9325     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9326     if (Result.isInvalid()) {
9327       VDecl->setInvalidDecl();
9328       return;
9329     }
9330     Init = Result.get();
9331   }
9332 
9333   // Perform the initialization.
9334   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9335   if (!VDecl->isInvalidDecl()) {
9336     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9337     InitializationKind Kind =
9338         DirectInit
9339             ? CXXDirectInit
9340                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9341                                                      Init->getLocStart(),
9342                                                      Init->getLocEnd())
9343                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9344             : InitializationKind::CreateCopy(VDecl->getLocation(),
9345                                              Init->getLocStart());
9346 
9347     MultiExprArg Args = Init;
9348     if (CXXDirectInit)
9349       Args = MultiExprArg(CXXDirectInit->getExprs(),
9350                           CXXDirectInit->getNumExprs());
9351 
9352     // Try to correct any TypoExprs in the initialization arguments.
9353     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9354       ExprResult Res = CorrectDelayedTyposInExpr(
9355           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9356             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9357             return Init.Failed() ? ExprError() : E;
9358           });
9359       if (Res.isInvalid()) {
9360         VDecl->setInvalidDecl();
9361       } else if (Res.get() != Args[Idx]) {
9362         Args[Idx] = Res.get();
9363       }
9364     }
9365     if (VDecl->isInvalidDecl())
9366       return;
9367 
9368     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9369     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9370     if (Result.isInvalid()) {
9371       VDecl->setInvalidDecl();
9372       return;
9373     }
9374 
9375     Init = Result.getAs<Expr>();
9376   }
9377 
9378   // Check for self-references within variable initializers.
9379   // Variables declared within a function/method body (except for references)
9380   // are handled by a dataflow analysis.
9381   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9382       VDecl->getType()->isReferenceType()) {
9383     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9384   }
9385 
9386   // If the type changed, it means we had an incomplete type that was
9387   // completed by the initializer. For example:
9388   //   int ary[] = { 1, 3, 5 };
9389   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9390   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9391     VDecl->setType(DclT);
9392 
9393   if (!VDecl->isInvalidDecl()) {
9394     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9395 
9396     if (VDecl->hasAttr<BlocksAttr>())
9397       checkRetainCycles(VDecl, Init);
9398 
9399     // It is safe to assign a weak reference into a strong variable.
9400     // Although this code can still have problems:
9401     //   id x = self.weakProp;
9402     //   id y = self.weakProp;
9403     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9404     // paths through the function. This should be revisited if
9405     // -Wrepeated-use-of-weak is made flow-sensitive.
9406     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9407         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9408                          Init->getLocStart()))
9409       getCurFunction()->markSafeWeakUse(Init);
9410   }
9411 
9412   // The initialization is usually a full-expression.
9413   //
9414   // FIXME: If this is a braced initialization of an aggregate, it is not
9415   // an expression, and each individual field initializer is a separate
9416   // full-expression. For instance, in:
9417   //
9418   //   struct Temp { ~Temp(); };
9419   //   struct S { S(Temp); };
9420   //   struct T { S a, b; } t = { Temp(), Temp() }
9421   //
9422   // we should destroy the first Temp before constructing the second.
9423   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9424                                           false,
9425                                           VDecl->isConstexpr());
9426   if (Result.isInvalid()) {
9427     VDecl->setInvalidDecl();
9428     return;
9429   }
9430   Init = Result.get();
9431 
9432   // Attach the initializer to the decl.
9433   VDecl->setInit(Init);
9434 
9435   if (VDecl->isLocalVarDecl()) {
9436     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9437     // static storage duration shall be constant expressions or string literals.
9438     // C++ does not have this restriction.
9439     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9440       const Expr *Culprit;
9441       if (VDecl->getStorageClass() == SC_Static)
9442         CheckForConstantInitializer(Init, DclT);
9443       // C89 is stricter than C99 for non-static aggregate types.
9444       // C89 6.5.7p3: All the expressions [...] in an initializer list
9445       // for an object that has aggregate or union type shall be
9446       // constant expressions.
9447       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9448                isa<InitListExpr>(Init) &&
9449                !Init->isConstantInitializer(Context, false, &Culprit))
9450         Diag(Culprit->getExprLoc(),
9451              diag::ext_aggregate_init_not_constant)
9452           << Culprit->getSourceRange();
9453     }
9454   } else if (VDecl->isStaticDataMember() &&
9455              VDecl->getLexicalDeclContext()->isRecord()) {
9456     // This is an in-class initialization for a static data member, e.g.,
9457     //
9458     // struct S {
9459     //   static const int value = 17;
9460     // };
9461 
9462     // C++ [class.mem]p4:
9463     //   A member-declarator can contain a constant-initializer only
9464     //   if it declares a static member (9.4) of const integral or
9465     //   const enumeration type, see 9.4.2.
9466     //
9467     // C++11 [class.static.data]p3:
9468     //   If a non-volatile const static data member is of integral or
9469     //   enumeration type, its declaration in the class definition can
9470     //   specify a brace-or-equal-initializer in which every initalizer-clause
9471     //   that is an assignment-expression is a constant expression. A static
9472     //   data member of literal type can be declared in the class definition
9473     //   with the constexpr specifier; if so, its declaration shall specify a
9474     //   brace-or-equal-initializer in which every initializer-clause that is
9475     //   an assignment-expression is a constant expression.
9476 
9477     // Do nothing on dependent types.
9478     if (DclT->isDependentType()) {
9479 
9480     // Allow any 'static constexpr' members, whether or not they are of literal
9481     // type. We separately check that every constexpr variable is of literal
9482     // type.
9483     } else if (VDecl->isConstexpr()) {
9484 
9485     // Require constness.
9486     } else if (!DclT.isConstQualified()) {
9487       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9488         << Init->getSourceRange();
9489       VDecl->setInvalidDecl();
9490 
9491     // We allow integer constant expressions in all cases.
9492     } else if (DclT->isIntegralOrEnumerationType()) {
9493       // Check whether the expression is a constant expression.
9494       SourceLocation Loc;
9495       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9496         // In C++11, a non-constexpr const static data member with an
9497         // in-class initializer cannot be volatile.
9498         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9499       else if (Init->isValueDependent())
9500         ; // Nothing to check.
9501       else if (Init->isIntegerConstantExpr(Context, &Loc))
9502         ; // Ok, it's an ICE!
9503       else if (Init->isEvaluatable(Context)) {
9504         // If we can constant fold the initializer through heroics, accept it,
9505         // but report this as a use of an extension for -pedantic.
9506         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9507           << Init->getSourceRange();
9508       } else {
9509         // Otherwise, this is some crazy unknown case.  Report the issue at the
9510         // location provided by the isIntegerConstantExpr failed check.
9511         Diag(Loc, diag::err_in_class_initializer_non_constant)
9512           << Init->getSourceRange();
9513         VDecl->setInvalidDecl();
9514       }
9515 
9516     // We allow foldable floating-point constants as an extension.
9517     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9518       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9519       // it anyway and provide a fixit to add the 'constexpr'.
9520       if (getLangOpts().CPlusPlus11) {
9521         Diag(VDecl->getLocation(),
9522              diag::ext_in_class_initializer_float_type_cxx11)
9523             << DclT << Init->getSourceRange();
9524         Diag(VDecl->getLocStart(),
9525              diag::note_in_class_initializer_float_type_cxx11)
9526             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9527       } else {
9528         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9529           << DclT << Init->getSourceRange();
9530 
9531         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9532           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9533             << Init->getSourceRange();
9534           VDecl->setInvalidDecl();
9535         }
9536       }
9537 
9538     // Suggest adding 'constexpr' in C++11 for literal types.
9539     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9540       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9541         << DclT << Init->getSourceRange()
9542         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9543       VDecl->setConstexpr(true);
9544 
9545     } else {
9546       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9547         << DclT << Init->getSourceRange();
9548       VDecl->setInvalidDecl();
9549     }
9550   } else if (VDecl->isFileVarDecl()) {
9551     if (VDecl->getStorageClass() == SC_Extern &&
9552         (!getLangOpts().CPlusPlus ||
9553          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9554            VDecl->isExternC())) &&
9555         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9556       Diag(VDecl->getLocation(), diag::warn_extern_init);
9557 
9558     // C99 6.7.8p4. All file scoped initializers need to be constant.
9559     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9560       CheckForConstantInitializer(Init, DclT);
9561   }
9562 
9563   // We will represent direct-initialization similarly to copy-initialization:
9564   //    int x(1);  -as-> int x = 1;
9565   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9566   //
9567   // Clients that want to distinguish between the two forms, can check for
9568   // direct initializer using VarDecl::getInitStyle().
9569   // A major benefit is that clients that don't particularly care about which
9570   // exactly form was it (like the CodeGen) can handle both cases without
9571   // special case code.
9572 
9573   // C++ 8.5p11:
9574   // The form of initialization (using parentheses or '=') is generally
9575   // insignificant, but does matter when the entity being initialized has a
9576   // class type.
9577   if (CXXDirectInit) {
9578     assert(DirectInit && "Call-style initializer must be direct init.");
9579     VDecl->setInitStyle(VarDecl::CallInit);
9580   } else if (DirectInit) {
9581     // This must be list-initialization. No other way is direct-initialization.
9582     VDecl->setInitStyle(VarDecl::ListInit);
9583   }
9584 
9585   CheckCompleteVariableDeclaration(VDecl);
9586 }
9587 
9588 /// ActOnInitializerError - Given that there was an error parsing an
9589 /// initializer for the given declaration, try to return to some form
9590 /// of sanity.
9591 void Sema::ActOnInitializerError(Decl *D) {
9592   // Our main concern here is re-establishing invariants like "a
9593   // variable's type is either dependent or complete".
9594   if (!D || D->isInvalidDecl()) return;
9595 
9596   VarDecl *VD = dyn_cast<VarDecl>(D);
9597   if (!VD) return;
9598 
9599   // Auto types are meaningless if we can't make sense of the initializer.
9600   if (ParsingInitForAutoVars.count(D)) {
9601     D->setInvalidDecl();
9602     return;
9603   }
9604 
9605   QualType Ty = VD->getType();
9606   if (Ty->isDependentType()) return;
9607 
9608   // Require a complete type.
9609   if (RequireCompleteType(VD->getLocation(),
9610                           Context.getBaseElementType(Ty),
9611                           diag::err_typecheck_decl_incomplete_type)) {
9612     VD->setInvalidDecl();
9613     return;
9614   }
9615 
9616   // Require a non-abstract type.
9617   if (RequireNonAbstractType(VD->getLocation(), Ty,
9618                              diag::err_abstract_type_in_decl,
9619                              AbstractVariableType)) {
9620     VD->setInvalidDecl();
9621     return;
9622   }
9623 
9624   // Don't bother complaining about constructors or destructors,
9625   // though.
9626 }
9627 
9628 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9629                                   bool TypeMayContainAuto) {
9630   // If there is no declaration, there was an error parsing it. Just ignore it.
9631   if (!RealDecl)
9632     return;
9633 
9634   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9635     QualType Type = Var->getType();
9636 
9637     // C++11 [dcl.spec.auto]p3
9638     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9639       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9640         << Var->getDeclName() << Type;
9641       Var->setInvalidDecl();
9642       return;
9643     }
9644 
9645     // C++11 [class.static.data]p3: A static data member can be declared with
9646     // the constexpr specifier; if so, its declaration shall specify
9647     // a brace-or-equal-initializer.
9648     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9649     // the definition of a variable [...] or the declaration of a static data
9650     // member.
9651     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9652       if (Var->isStaticDataMember())
9653         Diag(Var->getLocation(),
9654              diag::err_constexpr_static_mem_var_requires_init)
9655           << Var->getDeclName();
9656       else
9657         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9658       Var->setInvalidDecl();
9659       return;
9660     }
9661 
9662     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9663     // definition having the concept specifier is called a variable concept. A
9664     // concept definition refers to [...] a variable concept and its initializer.
9665     if (Var->isConcept()) {
9666       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9667       Var->setInvalidDecl();
9668       return;
9669     }
9670 
9671     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9672     // be initialized.
9673     if (!Var->isInvalidDecl() &&
9674         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9675         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9676       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9677       Var->setInvalidDecl();
9678       return;
9679     }
9680 
9681     switch (Var->isThisDeclarationADefinition()) {
9682     case VarDecl::Definition:
9683       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9684         break;
9685 
9686       // We have an out-of-line definition of a static data member
9687       // that has an in-class initializer, so we type-check this like
9688       // a declaration.
9689       //
9690       // Fall through
9691 
9692     case VarDecl::DeclarationOnly:
9693       // It's only a declaration.
9694 
9695       // Block scope. C99 6.7p7: If an identifier for an object is
9696       // declared with no linkage (C99 6.2.2p6), the type for the
9697       // object shall be complete.
9698       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9699           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9700           RequireCompleteType(Var->getLocation(), Type,
9701                               diag::err_typecheck_decl_incomplete_type))
9702         Var->setInvalidDecl();
9703 
9704       // Make sure that the type is not abstract.
9705       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9706           RequireNonAbstractType(Var->getLocation(), Type,
9707                                  diag::err_abstract_type_in_decl,
9708                                  AbstractVariableType))
9709         Var->setInvalidDecl();
9710       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9711           Var->getStorageClass() == SC_PrivateExtern) {
9712         Diag(Var->getLocation(), diag::warn_private_extern);
9713         Diag(Var->getLocation(), diag::note_private_extern);
9714       }
9715 
9716       return;
9717 
9718     case VarDecl::TentativeDefinition:
9719       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9720       // object that has file scope without an initializer, and without a
9721       // storage-class specifier or with the storage-class specifier "static",
9722       // constitutes a tentative definition. Note: A tentative definition with
9723       // external linkage is valid (C99 6.2.2p5).
9724       if (!Var->isInvalidDecl()) {
9725         if (const IncompleteArrayType *ArrayT
9726                                     = Context.getAsIncompleteArrayType(Type)) {
9727           if (RequireCompleteType(Var->getLocation(),
9728                                   ArrayT->getElementType(),
9729                                   diag::err_illegal_decl_array_incomplete_type))
9730             Var->setInvalidDecl();
9731         } else if (Var->getStorageClass() == SC_Static) {
9732           // C99 6.9.2p3: If the declaration of an identifier for an object is
9733           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9734           // declared type shall not be an incomplete type.
9735           // NOTE: code such as the following
9736           //     static struct s;
9737           //     struct s { int a; };
9738           // is accepted by gcc. Hence here we issue a warning instead of
9739           // an error and we do not invalidate the static declaration.
9740           // NOTE: to avoid multiple warnings, only check the first declaration.
9741           if (Var->isFirstDecl())
9742             RequireCompleteType(Var->getLocation(), Type,
9743                                 diag::ext_typecheck_decl_incomplete_type);
9744         }
9745       }
9746 
9747       // Record the tentative definition; we're done.
9748       if (!Var->isInvalidDecl())
9749         TentativeDefinitions.push_back(Var);
9750       return;
9751     }
9752 
9753     // Provide a specific diagnostic for uninitialized variable
9754     // definitions with incomplete array type.
9755     if (Type->isIncompleteArrayType()) {
9756       Diag(Var->getLocation(),
9757            diag::err_typecheck_incomplete_array_needs_initializer);
9758       Var->setInvalidDecl();
9759       return;
9760     }
9761 
9762     // Provide a specific diagnostic for uninitialized variable
9763     // definitions with reference type.
9764     if (Type->isReferenceType()) {
9765       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9766         << Var->getDeclName()
9767         << SourceRange(Var->getLocation(), Var->getLocation());
9768       Var->setInvalidDecl();
9769       return;
9770     }
9771 
9772     // Do not attempt to type-check the default initializer for a
9773     // variable with dependent type.
9774     if (Type->isDependentType())
9775       return;
9776 
9777     if (Var->isInvalidDecl())
9778       return;
9779 
9780     if (!Var->hasAttr<AliasAttr>()) {
9781       if (RequireCompleteType(Var->getLocation(),
9782                               Context.getBaseElementType(Type),
9783                               diag::err_typecheck_decl_incomplete_type)) {
9784         Var->setInvalidDecl();
9785         return;
9786       }
9787     } else {
9788       return;
9789     }
9790 
9791     // The variable can not have an abstract class type.
9792     if (RequireNonAbstractType(Var->getLocation(), Type,
9793                                diag::err_abstract_type_in_decl,
9794                                AbstractVariableType)) {
9795       Var->setInvalidDecl();
9796       return;
9797     }
9798 
9799     // Check for jumps past the implicit initializer.  C++0x
9800     // clarifies that this applies to a "variable with automatic
9801     // storage duration", not a "local variable".
9802     // C++11 [stmt.dcl]p3
9803     //   A program that jumps from a point where a variable with automatic
9804     //   storage duration is not in scope to a point where it is in scope is
9805     //   ill-formed unless the variable has scalar type, class type with a
9806     //   trivial default constructor and a trivial destructor, a cv-qualified
9807     //   version of one of these types, or an array of one of the preceding
9808     //   types and is declared without an initializer.
9809     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9810       if (const RecordType *Record
9811             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9812         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9813         // Mark the function for further checking even if the looser rules of
9814         // C++11 do not require such checks, so that we can diagnose
9815         // incompatibilities with C++98.
9816         if (!CXXRecord->isPOD())
9817           getCurFunction()->setHasBranchProtectedScope();
9818       }
9819     }
9820 
9821     // C++03 [dcl.init]p9:
9822     //   If no initializer is specified for an object, and the
9823     //   object is of (possibly cv-qualified) non-POD class type (or
9824     //   array thereof), the object shall be default-initialized; if
9825     //   the object is of const-qualified type, the underlying class
9826     //   type shall have a user-declared default
9827     //   constructor. Otherwise, if no initializer is specified for
9828     //   a non- static object, the object and its subobjects, if
9829     //   any, have an indeterminate initial value); if the object
9830     //   or any of its subobjects are of const-qualified type, the
9831     //   program is ill-formed.
9832     // C++0x [dcl.init]p11:
9833     //   If no initializer is specified for an object, the object is
9834     //   default-initialized; [...].
9835     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9836     InitializationKind Kind
9837       = InitializationKind::CreateDefault(Var->getLocation());
9838 
9839     InitializationSequence InitSeq(*this, Entity, Kind, None);
9840     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9841     if (Init.isInvalid())
9842       Var->setInvalidDecl();
9843     else if (Init.get()) {
9844       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9845       // This is important for template substitution.
9846       Var->setInitStyle(VarDecl::CallInit);
9847     }
9848 
9849     CheckCompleteVariableDeclaration(Var);
9850   }
9851 }
9852 
9853 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9854   VarDecl *VD = dyn_cast<VarDecl>(D);
9855   if (!VD) {
9856     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9857     D->setInvalidDecl();
9858     return;
9859   }
9860 
9861   VD->setCXXForRangeDecl(true);
9862 
9863   // for-range-declaration cannot be given a storage class specifier.
9864   int Error = -1;
9865   switch (VD->getStorageClass()) {
9866   case SC_None:
9867     break;
9868   case SC_Extern:
9869     Error = 0;
9870     break;
9871   case SC_Static:
9872     Error = 1;
9873     break;
9874   case SC_PrivateExtern:
9875     Error = 2;
9876     break;
9877   case SC_Auto:
9878     Error = 3;
9879     break;
9880   case SC_Register:
9881     Error = 4;
9882     break;
9883   }
9884   if (Error != -1) {
9885     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9886       << VD->getDeclName() << Error;
9887     D->setInvalidDecl();
9888   }
9889 }
9890 
9891 StmtResult
9892 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9893                                  IdentifierInfo *Ident,
9894                                  ParsedAttributes &Attrs,
9895                                  SourceLocation AttrEnd) {
9896   // C++1y [stmt.iter]p1:
9897   //   A range-based for statement of the form
9898   //      for ( for-range-identifier : for-range-initializer ) statement
9899   //   is equivalent to
9900   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9901   DeclSpec DS(Attrs.getPool().getFactory());
9902 
9903   const char *PrevSpec;
9904   unsigned DiagID;
9905   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9906                      getPrintingPolicy());
9907 
9908   Declarator D(DS, Declarator::ForContext);
9909   D.SetIdentifier(Ident, IdentLoc);
9910   D.takeAttributes(Attrs, AttrEnd);
9911 
9912   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9913   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9914                 EmptyAttrs, IdentLoc);
9915   Decl *Var = ActOnDeclarator(S, D);
9916   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9917   FinalizeDeclaration(Var);
9918   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9919                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9920 }
9921 
9922 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9923   if (var->isInvalidDecl()) return;
9924 
9925   // In Objective-C, don't allow jumps past the implicit initialization of a
9926   // local retaining variable.
9927   if (getLangOpts().ObjC1 &&
9928       var->hasLocalStorage()) {
9929     switch (var->getType().getObjCLifetime()) {
9930     case Qualifiers::OCL_None:
9931     case Qualifiers::OCL_ExplicitNone:
9932     case Qualifiers::OCL_Autoreleasing:
9933       break;
9934 
9935     case Qualifiers::OCL_Weak:
9936     case Qualifiers::OCL_Strong:
9937       getCurFunction()->setHasBranchProtectedScope();
9938       break;
9939     }
9940   }
9941 
9942   // Warn about externally-visible variables being defined without a
9943   // prior declaration.  We only want to do this for global
9944   // declarations, but we also specifically need to avoid doing it for
9945   // class members because the linkage of an anonymous class can
9946   // change if it's later given a typedef name.
9947   if (var->isThisDeclarationADefinition() &&
9948       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9949       var->isExternallyVisible() && var->hasLinkage() &&
9950       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9951                                   var->getLocation())) {
9952     // Find a previous declaration that's not a definition.
9953     VarDecl *prev = var->getPreviousDecl();
9954     while (prev && prev->isThisDeclarationADefinition())
9955       prev = prev->getPreviousDecl();
9956 
9957     if (!prev)
9958       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9959   }
9960 
9961   if (var->getTLSKind() == VarDecl::TLS_Static) {
9962     const Expr *Culprit;
9963     if (var->getType().isDestructedType()) {
9964       // GNU C++98 edits for __thread, [basic.start.term]p3:
9965       //   The type of an object with thread storage duration shall not
9966       //   have a non-trivial destructor.
9967       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9968       if (getLangOpts().CPlusPlus11)
9969         Diag(var->getLocation(), diag::note_use_thread_local);
9970     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9971                !var->getInit()->isConstantInitializer(
9972                    Context, var->getType()->isReferenceType(), &Culprit)) {
9973       // GNU C++98 edits for __thread, [basic.start.init]p4:
9974       //   An object of thread storage duration shall not require dynamic
9975       //   initialization.
9976       // FIXME: Need strict checking here.
9977       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9978         << Culprit->getSourceRange();
9979       if (getLangOpts().CPlusPlus11)
9980         Diag(var->getLocation(), diag::note_use_thread_local);
9981     }
9982 
9983   }
9984 
9985   // Apply section attributes and pragmas to global variables.
9986   bool GlobalStorage = var->hasGlobalStorage();
9987   if (GlobalStorage && var->isThisDeclarationADefinition() &&
9988       ActiveTemplateInstantiations.empty()) {
9989     PragmaStack<StringLiteral *> *Stack = nullptr;
9990     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9991     if (var->getType().isConstQualified())
9992       Stack = &ConstSegStack;
9993     else if (!var->getInit()) {
9994       Stack = &BSSSegStack;
9995       SectionFlags |= ASTContext::PSF_Write;
9996     } else {
9997       Stack = &DataSegStack;
9998       SectionFlags |= ASTContext::PSF_Write;
9999     }
10000     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10001       var->addAttr(SectionAttr::CreateImplicit(
10002           Context, SectionAttr::Declspec_allocate,
10003           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10004     }
10005     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10006       if (UnifySection(SA->getName(), SectionFlags, var))
10007         var->dropAttr<SectionAttr>();
10008 
10009     // Apply the init_seg attribute if this has an initializer.  If the
10010     // initializer turns out to not be dynamic, we'll end up ignoring this
10011     // attribute.
10012     if (CurInitSeg && var->getInit())
10013       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10014                                                CurInitSegLoc));
10015   }
10016 
10017   // All the following checks are C++ only.
10018   if (!getLangOpts().CPlusPlus) return;
10019 
10020   QualType type = var->getType();
10021   if (type->isDependentType()) return;
10022 
10023   // __block variables might require us to capture a copy-initializer.
10024   if (var->hasAttr<BlocksAttr>()) {
10025     // It's currently invalid to ever have a __block variable with an
10026     // array type; should we diagnose that here?
10027 
10028     // Regardless, we don't want to ignore array nesting when
10029     // constructing this copy.
10030     if (type->isStructureOrClassType()) {
10031       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10032       SourceLocation poi = var->getLocation();
10033       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10034       ExprResult result
10035         = PerformMoveOrCopyInitialization(
10036             InitializedEntity::InitializeBlock(poi, type, false),
10037             var, var->getType(), varRef, /*AllowNRVO=*/true);
10038       if (!result.isInvalid()) {
10039         result = MaybeCreateExprWithCleanups(result);
10040         Expr *init = result.getAs<Expr>();
10041         Context.setBlockVarCopyInits(var, init);
10042       }
10043     }
10044   }
10045 
10046   Expr *Init = var->getInit();
10047   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10048   QualType baseType = Context.getBaseElementType(type);
10049 
10050   if (!var->getDeclContext()->isDependentContext() &&
10051       Init && !Init->isValueDependent()) {
10052     if (IsGlobal && !var->isConstexpr() &&
10053         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10054                                     var->getLocation())) {
10055       // Warn about globals which don't have a constant initializer.  Don't
10056       // warn about globals with a non-trivial destructor because we already
10057       // warned about them.
10058       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10059       if (!(RD && !RD->hasTrivialDestructor()) &&
10060           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10061         Diag(var->getLocation(), diag::warn_global_constructor)
10062           << Init->getSourceRange();
10063     }
10064 
10065     if (var->isConstexpr()) {
10066       SmallVector<PartialDiagnosticAt, 8> Notes;
10067       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10068         SourceLocation DiagLoc = var->getLocation();
10069         // If the note doesn't add any useful information other than a source
10070         // location, fold it into the primary diagnostic.
10071         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10072               diag::note_invalid_subexpr_in_const_expr) {
10073           DiagLoc = Notes[0].first;
10074           Notes.clear();
10075         }
10076         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10077           << var << Init->getSourceRange();
10078         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10079           Diag(Notes[I].first, Notes[I].second);
10080       }
10081     } else if (var->isUsableInConstantExpressions(Context)) {
10082       // Check whether the initializer of a const variable of integral or
10083       // enumeration type is an ICE now, since we can't tell whether it was
10084       // initialized by a constant expression if we check later.
10085       var->checkInitIsICE();
10086     }
10087   }
10088 
10089   // Require the destructor.
10090   if (const RecordType *recordType = baseType->getAs<RecordType>())
10091     FinalizeVarWithDestructor(var, recordType);
10092 }
10093 
10094 /// \brief Determines if a variable's alignment is dependent.
10095 static bool hasDependentAlignment(VarDecl *VD) {
10096   if (VD->getType()->isDependentType())
10097     return true;
10098   for (auto *I : VD->specific_attrs<AlignedAttr>())
10099     if (I->isAlignmentDependent())
10100       return true;
10101   return false;
10102 }
10103 
10104 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10105 /// any semantic actions necessary after any initializer has been attached.
10106 void
10107 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10108   // Note that we are no longer parsing the initializer for this declaration.
10109   ParsingInitForAutoVars.erase(ThisDecl);
10110 
10111   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10112   if (!VD)
10113     return;
10114 
10115   checkAttributesAfterMerging(*this, *VD);
10116 
10117   // Perform TLS alignment check here after attributes attached to the variable
10118   // which may affect the alignment have been processed. Only perform the check
10119   // if the target has a maximum TLS alignment (zero means no constraints).
10120   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10121     // Protect the check so that it's not performed on dependent types and
10122     // dependent alignments (we can't determine the alignment in that case).
10123     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10124       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10125       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10126         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10127           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10128           << (unsigned)MaxAlignChars.getQuantity();
10129       }
10130     }
10131   }
10132 
10133   // Static locals inherit dll attributes from their function.
10134   if (VD->isStaticLocal()) {
10135     if (FunctionDecl *FD =
10136             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10137       if (Attr *A = getDLLAttr(FD)) {
10138         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10139         NewAttr->setInherited(true);
10140         VD->addAttr(NewAttr);
10141       }
10142     }
10143   }
10144 
10145   // Grab the dllimport or dllexport attribute off of the VarDecl.
10146   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10147 
10148   // Imported static data members cannot be defined out-of-line.
10149   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10150     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10151         VD->isThisDeclarationADefinition()) {
10152       // We allow definitions of dllimport class template static data members
10153       // with a warning.
10154       CXXRecordDecl *Context =
10155         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10156       bool IsClassTemplateMember =
10157           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10158           Context->getDescribedClassTemplate();
10159 
10160       Diag(VD->getLocation(),
10161            IsClassTemplateMember
10162                ? diag::warn_attribute_dllimport_static_field_definition
10163                : diag::err_attribute_dllimport_static_field_definition);
10164       Diag(IA->getLocation(), diag::note_attribute);
10165       if (!IsClassTemplateMember)
10166         VD->setInvalidDecl();
10167     }
10168   }
10169 
10170   // dllimport/dllexport variables cannot be thread local, their TLS index
10171   // isn't exported with the variable.
10172   if (DLLAttr && VD->getTLSKind()) {
10173     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10174     if (F && getDLLAttr(F)) {
10175       assert(VD->isStaticLocal());
10176       // But if this is a static local in a dlimport/dllexport function, the
10177       // function will never be inlined, which means the var would never be
10178       // imported, so having it marked import/export is safe.
10179     } else {
10180       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10181                                                                     << DLLAttr;
10182       VD->setInvalidDecl();
10183     }
10184   }
10185 
10186   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10187     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10188       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10189       VD->dropAttr<UsedAttr>();
10190     }
10191   }
10192 
10193   const DeclContext *DC = VD->getDeclContext();
10194   // If there's a #pragma GCC visibility in scope, and this isn't a class
10195   // member, set the visibility of this variable.
10196   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10197     AddPushedVisibilityAttribute(VD);
10198 
10199   // FIXME: Warn on unused templates.
10200   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10201       !isa<VarTemplatePartialSpecializationDecl>(VD))
10202     MarkUnusedFileScopedDecl(VD);
10203 
10204   // Now we have parsed the initializer and can update the table of magic
10205   // tag values.
10206   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10207       !VD->getType()->isIntegralOrEnumerationType())
10208     return;
10209 
10210   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10211     const Expr *MagicValueExpr = VD->getInit();
10212     if (!MagicValueExpr) {
10213       continue;
10214     }
10215     llvm::APSInt MagicValueInt;
10216     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10217       Diag(I->getRange().getBegin(),
10218            diag::err_type_tag_for_datatype_not_ice)
10219         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10220       continue;
10221     }
10222     if (MagicValueInt.getActiveBits() > 64) {
10223       Diag(I->getRange().getBegin(),
10224            diag::err_type_tag_for_datatype_too_large)
10225         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10226       continue;
10227     }
10228     uint64_t MagicValue = MagicValueInt.getZExtValue();
10229     RegisterTypeTagForDatatype(I->getArgumentKind(),
10230                                MagicValue,
10231                                I->getMatchingCType(),
10232                                I->getLayoutCompatible(),
10233                                I->getMustBeNull());
10234   }
10235 }
10236 
10237 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10238                                                    ArrayRef<Decl *> Group) {
10239   SmallVector<Decl*, 8> Decls;
10240 
10241   if (DS.isTypeSpecOwned())
10242     Decls.push_back(DS.getRepAsDecl());
10243 
10244   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10245   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10246     if (Decl *D = Group[i]) {
10247       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10248         if (!FirstDeclaratorInGroup)
10249           FirstDeclaratorInGroup = DD;
10250       Decls.push_back(D);
10251     }
10252 
10253   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10254     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10255       handleTagNumbering(Tag, S);
10256       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10257           getLangOpts().CPlusPlus)
10258         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10259     }
10260   }
10261 
10262   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10263 }
10264 
10265 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10266 /// group, performing any necessary semantic checking.
10267 Sema::DeclGroupPtrTy
10268 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10269                            bool TypeMayContainAuto) {
10270   // C++0x [dcl.spec.auto]p7:
10271   //   If the type deduced for the template parameter U is not the same in each
10272   //   deduction, the program is ill-formed.
10273   // FIXME: When initializer-list support is added, a distinction is needed
10274   // between the deduced type U and the deduced type which 'auto' stands for.
10275   //   auto a = 0, b = { 1, 2, 3 };
10276   // is legal because the deduced type U is 'int' in both cases.
10277   if (TypeMayContainAuto && Group.size() > 1) {
10278     QualType Deduced;
10279     CanQualType DeducedCanon;
10280     VarDecl *DeducedDecl = nullptr;
10281     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10282       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10283         AutoType *AT = D->getType()->getContainedAutoType();
10284         // Don't reissue diagnostics when instantiating a template.
10285         if (AT && D->isInvalidDecl())
10286           break;
10287         QualType U = AT ? AT->getDeducedType() : QualType();
10288         if (!U.isNull()) {
10289           CanQualType UCanon = Context.getCanonicalType(U);
10290           if (Deduced.isNull()) {
10291             Deduced = U;
10292             DeducedCanon = UCanon;
10293             DeducedDecl = D;
10294           } else if (DeducedCanon != UCanon) {
10295             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10296                  diag::err_auto_different_deductions)
10297               << (unsigned)AT->getKeyword()
10298               << Deduced << DeducedDecl->getDeclName()
10299               << U << D->getDeclName()
10300               << DeducedDecl->getInit()->getSourceRange()
10301               << D->getInit()->getSourceRange();
10302             D->setInvalidDecl();
10303             break;
10304           }
10305         }
10306       }
10307     }
10308   }
10309 
10310   ActOnDocumentableDecls(Group);
10311 
10312   return DeclGroupPtrTy::make(
10313       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10314 }
10315 
10316 void Sema::ActOnDocumentableDecl(Decl *D) {
10317   ActOnDocumentableDecls(D);
10318 }
10319 
10320 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10321   // Don't parse the comment if Doxygen diagnostics are ignored.
10322   if (Group.empty() || !Group[0])
10323     return;
10324 
10325   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10326                       Group[0]->getLocation()) &&
10327       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10328                       Group[0]->getLocation()))
10329     return;
10330 
10331   if (Group.size() >= 2) {
10332     // This is a decl group.  Normally it will contain only declarations
10333     // produced from declarator list.  But in case we have any definitions or
10334     // additional declaration references:
10335     //   'typedef struct S {} S;'
10336     //   'typedef struct S *S;'
10337     //   'struct S *pS;'
10338     // FinalizeDeclaratorGroup adds these as separate declarations.
10339     Decl *MaybeTagDecl = Group[0];
10340     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10341       Group = Group.slice(1);
10342     }
10343   }
10344 
10345   // See if there are any new comments that are not attached to a decl.
10346   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10347   if (!Comments.empty() &&
10348       !Comments.back()->isAttached()) {
10349     // There is at least one comment that not attached to a decl.
10350     // Maybe it should be attached to one of these decls?
10351     //
10352     // Note that this way we pick up not only comments that precede the
10353     // declaration, but also comments that *follow* the declaration -- thanks to
10354     // the lookahead in the lexer: we've consumed the semicolon and looked
10355     // ahead through comments.
10356     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10357       Context.getCommentForDecl(Group[i], &PP);
10358   }
10359 }
10360 
10361 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10362 /// to introduce parameters into function prototype scope.
10363 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10364   const DeclSpec &DS = D.getDeclSpec();
10365 
10366   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10367 
10368   // C++03 [dcl.stc]p2 also permits 'auto'.
10369   StorageClass SC = SC_None;
10370   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10371     SC = SC_Register;
10372   } else if (getLangOpts().CPlusPlus &&
10373              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10374     SC = SC_Auto;
10375   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10376     Diag(DS.getStorageClassSpecLoc(),
10377          diag::err_invalid_storage_class_in_func_decl);
10378     D.getMutableDeclSpec().ClearStorageClassSpecs();
10379   }
10380 
10381   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10382     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10383       << DeclSpec::getSpecifierName(TSCS);
10384   if (DS.isConstexprSpecified())
10385     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10386       << 0;
10387   if (DS.isConceptSpecified())
10388     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10389 
10390   DiagnoseFunctionSpecifiers(DS);
10391 
10392   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10393   QualType parmDeclType = TInfo->getType();
10394 
10395   if (getLangOpts().CPlusPlus) {
10396     // Check that there are no default arguments inside the type of this
10397     // parameter.
10398     CheckExtraCXXDefaultArguments(D);
10399 
10400     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10401     if (D.getCXXScopeSpec().isSet()) {
10402       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10403         << D.getCXXScopeSpec().getRange();
10404       D.getCXXScopeSpec().clear();
10405     }
10406   }
10407 
10408   // Ensure we have a valid name
10409   IdentifierInfo *II = nullptr;
10410   if (D.hasName()) {
10411     II = D.getIdentifier();
10412     if (!II) {
10413       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10414         << GetNameForDeclarator(D).getName();
10415       D.setInvalidType(true);
10416     }
10417   }
10418 
10419   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10420   if (II) {
10421     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10422                    ForRedeclaration);
10423     LookupName(R, S);
10424     if (R.isSingleResult()) {
10425       NamedDecl *PrevDecl = R.getFoundDecl();
10426       if (PrevDecl->isTemplateParameter()) {
10427         // Maybe we will complain about the shadowed template parameter.
10428         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10429         // Just pretend that we didn't see the previous declaration.
10430         PrevDecl = nullptr;
10431       } else if (S->isDeclScope(PrevDecl)) {
10432         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10433         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10434 
10435         // Recover by removing the name
10436         II = nullptr;
10437         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10438         D.setInvalidType(true);
10439       }
10440     }
10441   }
10442 
10443   // Temporarily put parameter variables in the translation unit, not
10444   // the enclosing context.  This prevents them from accidentally
10445   // looking like class members in C++.
10446   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10447                                     D.getLocStart(),
10448                                     D.getIdentifierLoc(), II,
10449                                     parmDeclType, TInfo,
10450                                     SC);
10451 
10452   if (D.isInvalidType())
10453     New->setInvalidDecl();
10454 
10455   assert(S->isFunctionPrototypeScope());
10456   assert(S->getFunctionPrototypeDepth() >= 1);
10457   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10458                     S->getNextFunctionPrototypeIndex());
10459 
10460   // Add the parameter declaration into this scope.
10461   S->AddDecl(New);
10462   if (II)
10463     IdResolver.AddDecl(New);
10464 
10465   ProcessDeclAttributes(S, New, D);
10466 
10467   if (D.getDeclSpec().isModulePrivateSpecified())
10468     Diag(New->getLocation(), diag::err_module_private_local)
10469       << 1 << New->getDeclName()
10470       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10471       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10472 
10473   if (New->hasAttr<BlocksAttr>()) {
10474     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10475   }
10476   return New;
10477 }
10478 
10479 /// \brief Synthesizes a variable for a parameter arising from a
10480 /// typedef.
10481 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10482                                               SourceLocation Loc,
10483                                               QualType T) {
10484   /* FIXME: setting StartLoc == Loc.
10485      Would it be worth to modify callers so as to provide proper source
10486      location for the unnamed parameters, embedding the parameter's type? */
10487   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10488                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10489                                            SC_None, nullptr);
10490   Param->setImplicit();
10491   return Param;
10492 }
10493 
10494 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10495                                     ParmVarDecl * const *ParamEnd) {
10496   // Don't diagnose unused-parameter errors in template instantiations; we
10497   // will already have done so in the template itself.
10498   if (!ActiveTemplateInstantiations.empty())
10499     return;
10500 
10501   for (; Param != ParamEnd; ++Param) {
10502     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10503         !(*Param)->hasAttr<UnusedAttr>()) {
10504       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10505         << (*Param)->getDeclName();
10506     }
10507   }
10508 }
10509 
10510 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10511                                                   ParmVarDecl * const *ParamEnd,
10512                                                   QualType ReturnTy,
10513                                                   NamedDecl *D) {
10514   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10515     return;
10516 
10517   // Warn if the return value is pass-by-value and larger than the specified
10518   // threshold.
10519   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10520     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10521     if (Size > LangOpts.NumLargeByValueCopy)
10522       Diag(D->getLocation(), diag::warn_return_value_size)
10523           << D->getDeclName() << Size;
10524   }
10525 
10526   // Warn if any parameter is pass-by-value and larger than the specified
10527   // threshold.
10528   for (; Param != ParamEnd; ++Param) {
10529     QualType T = (*Param)->getType();
10530     if (T->isDependentType() || !T.isPODType(Context))
10531       continue;
10532     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10533     if (Size > LangOpts.NumLargeByValueCopy)
10534       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10535           << (*Param)->getDeclName() << Size;
10536   }
10537 }
10538 
10539 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10540                                   SourceLocation NameLoc, IdentifierInfo *Name,
10541                                   QualType T, TypeSourceInfo *TSInfo,
10542                                   StorageClass SC) {
10543   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10544   if (getLangOpts().ObjCAutoRefCount &&
10545       T.getObjCLifetime() == Qualifiers::OCL_None &&
10546       T->isObjCLifetimeType()) {
10547 
10548     Qualifiers::ObjCLifetime lifetime;
10549 
10550     // Special cases for arrays:
10551     //   - if it's const, use __unsafe_unretained
10552     //   - otherwise, it's an error
10553     if (T->isArrayType()) {
10554       if (!T.isConstQualified()) {
10555         DelayedDiagnostics.add(
10556             sema::DelayedDiagnostic::makeForbiddenType(
10557             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10558       }
10559       lifetime = Qualifiers::OCL_ExplicitNone;
10560     } else {
10561       lifetime = T->getObjCARCImplicitLifetime();
10562     }
10563     T = Context.getLifetimeQualifiedType(T, lifetime);
10564   }
10565 
10566   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10567                                          Context.getAdjustedParameterType(T),
10568                                          TSInfo, SC, nullptr);
10569 
10570   // Parameters can not be abstract class types.
10571   // For record types, this is done by the AbstractClassUsageDiagnoser once
10572   // the class has been completely parsed.
10573   if (!CurContext->isRecord() &&
10574       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10575                              AbstractParamType))
10576     New->setInvalidDecl();
10577 
10578   // Parameter declarators cannot be interface types. All ObjC objects are
10579   // passed by reference.
10580   if (T->isObjCObjectType()) {
10581     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10582     Diag(NameLoc,
10583          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10584       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10585     T = Context.getObjCObjectPointerType(T);
10586     New->setType(T);
10587   }
10588 
10589   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10590   // duration shall not be qualified by an address-space qualifier."
10591   // Since all parameters have automatic store duration, they can not have
10592   // an address space.
10593   if (T.getAddressSpace() != 0) {
10594     // OpenCL allows function arguments declared to be an array of a type
10595     // to be qualified with an address space.
10596     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10597       Diag(NameLoc, diag::err_arg_with_address_space);
10598       New->setInvalidDecl();
10599     }
10600   }
10601 
10602   return New;
10603 }
10604 
10605 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10606                                            SourceLocation LocAfterDecls) {
10607   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10608 
10609   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10610   // for a K&R function.
10611   if (!FTI.hasPrototype) {
10612     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10613       --i;
10614       if (FTI.Params[i].Param == nullptr) {
10615         SmallString<256> Code;
10616         llvm::raw_svector_ostream(Code)
10617             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10618         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10619             << FTI.Params[i].Ident
10620             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10621 
10622         // Implicitly declare the argument as type 'int' for lack of a better
10623         // type.
10624         AttributeFactory attrs;
10625         DeclSpec DS(attrs);
10626         const char* PrevSpec; // unused
10627         unsigned DiagID; // unused
10628         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10629                            DiagID, Context.getPrintingPolicy());
10630         // Use the identifier location for the type source range.
10631         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10632         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10633         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10634         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10635         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10636       }
10637     }
10638   }
10639 }
10640 
10641 Decl *
10642 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10643                               MultiTemplateParamsArg TemplateParameterLists,
10644                               SkipBodyInfo *SkipBody) {
10645   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10646   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10647   Scope *ParentScope = FnBodyScope->getParent();
10648 
10649   D.setFunctionDefinitionKind(FDK_Definition);
10650   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10651   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10652 }
10653 
10654 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10655   Consumer.HandleInlineMethodDefinition(D);
10656 }
10657 
10658 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10659                              const FunctionDecl*& PossibleZeroParamPrototype) {
10660   // Don't warn about invalid declarations.
10661   if (FD->isInvalidDecl())
10662     return false;
10663 
10664   // Or declarations that aren't global.
10665   if (!FD->isGlobal())
10666     return false;
10667 
10668   // Don't warn about C++ member functions.
10669   if (isa<CXXMethodDecl>(FD))
10670     return false;
10671 
10672   // Don't warn about 'main'.
10673   if (FD->isMain())
10674     return false;
10675 
10676   // Don't warn about inline functions.
10677   if (FD->isInlined())
10678     return false;
10679 
10680   // Don't warn about function templates.
10681   if (FD->getDescribedFunctionTemplate())
10682     return false;
10683 
10684   // Don't warn about function template specializations.
10685   if (FD->isFunctionTemplateSpecialization())
10686     return false;
10687 
10688   // Don't warn for OpenCL kernels.
10689   if (FD->hasAttr<OpenCLKernelAttr>())
10690     return false;
10691 
10692   // Don't warn on explicitly deleted functions.
10693   if (FD->isDeleted())
10694     return false;
10695 
10696   bool MissingPrototype = true;
10697   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10698        Prev; Prev = Prev->getPreviousDecl()) {
10699     // Ignore any declarations that occur in function or method
10700     // scope, because they aren't visible from the header.
10701     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10702       continue;
10703 
10704     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10705     if (FD->getNumParams() == 0)
10706       PossibleZeroParamPrototype = Prev;
10707     break;
10708   }
10709 
10710   return MissingPrototype;
10711 }
10712 
10713 void
10714 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10715                                    const FunctionDecl *EffectiveDefinition,
10716                                    SkipBodyInfo *SkipBody) {
10717   // Don't complain if we're in GNU89 mode and the previous definition
10718   // was an extern inline function.
10719   const FunctionDecl *Definition = EffectiveDefinition;
10720   if (!Definition)
10721     if (!FD->isDefined(Definition))
10722       return;
10723 
10724   if (canRedefineFunction(Definition, getLangOpts()))
10725     return;
10726 
10727   // If we don't have a visible definition of the function, and it's inline or
10728   // a template, skip the new definition.
10729   if (SkipBody && !hasVisibleDefinition(Definition) &&
10730       (Definition->getFormalLinkage() == InternalLinkage ||
10731        Definition->isInlined() ||
10732        Definition->getDescribedFunctionTemplate() ||
10733        Definition->getNumTemplateParameterLists())) {
10734     SkipBody->ShouldSkip = true;
10735     if (auto *TD = Definition->getDescribedFunctionTemplate())
10736       makeMergedDefinitionVisible(TD, FD->getLocation());
10737     else
10738       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10739                                   FD->getLocation());
10740     return;
10741   }
10742 
10743   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10744       Definition->getStorageClass() == SC_Extern)
10745     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10746         << FD->getDeclName() << getLangOpts().CPlusPlus;
10747   else
10748     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10749 
10750   Diag(Definition->getLocation(), diag::note_previous_definition);
10751   FD->setInvalidDecl();
10752 }
10753 
10754 
10755 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10756                                    Sema &S) {
10757   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10758 
10759   LambdaScopeInfo *LSI = S.PushLambdaScope();
10760   LSI->CallOperator = CallOperator;
10761   LSI->Lambda = LambdaClass;
10762   LSI->ReturnType = CallOperator->getReturnType();
10763   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10764 
10765   if (LCD == LCD_None)
10766     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10767   else if (LCD == LCD_ByCopy)
10768     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10769   else if (LCD == LCD_ByRef)
10770     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10771   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10772 
10773   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10774   LSI->Mutable = !CallOperator->isConst();
10775 
10776   // Add the captures to the LSI so they can be noted as already
10777   // captured within tryCaptureVar.
10778   auto I = LambdaClass->field_begin();
10779   for (const auto &C : LambdaClass->captures()) {
10780     if (C.capturesVariable()) {
10781       VarDecl *VD = C.getCapturedVar();
10782       if (VD->isInitCapture())
10783         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10784       QualType CaptureType = VD->getType();
10785       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10786       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10787           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10788           /*EllipsisLoc*/C.isPackExpansion()
10789                          ? C.getEllipsisLoc() : SourceLocation(),
10790           CaptureType, /*Expr*/ nullptr);
10791 
10792     } else if (C.capturesThis()) {
10793       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10794                               S.getCurrentThisType(), /*Expr*/ nullptr);
10795     } else {
10796       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10797     }
10798     ++I;
10799   }
10800 }
10801 
10802 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10803                                     SkipBodyInfo *SkipBody) {
10804   // Clear the last template instantiation error context.
10805   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10806 
10807   if (!D)
10808     return D;
10809   FunctionDecl *FD = nullptr;
10810 
10811   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10812     FD = FunTmpl->getTemplatedDecl();
10813   else
10814     FD = cast<FunctionDecl>(D);
10815 
10816   // See if this is a redefinition.
10817   if (!FD->isLateTemplateParsed()) {
10818     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10819 
10820     // If we're skipping the body, we're done. Don't enter the scope.
10821     if (SkipBody && SkipBody->ShouldSkip)
10822       return D;
10823   }
10824 
10825   // If we are instantiating a generic lambda call operator, push
10826   // a LambdaScopeInfo onto the function stack.  But use the information
10827   // that's already been calculated (ActOnLambdaExpr) to prime the current
10828   // LambdaScopeInfo.
10829   // When the template operator is being specialized, the LambdaScopeInfo,
10830   // has to be properly restored so that tryCaptureVariable doesn't try
10831   // and capture any new variables. In addition when calculating potential
10832   // captures during transformation of nested lambdas, it is necessary to
10833   // have the LSI properly restored.
10834   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10835     assert(ActiveTemplateInstantiations.size() &&
10836       "There should be an active template instantiation on the stack "
10837       "when instantiating a generic lambda!");
10838     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10839   }
10840   else
10841     // Enter a new function scope
10842     PushFunctionScope();
10843 
10844   // Builtin functions cannot be defined.
10845   if (unsigned BuiltinID = FD->getBuiltinID()) {
10846     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10847         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10848       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10849       FD->setInvalidDecl();
10850     }
10851   }
10852 
10853   // The return type of a function definition must be complete
10854   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10855   QualType ResultType = FD->getReturnType();
10856   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10857       !FD->isInvalidDecl() &&
10858       RequireCompleteType(FD->getLocation(), ResultType,
10859                           diag::err_func_def_incomplete_result))
10860     FD->setInvalidDecl();
10861 
10862   if (FnBodyScope)
10863     PushDeclContext(FnBodyScope, FD);
10864 
10865   // Check the validity of our function parameters
10866   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10867                            /*CheckParameterNames=*/true);
10868 
10869   // Introduce our parameters into the function scope
10870   for (auto Param : FD->params()) {
10871     Param->setOwningFunction(FD);
10872 
10873     // If this has an identifier, add it to the scope stack.
10874     if (Param->getIdentifier() && FnBodyScope) {
10875       CheckShadow(FnBodyScope, Param);
10876 
10877       PushOnScopeChains(Param, FnBodyScope);
10878     }
10879   }
10880 
10881   // If we had any tags defined in the function prototype,
10882   // introduce them into the function scope.
10883   if (FnBodyScope) {
10884     for (ArrayRef<NamedDecl *>::iterator
10885              I = FD->getDeclsInPrototypeScope().begin(),
10886              E = FD->getDeclsInPrototypeScope().end();
10887          I != E; ++I) {
10888       NamedDecl *D = *I;
10889 
10890       // Some of these decls (like enums) may have been pinned to the
10891       // translation unit for lack of a real context earlier. If so, remove
10892       // from the translation unit and reattach to the current context.
10893       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10894         // Is the decl actually in the context?
10895         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10896           if (DI == D) {
10897             Context.getTranslationUnitDecl()->removeDecl(D);
10898             break;
10899           }
10900         }
10901         // Either way, reassign the lexical decl context to our FunctionDecl.
10902         D->setLexicalDeclContext(CurContext);
10903       }
10904 
10905       // If the decl has a non-null name, make accessible in the current scope.
10906       if (!D->getName().empty())
10907         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10908 
10909       // Similarly, dive into enums and fish their constants out, making them
10910       // accessible in this scope.
10911       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10912         for (auto *EI : ED->enumerators())
10913           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10914       }
10915     }
10916   }
10917 
10918   // Ensure that the function's exception specification is instantiated.
10919   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10920     ResolveExceptionSpec(D->getLocation(), FPT);
10921 
10922   // dllimport cannot be applied to non-inline function definitions.
10923   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10924       !FD->isTemplateInstantiation()) {
10925     assert(!FD->hasAttr<DLLExportAttr>());
10926     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10927     FD->setInvalidDecl();
10928     return D;
10929   }
10930   // We want to attach documentation to original Decl (which might be
10931   // a function template).
10932   ActOnDocumentableDecl(D);
10933   if (getCurLexicalContext()->isObjCContainer() &&
10934       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10935       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10936     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10937 
10938   return D;
10939 }
10940 
10941 /// \brief Given the set of return statements within a function body,
10942 /// compute the variables that are subject to the named return value
10943 /// optimization.
10944 ///
10945 /// Each of the variables that is subject to the named return value
10946 /// optimization will be marked as NRVO variables in the AST, and any
10947 /// return statement that has a marked NRVO variable as its NRVO candidate can
10948 /// use the named return value optimization.
10949 ///
10950 /// This function applies a very simplistic algorithm for NRVO: if every return
10951 /// statement in the scope of a variable has the same NRVO candidate, that
10952 /// candidate is an NRVO variable.
10953 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10954   ReturnStmt **Returns = Scope->Returns.data();
10955 
10956   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10957     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10958       if (!NRVOCandidate->isNRVOVariable())
10959         Returns[I]->setNRVOCandidate(nullptr);
10960     }
10961   }
10962 }
10963 
10964 bool Sema::canDelayFunctionBody(const Declarator &D) {
10965   // We can't delay parsing the body of a constexpr function template (yet).
10966   if (D.getDeclSpec().isConstexprSpecified())
10967     return false;
10968 
10969   // We can't delay parsing the body of a function template with a deduced
10970   // return type (yet).
10971   if (D.getDeclSpec().containsPlaceholderType()) {
10972     // If the placeholder introduces a non-deduced trailing return type,
10973     // we can still delay parsing it.
10974     if (D.getNumTypeObjects()) {
10975       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10976       if (Outer.Kind == DeclaratorChunk::Function &&
10977           Outer.Fun.hasTrailingReturnType()) {
10978         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10979         return Ty.isNull() || !Ty->isUndeducedType();
10980       }
10981     }
10982     return false;
10983   }
10984 
10985   return true;
10986 }
10987 
10988 bool Sema::canSkipFunctionBody(Decl *D) {
10989   // We cannot skip the body of a function (or function template) which is
10990   // constexpr, since we may need to evaluate its body in order to parse the
10991   // rest of the file.
10992   // We cannot skip the body of a function with an undeduced return type,
10993   // because any callers of that function need to know the type.
10994   if (const FunctionDecl *FD = D->getAsFunction())
10995     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10996       return false;
10997   return Consumer.shouldSkipFunctionBody(D);
10998 }
10999 
11000 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11001   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11002     FD->setHasSkippedBody();
11003   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11004     MD->setHasSkippedBody();
11005   return ActOnFinishFunctionBody(Decl, nullptr);
11006 }
11007 
11008 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11009   return ActOnFinishFunctionBody(D, BodyArg, false);
11010 }
11011 
11012 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11013                                     bool IsInstantiation) {
11014   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11015 
11016   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11017   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11018 
11019   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11020     CheckCompletedCoroutineBody(FD, Body);
11021 
11022   if (FD) {
11023     FD->setBody(Body);
11024 
11025     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11026         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11027       // If the function has a deduced result type but contains no 'return'
11028       // statements, the result type as written must be exactly 'auto', and
11029       // the deduced result type is 'void'.
11030       if (!FD->getReturnType()->getAs<AutoType>()) {
11031         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11032             << FD->getReturnType();
11033         FD->setInvalidDecl();
11034       } else {
11035         // Substitute 'void' for the 'auto' in the type.
11036         TypeLoc ResultType = getReturnTypeLoc(FD);
11037         Context.adjustDeducedFunctionResultType(
11038             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11039       }
11040     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11041       auto *LSI = getCurLambda();
11042       if (LSI->HasImplicitReturnType) {
11043         deduceClosureReturnType(*LSI);
11044 
11045         // C++11 [expr.prim.lambda]p4:
11046         //   [...] if there are no return statements in the compound-statement
11047         //   [the deduced type is] the type void
11048         QualType RetType =
11049             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11050 
11051         // Update the return type to the deduced type.
11052         const FunctionProtoType *Proto =
11053             FD->getType()->getAs<FunctionProtoType>();
11054         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11055                                             Proto->getExtProtoInfo()));
11056       }
11057     }
11058 
11059     // The only way to be included in UndefinedButUsed is if there is an
11060     // ODR use before the definition. Avoid the expensive map lookup if this
11061     // is the first declaration.
11062     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11063       if (!FD->isExternallyVisible())
11064         UndefinedButUsed.erase(FD);
11065       else if (FD->isInlined() &&
11066                !LangOpts.GNUInline &&
11067                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11068         UndefinedButUsed.erase(FD);
11069     }
11070 
11071     // If the function implicitly returns zero (like 'main') or is naked,
11072     // don't complain about missing return statements.
11073     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11074       WP.disableCheckFallThrough();
11075 
11076     // MSVC permits the use of pure specifier (=0) on function definition,
11077     // defined at class scope, warn about this non-standard construct.
11078     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11079       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11080 
11081     if (!FD->isInvalidDecl()) {
11082       // Don't diagnose unused parameters of defaulted or deleted functions.
11083       if (!FD->isDeleted() && !FD->isDefaulted())
11084         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11085       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11086                                              FD->getReturnType(), FD);
11087 
11088       // If this is a structor, we need a vtable.
11089       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11090         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11091       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11092         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11093 
11094       // Try to apply the named return value optimization. We have to check
11095       // if we can do this here because lambdas keep return statements around
11096       // to deduce an implicit return type.
11097       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11098           !FD->isDependentContext())
11099         computeNRVO(Body, getCurFunction());
11100     }
11101 
11102     // GNU warning -Wmissing-prototypes:
11103     //   Warn if a global function is defined without a previous
11104     //   prototype declaration. This warning is issued even if the
11105     //   definition itself provides a prototype. The aim is to detect
11106     //   global functions that fail to be declared in header files.
11107     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11108     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11109       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11110 
11111       if (PossibleZeroParamPrototype) {
11112         // We found a declaration that is not a prototype,
11113         // but that could be a zero-parameter prototype
11114         if (TypeSourceInfo *TI =
11115                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11116           TypeLoc TL = TI->getTypeLoc();
11117           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11118             Diag(PossibleZeroParamPrototype->getLocation(),
11119                  diag::note_declaration_not_a_prototype)
11120                 << PossibleZeroParamPrototype
11121                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11122         }
11123       }
11124     }
11125 
11126     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11127       const CXXMethodDecl *KeyFunction;
11128       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11129           MD->isVirtual() &&
11130           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11131           MD == KeyFunction->getCanonicalDecl()) {
11132         // Update the key-function state if necessary for this ABI.
11133         if (FD->isInlined() &&
11134             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11135           Context.setNonKeyFunction(MD);
11136 
11137           // If the newly-chosen key function is already defined, then we
11138           // need to mark the vtable as used retroactively.
11139           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11140           const FunctionDecl *Definition;
11141           if (KeyFunction && KeyFunction->isDefined(Definition))
11142             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11143         } else {
11144           // We just defined they key function; mark the vtable as used.
11145           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11146         }
11147       }
11148     }
11149 
11150     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11151            "Function parsing confused");
11152   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11153     assert(MD == getCurMethodDecl() && "Method parsing confused");
11154     MD->setBody(Body);
11155     if (!MD->isInvalidDecl()) {
11156       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11157       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11158                                              MD->getReturnType(), MD);
11159 
11160       if (Body)
11161         computeNRVO(Body, getCurFunction());
11162     }
11163     if (getCurFunction()->ObjCShouldCallSuper) {
11164       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11165         << MD->getSelector().getAsString();
11166       getCurFunction()->ObjCShouldCallSuper = false;
11167     }
11168     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11169       const ObjCMethodDecl *InitMethod = nullptr;
11170       bool isDesignated =
11171           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11172       assert(isDesignated && InitMethod);
11173       (void)isDesignated;
11174 
11175       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11176         auto IFace = MD->getClassInterface();
11177         if (!IFace)
11178           return false;
11179         auto SuperD = IFace->getSuperClass();
11180         if (!SuperD)
11181           return false;
11182         return SuperD->getIdentifier() ==
11183             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11184       };
11185       // Don't issue this warning for unavailable inits or direct subclasses
11186       // of NSObject.
11187       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11188         Diag(MD->getLocation(),
11189              diag::warn_objc_designated_init_missing_super_call);
11190         Diag(InitMethod->getLocation(),
11191              diag::note_objc_designated_init_marked_here);
11192       }
11193       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11194     }
11195     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11196       // Don't issue this warning for unavaialable inits.
11197       if (!MD->isUnavailable())
11198         Diag(MD->getLocation(),
11199              diag::warn_objc_secondary_init_missing_init_call);
11200       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11201     }
11202   } else {
11203     return nullptr;
11204   }
11205 
11206   assert(!getCurFunction()->ObjCShouldCallSuper &&
11207          "This should only be set for ObjC methods, which should have been "
11208          "handled in the block above.");
11209 
11210   // Verify and clean out per-function state.
11211   if (Body && (!FD || !FD->isDefaulted())) {
11212     // C++ constructors that have function-try-blocks can't have return
11213     // statements in the handlers of that block. (C++ [except.handle]p14)
11214     // Verify this.
11215     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11216       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11217 
11218     // Verify that gotos and switch cases don't jump into scopes illegally.
11219     if (getCurFunction()->NeedsScopeChecking() &&
11220         !PP.isCodeCompletionEnabled())
11221       DiagnoseInvalidJumps(Body);
11222 
11223     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11224       if (!Destructor->getParent()->isDependentType())
11225         CheckDestructor(Destructor);
11226 
11227       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11228                                              Destructor->getParent());
11229     }
11230 
11231     // If any errors have occurred, clear out any temporaries that may have
11232     // been leftover. This ensures that these temporaries won't be picked up for
11233     // deletion in some later function.
11234     if (getDiagnostics().hasErrorOccurred() ||
11235         getDiagnostics().getSuppressAllDiagnostics()) {
11236       DiscardCleanupsInEvaluationContext();
11237     }
11238     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11239         !isa<FunctionTemplateDecl>(dcl)) {
11240       // Since the body is valid, issue any analysis-based warnings that are
11241       // enabled.
11242       ActivePolicy = &WP;
11243     }
11244 
11245     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11246         (!CheckConstexprFunctionDecl(FD) ||
11247          !CheckConstexprFunctionBody(FD, Body)))
11248       FD->setInvalidDecl();
11249 
11250     if (FD && FD->hasAttr<NakedAttr>()) {
11251       for (const Stmt *S : Body->children()) {
11252         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11253           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11254           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11255           FD->setInvalidDecl();
11256           break;
11257         }
11258       }
11259     }
11260 
11261     assert(ExprCleanupObjects.size() ==
11262                ExprEvalContexts.back().NumCleanupObjects &&
11263            "Leftover temporaries in function");
11264     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11265     assert(MaybeODRUseExprs.empty() &&
11266            "Leftover expressions for odr-use checking");
11267   }
11268 
11269   if (!IsInstantiation)
11270     PopDeclContext();
11271 
11272   PopFunctionScopeInfo(ActivePolicy, dcl);
11273   // If any errors have occurred, clear out any temporaries that may have
11274   // been leftover. This ensures that these temporaries won't be picked up for
11275   // deletion in some later function.
11276   if (getDiagnostics().hasErrorOccurred()) {
11277     DiscardCleanupsInEvaluationContext();
11278   }
11279 
11280   return dcl;
11281 }
11282 
11283 
11284 /// When we finish delayed parsing of an attribute, we must attach it to the
11285 /// relevant Decl.
11286 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11287                                        ParsedAttributes &Attrs) {
11288   // Always attach attributes to the underlying decl.
11289   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11290     D = TD->getTemplatedDecl();
11291   ProcessDeclAttributeList(S, D, Attrs.getList());
11292 
11293   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11294     if (Method->isStatic())
11295       checkThisInStaticMemberFunctionAttributes(Method);
11296 }
11297 
11298 
11299 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11300 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11301 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11302                                           IdentifierInfo &II, Scope *S) {
11303   // Before we produce a declaration for an implicitly defined
11304   // function, see whether there was a locally-scoped declaration of
11305   // this name as a function or variable. If so, use that
11306   // (non-visible) declaration, and complain about it.
11307   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11308     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11309     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11310     return ExternCPrev;
11311   }
11312 
11313   // Extension in C99.  Legal in C90, but warn about it.
11314   unsigned diag_id;
11315   if (II.getName().startswith("__builtin_"))
11316     diag_id = diag::warn_builtin_unknown;
11317   else if (getLangOpts().C99)
11318     diag_id = diag::ext_implicit_function_decl;
11319   else
11320     diag_id = diag::warn_implicit_function_decl;
11321   Diag(Loc, diag_id) << &II;
11322 
11323   // Because typo correction is expensive, only do it if the implicit
11324   // function declaration is going to be treated as an error.
11325   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11326     TypoCorrection Corrected;
11327     if (S &&
11328         (Corrected = CorrectTypo(
11329              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11330              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11331       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11332                    /*ErrorRecovery*/false);
11333   }
11334 
11335   // Set a Declarator for the implicit definition: int foo();
11336   const char *Dummy;
11337   AttributeFactory attrFactory;
11338   DeclSpec DS(attrFactory);
11339   unsigned DiagID;
11340   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11341                                   Context.getPrintingPolicy());
11342   (void)Error; // Silence warning.
11343   assert(!Error && "Error setting up implicit decl!");
11344   SourceLocation NoLoc;
11345   Declarator D(DS, Declarator::BlockContext);
11346   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11347                                              /*IsAmbiguous=*/false,
11348                                              /*LParenLoc=*/NoLoc,
11349                                              /*Params=*/nullptr,
11350                                              /*NumParams=*/0,
11351                                              /*EllipsisLoc=*/NoLoc,
11352                                              /*RParenLoc=*/NoLoc,
11353                                              /*TypeQuals=*/0,
11354                                              /*RefQualifierIsLvalueRef=*/true,
11355                                              /*RefQualifierLoc=*/NoLoc,
11356                                              /*ConstQualifierLoc=*/NoLoc,
11357                                              /*VolatileQualifierLoc=*/NoLoc,
11358                                              /*RestrictQualifierLoc=*/NoLoc,
11359                                              /*MutableLoc=*/NoLoc,
11360                                              EST_None,
11361                                              /*ESpecRange=*/SourceRange(),
11362                                              /*Exceptions=*/nullptr,
11363                                              /*ExceptionRanges=*/nullptr,
11364                                              /*NumExceptions=*/0,
11365                                              /*NoexceptExpr=*/nullptr,
11366                                              /*ExceptionSpecTokens=*/nullptr,
11367                                              Loc, Loc, D),
11368                 DS.getAttributes(),
11369                 SourceLocation());
11370   D.SetIdentifier(&II, Loc);
11371 
11372   // Insert this function into translation-unit scope.
11373 
11374   DeclContext *PrevDC = CurContext;
11375   CurContext = Context.getTranslationUnitDecl();
11376 
11377   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11378   FD->setImplicit();
11379 
11380   CurContext = PrevDC;
11381 
11382   AddKnownFunctionAttributes(FD);
11383 
11384   return FD;
11385 }
11386 
11387 /// \brief Adds any function attributes that we know a priori based on
11388 /// the declaration of this function.
11389 ///
11390 /// These attributes can apply both to implicitly-declared builtins
11391 /// (like __builtin___printf_chk) or to library-declared functions
11392 /// like NSLog or printf.
11393 ///
11394 /// We need to check for duplicate attributes both here and where user-written
11395 /// attributes are applied to declarations.
11396 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11397   if (FD->isInvalidDecl())
11398     return;
11399 
11400   // If this is a built-in function, map its builtin attributes to
11401   // actual attributes.
11402   if (unsigned BuiltinID = FD->getBuiltinID()) {
11403     // Handle printf-formatting attributes.
11404     unsigned FormatIdx;
11405     bool HasVAListArg;
11406     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11407       if (!FD->hasAttr<FormatAttr>()) {
11408         const char *fmt = "printf";
11409         unsigned int NumParams = FD->getNumParams();
11410         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11411             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11412           fmt = "NSString";
11413         FD->addAttr(FormatAttr::CreateImplicit(Context,
11414                                                &Context.Idents.get(fmt),
11415                                                FormatIdx+1,
11416                                                HasVAListArg ? 0 : FormatIdx+2,
11417                                                FD->getLocation()));
11418       }
11419     }
11420     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11421                                              HasVAListArg)) {
11422      if (!FD->hasAttr<FormatAttr>())
11423        FD->addAttr(FormatAttr::CreateImplicit(Context,
11424                                               &Context.Idents.get("scanf"),
11425                                               FormatIdx+1,
11426                                               HasVAListArg ? 0 : FormatIdx+2,
11427                                               FD->getLocation()));
11428     }
11429 
11430     // Mark const if we don't care about errno and that is the only
11431     // thing preventing the function from being const. This allows
11432     // IRgen to use LLVM intrinsics for such functions.
11433     if (!getLangOpts().MathErrno &&
11434         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11435       if (!FD->hasAttr<ConstAttr>())
11436         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11437     }
11438 
11439     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11440         !FD->hasAttr<ReturnsTwiceAttr>())
11441       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11442                                          FD->getLocation()));
11443     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11444       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11445     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11446       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11447     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11448         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11449         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11450       // Assign appropriate attribute depending on CUDA compilation
11451       // mode and the target builtin belongs to. E.g. during host
11452       // compilation, aux builtins are __device__, the rest are __host__.
11453       if (getLangOpts().CUDAIsDevice !=
11454           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11455         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11456       else
11457         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11458     }
11459   }
11460 
11461   IdentifierInfo *Name = FD->getIdentifier();
11462   if (!Name)
11463     return;
11464   if ((!getLangOpts().CPlusPlus &&
11465        FD->getDeclContext()->isTranslationUnit()) ||
11466       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11467        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11468        LinkageSpecDecl::lang_c)) {
11469     // Okay: this could be a libc/libm/Objective-C function we know
11470     // about.
11471   } else
11472     return;
11473 
11474   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11475     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11476     // target-specific builtins, perhaps?
11477     if (!FD->hasAttr<FormatAttr>())
11478       FD->addAttr(FormatAttr::CreateImplicit(Context,
11479                                              &Context.Idents.get("printf"), 2,
11480                                              Name->isStr("vasprintf") ? 0 : 3,
11481                                              FD->getLocation()));
11482   }
11483 
11484   if (Name->isStr("__CFStringMakeConstantString")) {
11485     // We already have a __builtin___CFStringMakeConstantString,
11486     // but builds that use -fno-constant-cfstrings don't go through that.
11487     if (!FD->hasAttr<FormatArgAttr>())
11488       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11489                                                 FD->getLocation()));
11490   }
11491 }
11492 
11493 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11494                                     TypeSourceInfo *TInfo) {
11495   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11496   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11497 
11498   if (!TInfo) {
11499     assert(D.isInvalidType() && "no declarator info for valid type");
11500     TInfo = Context.getTrivialTypeSourceInfo(T);
11501   }
11502 
11503   // Scope manipulation handled by caller.
11504   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11505                                            D.getLocStart(),
11506                                            D.getIdentifierLoc(),
11507                                            D.getIdentifier(),
11508                                            TInfo);
11509 
11510   // Bail out immediately if we have an invalid declaration.
11511   if (D.isInvalidType()) {
11512     NewTD->setInvalidDecl();
11513     return NewTD;
11514   }
11515 
11516   if (D.getDeclSpec().isModulePrivateSpecified()) {
11517     if (CurContext->isFunctionOrMethod())
11518       Diag(NewTD->getLocation(), diag::err_module_private_local)
11519         << 2 << NewTD->getDeclName()
11520         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11521         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11522     else
11523       NewTD->setModulePrivate();
11524   }
11525 
11526   // C++ [dcl.typedef]p8:
11527   //   If the typedef declaration defines an unnamed class (or
11528   //   enum), the first typedef-name declared by the declaration
11529   //   to be that class type (or enum type) is used to denote the
11530   //   class type (or enum type) for linkage purposes only.
11531   // We need to check whether the type was declared in the declaration.
11532   switch (D.getDeclSpec().getTypeSpecType()) {
11533   case TST_enum:
11534   case TST_struct:
11535   case TST_interface:
11536   case TST_union:
11537   case TST_class: {
11538     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11539     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11540     break;
11541   }
11542 
11543   default:
11544     break;
11545   }
11546 
11547   return NewTD;
11548 }
11549 
11550 
11551 /// \brief Check that this is a valid underlying type for an enum declaration.
11552 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11553   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11554   QualType T = TI->getType();
11555 
11556   if (T->isDependentType())
11557     return false;
11558 
11559   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11560     if (BT->isInteger())
11561       return false;
11562 
11563   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11564   return true;
11565 }
11566 
11567 /// Check whether this is a valid redeclaration of a previous enumeration.
11568 /// \return true if the redeclaration was invalid.
11569 bool Sema::CheckEnumRedeclaration(
11570     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11571     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11572   bool IsFixed = !EnumUnderlyingTy.isNull();
11573 
11574   if (IsScoped != Prev->isScoped()) {
11575     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11576       << Prev->isScoped();
11577     Diag(Prev->getLocation(), diag::note_previous_declaration);
11578     return true;
11579   }
11580 
11581   if (IsFixed && Prev->isFixed()) {
11582     if (!EnumUnderlyingTy->isDependentType() &&
11583         !Prev->getIntegerType()->isDependentType() &&
11584         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11585                                         Prev->getIntegerType())) {
11586       // TODO: Highlight the underlying type of the redeclaration.
11587       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11588         << EnumUnderlyingTy << Prev->getIntegerType();
11589       Diag(Prev->getLocation(), diag::note_previous_declaration)
11590           << Prev->getIntegerTypeRange();
11591       return true;
11592     }
11593   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11594     ;
11595   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11596     ;
11597   } else if (IsFixed != Prev->isFixed()) {
11598     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11599       << Prev->isFixed();
11600     Diag(Prev->getLocation(), diag::note_previous_declaration);
11601     return true;
11602   }
11603 
11604   return false;
11605 }
11606 
11607 /// \brief Get diagnostic %select index for tag kind for
11608 /// redeclaration diagnostic message.
11609 /// WARNING: Indexes apply to particular diagnostics only!
11610 ///
11611 /// \returns diagnostic %select index.
11612 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11613   switch (Tag) {
11614   case TTK_Struct: return 0;
11615   case TTK_Interface: return 1;
11616   case TTK_Class:  return 2;
11617   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11618   }
11619 }
11620 
11621 /// \brief Determine if tag kind is a class-key compatible with
11622 /// class for redeclaration (class, struct, or __interface).
11623 ///
11624 /// \returns true iff the tag kind is compatible.
11625 static bool isClassCompatTagKind(TagTypeKind Tag)
11626 {
11627   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11628 }
11629 
11630 /// \brief Determine whether a tag with a given kind is acceptable
11631 /// as a redeclaration of the given tag declaration.
11632 ///
11633 /// \returns true if the new tag kind is acceptable, false otherwise.
11634 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11635                                         TagTypeKind NewTag, bool isDefinition,
11636                                         SourceLocation NewTagLoc,
11637                                         const IdentifierInfo *Name) {
11638   // C++ [dcl.type.elab]p3:
11639   //   The class-key or enum keyword present in the
11640   //   elaborated-type-specifier shall agree in kind with the
11641   //   declaration to which the name in the elaborated-type-specifier
11642   //   refers. This rule also applies to the form of
11643   //   elaborated-type-specifier that declares a class-name or
11644   //   friend class since it can be construed as referring to the
11645   //   definition of the class. Thus, in any
11646   //   elaborated-type-specifier, the enum keyword shall be used to
11647   //   refer to an enumeration (7.2), the union class-key shall be
11648   //   used to refer to a union (clause 9), and either the class or
11649   //   struct class-key shall be used to refer to a class (clause 9)
11650   //   declared using the class or struct class-key.
11651   TagTypeKind OldTag = Previous->getTagKind();
11652   if (!isDefinition || !isClassCompatTagKind(NewTag))
11653     if (OldTag == NewTag)
11654       return true;
11655 
11656   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11657     // Warn about the struct/class tag mismatch.
11658     bool isTemplate = false;
11659     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11660       isTemplate = Record->getDescribedClassTemplate();
11661 
11662     if (!ActiveTemplateInstantiations.empty()) {
11663       // In a template instantiation, do not offer fix-its for tag mismatches
11664       // since they usually mess up the template instead of fixing the problem.
11665       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11666         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11667         << getRedeclDiagFromTagKind(OldTag);
11668       return true;
11669     }
11670 
11671     if (isDefinition) {
11672       // On definitions, check previous tags and issue a fix-it for each
11673       // one that doesn't match the current tag.
11674       if (Previous->getDefinition()) {
11675         // Don't suggest fix-its for redefinitions.
11676         return true;
11677       }
11678 
11679       bool previousMismatch = false;
11680       for (auto I : Previous->redecls()) {
11681         if (I->getTagKind() != NewTag) {
11682           if (!previousMismatch) {
11683             previousMismatch = true;
11684             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11685               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11686               << getRedeclDiagFromTagKind(I->getTagKind());
11687           }
11688           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11689             << getRedeclDiagFromTagKind(NewTag)
11690             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11691                  TypeWithKeyword::getTagTypeKindName(NewTag));
11692         }
11693       }
11694       return true;
11695     }
11696 
11697     // Check for a previous definition.  If current tag and definition
11698     // are same type, do nothing.  If no definition, but disagree with
11699     // with previous tag type, give a warning, but no fix-it.
11700     const TagDecl *Redecl = Previous->getDefinition() ?
11701                             Previous->getDefinition() : Previous;
11702     if (Redecl->getTagKind() == NewTag) {
11703       return true;
11704     }
11705 
11706     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11707       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11708       << getRedeclDiagFromTagKind(OldTag);
11709     Diag(Redecl->getLocation(), diag::note_previous_use);
11710 
11711     // If there is a previous definition, suggest a fix-it.
11712     if (Previous->getDefinition()) {
11713         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11714           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11715           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11716                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11717     }
11718 
11719     return true;
11720   }
11721   return false;
11722 }
11723 
11724 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11725 /// from an outer enclosing namespace or file scope inside a friend declaration.
11726 /// This should provide the commented out code in the following snippet:
11727 ///   namespace N {
11728 ///     struct X;
11729 ///     namespace M {
11730 ///       struct Y { friend struct /*N::*/ X; };
11731 ///     }
11732 ///   }
11733 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11734                                          SourceLocation NameLoc) {
11735   // While the decl is in a namespace, do repeated lookup of that name and see
11736   // if we get the same namespace back.  If we do not, continue until
11737   // translation unit scope, at which point we have a fully qualified NNS.
11738   SmallVector<IdentifierInfo *, 4> Namespaces;
11739   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11740   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11741     // This tag should be declared in a namespace, which can only be enclosed by
11742     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11743     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11744     if (!Namespace || Namespace->isAnonymousNamespace())
11745       return FixItHint();
11746     IdentifierInfo *II = Namespace->getIdentifier();
11747     Namespaces.push_back(II);
11748     NamedDecl *Lookup = SemaRef.LookupSingleName(
11749         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11750     if (Lookup == Namespace)
11751       break;
11752   }
11753 
11754   // Once we have all the namespaces, reverse them to go outermost first, and
11755   // build an NNS.
11756   SmallString<64> Insertion;
11757   llvm::raw_svector_ostream OS(Insertion);
11758   if (DC->isTranslationUnit())
11759     OS << "::";
11760   std::reverse(Namespaces.begin(), Namespaces.end());
11761   for (auto *II : Namespaces)
11762     OS << II->getName() << "::";
11763   return FixItHint::CreateInsertion(NameLoc, Insertion);
11764 }
11765 
11766 /// \brief Determine whether a tag originally declared in context \p OldDC can
11767 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11768 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11769 /// using-declaration).
11770 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11771                                          DeclContext *NewDC) {
11772   OldDC = OldDC->getRedeclContext();
11773   NewDC = NewDC->getRedeclContext();
11774 
11775   if (OldDC->Equals(NewDC))
11776     return true;
11777 
11778   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11779   // encloses the other).
11780   if (S.getLangOpts().MSVCCompat &&
11781       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11782     return true;
11783 
11784   return false;
11785 }
11786 
11787 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11788 /// former case, Name will be non-null.  In the later case, Name will be null.
11789 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11790 /// reference/declaration/definition of a tag.
11791 ///
11792 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11793 /// trailing-type-specifier) other than one in an alias-declaration.
11794 ///
11795 /// \param SkipBody If non-null, will be set to indicate if the caller should
11796 /// skip the definition of this tag and treat it as if it were a declaration.
11797 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11798                      SourceLocation KWLoc, CXXScopeSpec &SS,
11799                      IdentifierInfo *Name, SourceLocation NameLoc,
11800                      AttributeList *Attr, AccessSpecifier AS,
11801                      SourceLocation ModulePrivateLoc,
11802                      MultiTemplateParamsArg TemplateParameterLists,
11803                      bool &OwnedDecl, bool &IsDependent,
11804                      SourceLocation ScopedEnumKWLoc,
11805                      bool ScopedEnumUsesClassTag,
11806                      TypeResult UnderlyingType,
11807                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11808   // If this is not a definition, it must have a name.
11809   IdentifierInfo *OrigName = Name;
11810   assert((Name != nullptr || TUK == TUK_Definition) &&
11811          "Nameless record must be a definition!");
11812   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11813 
11814   OwnedDecl = false;
11815   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11816   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11817 
11818   // FIXME: Check explicit specializations more carefully.
11819   bool isExplicitSpecialization = false;
11820   bool Invalid = false;
11821 
11822   // We only need to do this matching if we have template parameters
11823   // or a scope specifier, which also conveniently avoids this work
11824   // for non-C++ cases.
11825   if (TemplateParameterLists.size() > 0 ||
11826       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11827     if (TemplateParameterList *TemplateParams =
11828             MatchTemplateParametersToScopeSpecifier(
11829                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11830                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11831       if (Kind == TTK_Enum) {
11832         Diag(KWLoc, diag::err_enum_template);
11833         return nullptr;
11834       }
11835 
11836       if (TemplateParams->size() > 0) {
11837         // This is a declaration or definition of a class template (which may
11838         // be a member of another template).
11839 
11840         if (Invalid)
11841           return nullptr;
11842 
11843         OwnedDecl = false;
11844         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11845                                                SS, Name, NameLoc, Attr,
11846                                                TemplateParams, AS,
11847                                                ModulePrivateLoc,
11848                                                /*FriendLoc*/SourceLocation(),
11849                                                TemplateParameterLists.size()-1,
11850                                                TemplateParameterLists.data(),
11851                                                SkipBody);
11852         return Result.get();
11853       } else {
11854         // The "template<>" header is extraneous.
11855         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11856           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11857         isExplicitSpecialization = true;
11858       }
11859     }
11860   }
11861 
11862   // Figure out the underlying type if this a enum declaration. We need to do
11863   // this early, because it's needed to detect if this is an incompatible
11864   // redeclaration.
11865   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11866   bool EnumUnderlyingIsImplicit = false;
11867 
11868   if (Kind == TTK_Enum) {
11869     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11870       // No underlying type explicitly specified, or we failed to parse the
11871       // type, default to int.
11872       EnumUnderlying = Context.IntTy.getTypePtr();
11873     else if (UnderlyingType.get()) {
11874       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11875       // integral type; any cv-qualification is ignored.
11876       TypeSourceInfo *TI = nullptr;
11877       GetTypeFromParser(UnderlyingType.get(), &TI);
11878       EnumUnderlying = TI;
11879 
11880       if (CheckEnumUnderlyingType(TI))
11881         // Recover by falling back to int.
11882         EnumUnderlying = Context.IntTy.getTypePtr();
11883 
11884       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11885                                           UPPC_FixedUnderlyingType))
11886         EnumUnderlying = Context.IntTy.getTypePtr();
11887 
11888     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11889       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11890         // Microsoft enums are always of int type.
11891         EnumUnderlying = Context.IntTy.getTypePtr();
11892         EnumUnderlyingIsImplicit = true;
11893       }
11894     }
11895   }
11896 
11897   DeclContext *SearchDC = CurContext;
11898   DeclContext *DC = CurContext;
11899   bool isStdBadAlloc = false;
11900 
11901   RedeclarationKind Redecl = ForRedeclaration;
11902   if (TUK == TUK_Friend || TUK == TUK_Reference)
11903     Redecl = NotForRedeclaration;
11904 
11905   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11906   if (Name && SS.isNotEmpty()) {
11907     // We have a nested-name tag ('struct foo::bar').
11908 
11909     // Check for invalid 'foo::'.
11910     if (SS.isInvalid()) {
11911       Name = nullptr;
11912       goto CreateNewDecl;
11913     }
11914 
11915     // If this is a friend or a reference to a class in a dependent
11916     // context, don't try to make a decl for it.
11917     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11918       DC = computeDeclContext(SS, false);
11919       if (!DC) {
11920         IsDependent = true;
11921         return nullptr;
11922       }
11923     } else {
11924       DC = computeDeclContext(SS, true);
11925       if (!DC) {
11926         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11927           << SS.getRange();
11928         return nullptr;
11929       }
11930     }
11931 
11932     if (RequireCompleteDeclContext(SS, DC))
11933       return nullptr;
11934 
11935     SearchDC = DC;
11936     // Look-up name inside 'foo::'.
11937     LookupQualifiedName(Previous, DC);
11938 
11939     if (Previous.isAmbiguous())
11940       return nullptr;
11941 
11942     if (Previous.empty()) {
11943       // Name lookup did not find anything. However, if the
11944       // nested-name-specifier refers to the current instantiation,
11945       // and that current instantiation has any dependent base
11946       // classes, we might find something at instantiation time: treat
11947       // this as a dependent elaborated-type-specifier.
11948       // But this only makes any sense for reference-like lookups.
11949       if (Previous.wasNotFoundInCurrentInstantiation() &&
11950           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11951         IsDependent = true;
11952         return nullptr;
11953       }
11954 
11955       // A tag 'foo::bar' must already exist.
11956       Diag(NameLoc, diag::err_not_tag_in_scope)
11957         << Kind << Name << DC << SS.getRange();
11958       Name = nullptr;
11959       Invalid = true;
11960       goto CreateNewDecl;
11961     }
11962   } else if (Name) {
11963     // C++14 [class.mem]p14:
11964     //   If T is the name of a class, then each of the following shall have a
11965     //   name different from T:
11966     //    -- every member of class T that is itself a type
11967     if (TUK != TUK_Reference && TUK != TUK_Friend &&
11968         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11969       return nullptr;
11970 
11971     // If this is a named struct, check to see if there was a previous forward
11972     // declaration or definition.
11973     // FIXME: We're looking into outer scopes here, even when we
11974     // shouldn't be. Doing so can result in ambiguities that we
11975     // shouldn't be diagnosing.
11976     LookupName(Previous, S);
11977 
11978     // When declaring or defining a tag, ignore ambiguities introduced
11979     // by types using'ed into this scope.
11980     if (Previous.isAmbiguous() &&
11981         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11982       LookupResult::Filter F = Previous.makeFilter();
11983       while (F.hasNext()) {
11984         NamedDecl *ND = F.next();
11985         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11986           F.erase();
11987       }
11988       F.done();
11989     }
11990 
11991     // C++11 [namespace.memdef]p3:
11992     //   If the name in a friend declaration is neither qualified nor
11993     //   a template-id and the declaration is a function or an
11994     //   elaborated-type-specifier, the lookup to determine whether
11995     //   the entity has been previously declared shall not consider
11996     //   any scopes outside the innermost enclosing namespace.
11997     //
11998     // MSVC doesn't implement the above rule for types, so a friend tag
11999     // declaration may be a redeclaration of a type declared in an enclosing
12000     // scope.  They do implement this rule for friend functions.
12001     //
12002     // Does it matter that this should be by scope instead of by
12003     // semantic context?
12004     if (!Previous.empty() && TUK == TUK_Friend) {
12005       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12006       LookupResult::Filter F = Previous.makeFilter();
12007       bool FriendSawTagOutsideEnclosingNamespace = false;
12008       while (F.hasNext()) {
12009         NamedDecl *ND = F.next();
12010         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12011         if (DC->isFileContext() &&
12012             !EnclosingNS->Encloses(ND->getDeclContext())) {
12013           if (getLangOpts().MSVCCompat)
12014             FriendSawTagOutsideEnclosingNamespace = true;
12015           else
12016             F.erase();
12017         }
12018       }
12019       F.done();
12020 
12021       // Diagnose this MSVC extension in the easy case where lookup would have
12022       // unambiguously found something outside the enclosing namespace.
12023       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12024         NamedDecl *ND = Previous.getFoundDecl();
12025         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12026             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12027       }
12028     }
12029 
12030     // Note:  there used to be some attempt at recovery here.
12031     if (Previous.isAmbiguous())
12032       return nullptr;
12033 
12034     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12035       // FIXME: This makes sure that we ignore the contexts associated
12036       // with C structs, unions, and enums when looking for a matching
12037       // tag declaration or definition. See the similar lookup tweak
12038       // in Sema::LookupName; is there a better way to deal with this?
12039       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12040         SearchDC = SearchDC->getParent();
12041     }
12042   }
12043 
12044   if (Previous.isSingleResult() &&
12045       Previous.getFoundDecl()->isTemplateParameter()) {
12046     // Maybe we will complain about the shadowed template parameter.
12047     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12048     // Just pretend that we didn't see the previous declaration.
12049     Previous.clear();
12050   }
12051 
12052   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12053       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12054     // This is a declaration of or a reference to "std::bad_alloc".
12055     isStdBadAlloc = true;
12056 
12057     if (Previous.empty() && StdBadAlloc) {
12058       // std::bad_alloc has been implicitly declared (but made invisible to
12059       // name lookup). Fill in this implicit declaration as the previous
12060       // declaration, so that the declarations get chained appropriately.
12061       Previous.addDecl(getStdBadAlloc());
12062     }
12063   }
12064 
12065   // If we didn't find a previous declaration, and this is a reference
12066   // (or friend reference), move to the correct scope.  In C++, we
12067   // also need to do a redeclaration lookup there, just in case
12068   // there's a shadow friend decl.
12069   if (Name && Previous.empty() &&
12070       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12071     if (Invalid) goto CreateNewDecl;
12072     assert(SS.isEmpty());
12073 
12074     if (TUK == TUK_Reference) {
12075       // C++ [basic.scope.pdecl]p5:
12076       //   -- for an elaborated-type-specifier of the form
12077       //
12078       //          class-key identifier
12079       //
12080       //      if the elaborated-type-specifier is used in the
12081       //      decl-specifier-seq or parameter-declaration-clause of a
12082       //      function defined in namespace scope, the identifier is
12083       //      declared as a class-name in the namespace that contains
12084       //      the declaration; otherwise, except as a friend
12085       //      declaration, the identifier is declared in the smallest
12086       //      non-class, non-function-prototype scope that contains the
12087       //      declaration.
12088       //
12089       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12090       // C structs and unions.
12091       //
12092       // It is an error in C++ to declare (rather than define) an enum
12093       // type, including via an elaborated type specifier.  We'll
12094       // diagnose that later; for now, declare the enum in the same
12095       // scope as we would have picked for any other tag type.
12096       //
12097       // GNU C also supports this behavior as part of its incomplete
12098       // enum types extension, while GNU C++ does not.
12099       //
12100       // Find the context where we'll be declaring the tag.
12101       // FIXME: We would like to maintain the current DeclContext as the
12102       // lexical context,
12103       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
12104         SearchDC = SearchDC->getParent();
12105 
12106       // Find the scope where we'll be declaring the tag.
12107       while (S->isClassScope() ||
12108              (getLangOpts().CPlusPlus &&
12109               S->isFunctionPrototypeScope()) ||
12110              ((S->getFlags() & Scope::DeclScope) == 0) ||
12111              (S->getEntity() && S->getEntity()->isTransparentContext()))
12112         S = S->getParent();
12113     } else {
12114       assert(TUK == TUK_Friend);
12115       // C++ [namespace.memdef]p3:
12116       //   If a friend declaration in a non-local class first declares a
12117       //   class or function, the friend class or function is a member of
12118       //   the innermost enclosing namespace.
12119       SearchDC = SearchDC->getEnclosingNamespaceContext();
12120     }
12121 
12122     // In C++, we need to do a redeclaration lookup to properly
12123     // diagnose some problems.
12124     if (getLangOpts().CPlusPlus) {
12125       Previous.setRedeclarationKind(ForRedeclaration);
12126       LookupQualifiedName(Previous, SearchDC);
12127     }
12128   }
12129 
12130   // If we have a known previous declaration to use, then use it.
12131   if (Previous.empty() && SkipBody && SkipBody->Previous)
12132     Previous.addDecl(SkipBody->Previous);
12133 
12134   if (!Previous.empty()) {
12135     NamedDecl *PrevDecl = Previous.getFoundDecl();
12136     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12137 
12138     // It's okay to have a tag decl in the same scope as a typedef
12139     // which hides a tag decl in the same scope.  Finding this
12140     // insanity with a redeclaration lookup can only actually happen
12141     // in C++.
12142     //
12143     // This is also okay for elaborated-type-specifiers, which is
12144     // technically forbidden by the current standard but which is
12145     // okay according to the likely resolution of an open issue;
12146     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12147     if (getLangOpts().CPlusPlus) {
12148       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12149         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12150           TagDecl *Tag = TT->getDecl();
12151           if (Tag->getDeclName() == Name &&
12152               Tag->getDeclContext()->getRedeclContext()
12153                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12154             PrevDecl = Tag;
12155             Previous.clear();
12156             Previous.addDecl(Tag);
12157             Previous.resolveKind();
12158           }
12159         }
12160       }
12161     }
12162 
12163     // If this is a redeclaration of a using shadow declaration, it must
12164     // declare a tag in the same context. In MSVC mode, we allow a
12165     // redefinition if either context is within the other.
12166     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12167       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12168       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12169           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12170           !(OldTag && isAcceptableTagRedeclContext(
12171                           *this, OldTag->getDeclContext(), SearchDC))) {
12172         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12173         Diag(Shadow->getTargetDecl()->getLocation(),
12174              diag::note_using_decl_target);
12175         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12176             << 0;
12177         // Recover by ignoring the old declaration.
12178         Previous.clear();
12179         goto CreateNewDecl;
12180       }
12181     }
12182 
12183     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12184       // If this is a use of a previous tag, or if the tag is already declared
12185       // in the same scope (so that the definition/declaration completes or
12186       // rementions the tag), reuse the decl.
12187       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12188           isDeclInScope(DirectPrevDecl, SearchDC, S,
12189                         SS.isNotEmpty() || isExplicitSpecialization)) {
12190         // Make sure that this wasn't declared as an enum and now used as a
12191         // struct or something similar.
12192         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12193                                           TUK == TUK_Definition, KWLoc,
12194                                           Name)) {
12195           bool SafeToContinue
12196             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12197                Kind != TTK_Enum);
12198           if (SafeToContinue)
12199             Diag(KWLoc, diag::err_use_with_wrong_tag)
12200               << Name
12201               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12202                                               PrevTagDecl->getKindName());
12203           else
12204             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12205           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12206 
12207           if (SafeToContinue)
12208             Kind = PrevTagDecl->getTagKind();
12209           else {
12210             // Recover by making this an anonymous redefinition.
12211             Name = nullptr;
12212             Previous.clear();
12213             Invalid = true;
12214           }
12215         }
12216 
12217         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12218           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12219 
12220           // If this is an elaborated-type-specifier for a scoped enumeration,
12221           // the 'class' keyword is not necessary and not permitted.
12222           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12223             if (ScopedEnum)
12224               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12225                 << PrevEnum->isScoped()
12226                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12227             return PrevTagDecl;
12228           }
12229 
12230           QualType EnumUnderlyingTy;
12231           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12232             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12233           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12234             EnumUnderlyingTy = QualType(T, 0);
12235 
12236           // All conflicts with previous declarations are recovered by
12237           // returning the previous declaration, unless this is a definition,
12238           // in which case we want the caller to bail out.
12239           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12240                                      ScopedEnum, EnumUnderlyingTy,
12241                                      EnumUnderlyingIsImplicit, PrevEnum))
12242             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12243         }
12244 
12245         // C++11 [class.mem]p1:
12246         //   A member shall not be declared twice in the member-specification,
12247         //   except that a nested class or member class template can be declared
12248         //   and then later defined.
12249         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12250             S->isDeclScope(PrevDecl)) {
12251           Diag(NameLoc, diag::ext_member_redeclared);
12252           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12253         }
12254 
12255         if (!Invalid) {
12256           // If this is a use, just return the declaration we found, unless
12257           // we have attributes.
12258 
12259           // FIXME: In the future, return a variant or some other clue
12260           // for the consumer of this Decl to know it doesn't own it.
12261           // For our current ASTs this shouldn't be a problem, but will
12262           // need to be changed with DeclGroups.
12263           if (!Attr &&
12264               ((TUK == TUK_Reference &&
12265                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
12266                || TUK == TUK_Friend))
12267             return PrevTagDecl;
12268 
12269           // Diagnose attempts to redefine a tag.
12270           if (TUK == TUK_Definition) {
12271             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12272               // If we're defining a specialization and the previous definition
12273               // is from an implicit instantiation, don't emit an error
12274               // here; we'll catch this in the general case below.
12275               bool IsExplicitSpecializationAfterInstantiation = false;
12276               if (isExplicitSpecialization) {
12277                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12278                   IsExplicitSpecializationAfterInstantiation =
12279                     RD->getTemplateSpecializationKind() !=
12280                     TSK_ExplicitSpecialization;
12281                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12282                   IsExplicitSpecializationAfterInstantiation =
12283                     ED->getTemplateSpecializationKind() !=
12284                     TSK_ExplicitSpecialization;
12285               }
12286 
12287               NamedDecl *Hidden = nullptr;
12288               if (SkipBody && getLangOpts().CPlusPlus &&
12289                   !hasVisibleDefinition(Def, &Hidden)) {
12290                 // There is a definition of this tag, but it is not visible. We
12291                 // explicitly make use of C++'s one definition rule here, and
12292                 // assume that this definition is identical to the hidden one
12293                 // we already have. Make the existing definition visible and
12294                 // use it in place of this one.
12295                 SkipBody->ShouldSkip = true;
12296                 makeMergedDefinitionVisible(Hidden, KWLoc);
12297                 return Def;
12298               } else if (!IsExplicitSpecializationAfterInstantiation) {
12299                 // A redeclaration in function prototype scope in C isn't
12300                 // visible elsewhere, so merely issue a warning.
12301                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12302                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12303                 else
12304                   Diag(NameLoc, diag::err_redefinition) << Name;
12305                 Diag(Def->getLocation(), diag::note_previous_definition);
12306                 // If this is a redefinition, recover by making this
12307                 // struct be anonymous, which will make any later
12308                 // references get the previous definition.
12309                 Name = nullptr;
12310                 Previous.clear();
12311                 Invalid = true;
12312               }
12313             } else {
12314               // If the type is currently being defined, complain
12315               // about a nested redefinition.
12316               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12317               if (TD->isBeingDefined()) {
12318                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12319                 Diag(PrevTagDecl->getLocation(),
12320                      diag::note_previous_definition);
12321                 Name = nullptr;
12322                 Previous.clear();
12323                 Invalid = true;
12324               }
12325             }
12326 
12327             // Okay, this is definition of a previously declared or referenced
12328             // tag. We're going to create a new Decl for it.
12329           }
12330 
12331           // Okay, we're going to make a redeclaration.  If this is some kind
12332           // of reference, make sure we build the redeclaration in the same DC
12333           // as the original, and ignore the current access specifier.
12334           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12335             SearchDC = PrevTagDecl->getDeclContext();
12336             AS = AS_none;
12337           }
12338         }
12339         // If we get here we have (another) forward declaration or we
12340         // have a definition.  Just create a new decl.
12341 
12342       } else {
12343         // If we get here, this is a definition of a new tag type in a nested
12344         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12345         // new decl/type.  We set PrevDecl to NULL so that the entities
12346         // have distinct types.
12347         Previous.clear();
12348       }
12349       // If we get here, we're going to create a new Decl. If PrevDecl
12350       // is non-NULL, it's a definition of the tag declared by
12351       // PrevDecl. If it's NULL, we have a new definition.
12352 
12353 
12354     // Otherwise, PrevDecl is not a tag, but was found with tag
12355     // lookup.  This is only actually possible in C++, where a few
12356     // things like templates still live in the tag namespace.
12357     } else {
12358       // Use a better diagnostic if an elaborated-type-specifier
12359       // found the wrong kind of type on the first
12360       // (non-redeclaration) lookup.
12361       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12362           !Previous.isForRedeclaration()) {
12363         unsigned Kind = 0;
12364         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12365         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12366         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12367         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12368         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12369         Invalid = true;
12370 
12371       // Otherwise, only diagnose if the declaration is in scope.
12372       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12373                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12374         // do nothing
12375 
12376       // Diagnose implicit declarations introduced by elaborated types.
12377       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12378         unsigned Kind = 0;
12379         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12380         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12381         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12382         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12383         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12384         Invalid = true;
12385 
12386       // Otherwise it's a declaration.  Call out a particularly common
12387       // case here.
12388       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12389         unsigned Kind = 0;
12390         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12391         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12392           << Name << Kind << TND->getUnderlyingType();
12393         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12394         Invalid = true;
12395 
12396       // Otherwise, diagnose.
12397       } else {
12398         // The tag name clashes with something else in the target scope,
12399         // issue an error and recover by making this tag be anonymous.
12400         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12401         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12402         Name = nullptr;
12403         Invalid = true;
12404       }
12405 
12406       // The existing declaration isn't relevant to us; we're in a
12407       // new scope, so clear out the previous declaration.
12408       Previous.clear();
12409     }
12410   }
12411 
12412 CreateNewDecl:
12413 
12414   TagDecl *PrevDecl = nullptr;
12415   if (Previous.isSingleResult())
12416     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12417 
12418   // If there is an identifier, use the location of the identifier as the
12419   // location of the decl, otherwise use the location of the struct/union
12420   // keyword.
12421   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12422 
12423   // Otherwise, create a new declaration. If there is a previous
12424   // declaration of the same entity, the two will be linked via
12425   // PrevDecl.
12426   TagDecl *New;
12427 
12428   bool IsForwardReference = false;
12429   if (Kind == TTK_Enum) {
12430     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12431     // enum X { A, B, C } D;    D should chain to X.
12432     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12433                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12434                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12435     // If this is an undefined enum, warn.
12436     if (TUK != TUK_Definition && !Invalid) {
12437       TagDecl *Def;
12438       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12439           cast<EnumDecl>(New)->isFixed()) {
12440         // C++0x: 7.2p2: opaque-enum-declaration.
12441         // Conflicts are diagnosed above. Do nothing.
12442       }
12443       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12444         Diag(Loc, diag::ext_forward_ref_enum_def)
12445           << New;
12446         Diag(Def->getLocation(), diag::note_previous_definition);
12447       } else {
12448         unsigned DiagID = diag::ext_forward_ref_enum;
12449         if (getLangOpts().MSVCCompat)
12450           DiagID = diag::ext_ms_forward_ref_enum;
12451         else if (getLangOpts().CPlusPlus)
12452           DiagID = diag::err_forward_ref_enum;
12453         Diag(Loc, DiagID);
12454 
12455         // If this is a forward-declared reference to an enumeration, make a
12456         // note of it; we won't actually be introducing the declaration into
12457         // the declaration context.
12458         if (TUK == TUK_Reference)
12459           IsForwardReference = true;
12460       }
12461     }
12462 
12463     if (EnumUnderlying) {
12464       EnumDecl *ED = cast<EnumDecl>(New);
12465       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12466         ED->setIntegerTypeSourceInfo(TI);
12467       else
12468         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12469       ED->setPromotionType(ED->getIntegerType());
12470     }
12471 
12472   } else {
12473     // struct/union/class
12474 
12475     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12476     // struct X { int A; } D;    D should chain to X.
12477     if (getLangOpts().CPlusPlus) {
12478       // FIXME: Look for a way to use RecordDecl for simple structs.
12479       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12480                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12481 
12482       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12483         StdBadAlloc = cast<CXXRecordDecl>(New);
12484     } else
12485       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12486                                cast_or_null<RecordDecl>(PrevDecl));
12487   }
12488 
12489   // C++11 [dcl.type]p3:
12490   //   A type-specifier-seq shall not define a class or enumeration [...].
12491   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12492     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12493       << Context.getTagDeclType(New);
12494     Invalid = true;
12495   }
12496 
12497   // Maybe add qualifier info.
12498   if (SS.isNotEmpty()) {
12499     if (SS.isSet()) {
12500       // If this is either a declaration or a definition, check the
12501       // nested-name-specifier against the current context. We don't do this
12502       // for explicit specializations, because they have similar checking
12503       // (with more specific diagnostics) in the call to
12504       // CheckMemberSpecialization, below.
12505       if (!isExplicitSpecialization &&
12506           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12507           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12508         Invalid = true;
12509 
12510       New->setQualifierInfo(SS.getWithLocInContext(Context));
12511       if (TemplateParameterLists.size() > 0) {
12512         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12513       }
12514     }
12515     else
12516       Invalid = true;
12517   }
12518 
12519   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12520     // Add alignment attributes if necessary; these attributes are checked when
12521     // the ASTContext lays out the structure.
12522     //
12523     // It is important for implementing the correct semantics that this
12524     // happen here (in act on tag decl). The #pragma pack stack is
12525     // maintained as a result of parser callbacks which can occur at
12526     // many points during the parsing of a struct declaration (because
12527     // the #pragma tokens are effectively skipped over during the
12528     // parsing of the struct).
12529     if (TUK == TUK_Definition) {
12530       AddAlignmentAttributesForRecord(RD);
12531       AddMsStructLayoutForRecord(RD);
12532     }
12533   }
12534 
12535   if (ModulePrivateLoc.isValid()) {
12536     if (isExplicitSpecialization)
12537       Diag(New->getLocation(), diag::err_module_private_specialization)
12538         << 2
12539         << FixItHint::CreateRemoval(ModulePrivateLoc);
12540     // __module_private__ does not apply to local classes. However, we only
12541     // diagnose this as an error when the declaration specifiers are
12542     // freestanding. Here, we just ignore the __module_private__.
12543     else if (!SearchDC->isFunctionOrMethod())
12544       New->setModulePrivate();
12545   }
12546 
12547   // If this is a specialization of a member class (of a class template),
12548   // check the specialization.
12549   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12550     Invalid = true;
12551 
12552   // If we're declaring or defining a tag in function prototype scope in C,
12553   // note that this type can only be used within the function and add it to
12554   // the list of decls to inject into the function definition scope.
12555   if ((Name || Kind == TTK_Enum) &&
12556       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12557     if (getLangOpts().CPlusPlus) {
12558       // C++ [dcl.fct]p6:
12559       //   Types shall not be defined in return or parameter types.
12560       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12561         Diag(Loc, diag::err_type_defined_in_param_type)
12562             << Name;
12563         Invalid = true;
12564       }
12565     } else {
12566       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12567     }
12568     DeclsInPrototypeScope.push_back(New);
12569   }
12570 
12571   if (Invalid)
12572     New->setInvalidDecl();
12573 
12574   if (Attr)
12575     ProcessDeclAttributeList(S, New, Attr);
12576 
12577   // Set the lexical context. If the tag has a C++ scope specifier, the
12578   // lexical context will be different from the semantic context.
12579   New->setLexicalDeclContext(CurContext);
12580 
12581   // Mark this as a friend decl if applicable.
12582   // In Microsoft mode, a friend declaration also acts as a forward
12583   // declaration so we always pass true to setObjectOfFriendDecl to make
12584   // the tag name visible.
12585   if (TUK == TUK_Friend)
12586     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12587 
12588   // Set the access specifier.
12589   if (!Invalid && SearchDC->isRecord())
12590     SetMemberAccessSpecifier(New, PrevDecl, AS);
12591 
12592   if (TUK == TUK_Definition)
12593     New->startDefinition();
12594 
12595   // If this has an identifier, add it to the scope stack.
12596   if (TUK == TUK_Friend) {
12597     // We might be replacing an existing declaration in the lookup tables;
12598     // if so, borrow its access specifier.
12599     if (PrevDecl)
12600       New->setAccess(PrevDecl->getAccess());
12601 
12602     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12603     DC->makeDeclVisibleInContext(New);
12604     if (Name) // can be null along some error paths
12605       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12606         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12607   } else if (Name) {
12608     S = getNonFieldDeclScope(S);
12609     PushOnScopeChains(New, S, !IsForwardReference);
12610     if (IsForwardReference)
12611       SearchDC->makeDeclVisibleInContext(New);
12612 
12613   } else {
12614     CurContext->addDecl(New);
12615   }
12616 
12617   // If this is the C FILE type, notify the AST context.
12618   if (IdentifierInfo *II = New->getIdentifier())
12619     if (!New->isInvalidDecl() &&
12620         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12621         II->isStr("FILE"))
12622       Context.setFILEDecl(New);
12623 
12624   if (PrevDecl)
12625     mergeDeclAttributes(New, PrevDecl);
12626 
12627   // If there's a #pragma GCC visibility in scope, set the visibility of this
12628   // record.
12629   AddPushedVisibilityAttribute(New);
12630 
12631   OwnedDecl = true;
12632   // In C++, don't return an invalid declaration. We can't recover well from
12633   // the cases where we make the type anonymous.
12634   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12635 }
12636 
12637 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12638   AdjustDeclIfTemplate(TagD);
12639   TagDecl *Tag = cast<TagDecl>(TagD);
12640 
12641   // Enter the tag context.
12642   PushDeclContext(S, Tag);
12643 
12644   ActOnDocumentableDecl(TagD);
12645 
12646   // If there's a #pragma GCC visibility in scope, set the visibility of this
12647   // record.
12648   AddPushedVisibilityAttribute(Tag);
12649 }
12650 
12651 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12652   assert(isa<ObjCContainerDecl>(IDecl) &&
12653          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12654   DeclContext *OCD = cast<DeclContext>(IDecl);
12655   assert(getContainingDC(OCD) == CurContext &&
12656       "The next DeclContext should be lexically contained in the current one.");
12657   CurContext = OCD;
12658   return IDecl;
12659 }
12660 
12661 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12662                                            SourceLocation FinalLoc,
12663                                            bool IsFinalSpelledSealed,
12664                                            SourceLocation LBraceLoc) {
12665   AdjustDeclIfTemplate(TagD);
12666   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12667 
12668   FieldCollector->StartClass();
12669 
12670   if (!Record->getIdentifier())
12671     return;
12672 
12673   if (FinalLoc.isValid())
12674     Record->addAttr(new (Context)
12675                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12676 
12677   // C++ [class]p2:
12678   //   [...] The class-name is also inserted into the scope of the
12679   //   class itself; this is known as the injected-class-name. For
12680   //   purposes of access checking, the injected-class-name is treated
12681   //   as if it were a public member name.
12682   CXXRecordDecl *InjectedClassName
12683     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12684                             Record->getLocStart(), Record->getLocation(),
12685                             Record->getIdentifier(),
12686                             /*PrevDecl=*/nullptr,
12687                             /*DelayTypeCreation=*/true);
12688   Context.getTypeDeclType(InjectedClassName, Record);
12689   InjectedClassName->setImplicit();
12690   InjectedClassName->setAccess(AS_public);
12691   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12692       InjectedClassName->setDescribedClassTemplate(Template);
12693   PushOnScopeChains(InjectedClassName, S);
12694   assert(InjectedClassName->isInjectedClassName() &&
12695          "Broken injected-class-name");
12696 }
12697 
12698 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12699                                     SourceLocation RBraceLoc) {
12700   AdjustDeclIfTemplate(TagD);
12701   TagDecl *Tag = cast<TagDecl>(TagD);
12702   Tag->setRBraceLoc(RBraceLoc);
12703 
12704   // Make sure we "complete" the definition even it is invalid.
12705   if (Tag->isBeingDefined()) {
12706     assert(Tag->isInvalidDecl() && "We should already have completed it");
12707     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12708       RD->completeDefinition();
12709   }
12710 
12711   if (isa<CXXRecordDecl>(Tag))
12712     FieldCollector->FinishClass();
12713 
12714   // Exit this scope of this tag's definition.
12715   PopDeclContext();
12716 
12717   if (getCurLexicalContext()->isObjCContainer() &&
12718       Tag->getDeclContext()->isFileContext())
12719     Tag->setTopLevelDeclInObjCContainer();
12720 
12721   // Notify the consumer that we've defined a tag.
12722   if (!Tag->isInvalidDecl())
12723     Consumer.HandleTagDeclDefinition(Tag);
12724 }
12725 
12726 void Sema::ActOnObjCContainerFinishDefinition() {
12727   // Exit this scope of this interface definition.
12728   PopDeclContext();
12729 }
12730 
12731 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12732   assert(DC == CurContext && "Mismatch of container contexts");
12733   OriginalLexicalContext = DC;
12734   ActOnObjCContainerFinishDefinition();
12735 }
12736 
12737 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12738   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12739   OriginalLexicalContext = nullptr;
12740 }
12741 
12742 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12743   AdjustDeclIfTemplate(TagD);
12744   TagDecl *Tag = cast<TagDecl>(TagD);
12745   Tag->setInvalidDecl();
12746 
12747   // Make sure we "complete" the definition even it is invalid.
12748   if (Tag->isBeingDefined()) {
12749     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12750       RD->completeDefinition();
12751   }
12752 
12753   // We're undoing ActOnTagStartDefinition here, not
12754   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12755   // the FieldCollector.
12756 
12757   PopDeclContext();
12758 }
12759 
12760 // Note that FieldName may be null for anonymous bitfields.
12761 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12762                                 IdentifierInfo *FieldName,
12763                                 QualType FieldTy, bool IsMsStruct,
12764                                 Expr *BitWidth, bool *ZeroWidth) {
12765   // Default to true; that shouldn't confuse checks for emptiness
12766   if (ZeroWidth)
12767     *ZeroWidth = true;
12768 
12769   // C99 6.7.2.1p4 - verify the field type.
12770   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12771   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12772     // Handle incomplete types with specific error.
12773     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12774       return ExprError();
12775     if (FieldName)
12776       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12777         << FieldName << FieldTy << BitWidth->getSourceRange();
12778     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12779       << FieldTy << BitWidth->getSourceRange();
12780   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12781                                              UPPC_BitFieldWidth))
12782     return ExprError();
12783 
12784   // If the bit-width is type- or value-dependent, don't try to check
12785   // it now.
12786   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12787     return BitWidth;
12788 
12789   llvm::APSInt Value;
12790   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12791   if (ICE.isInvalid())
12792     return ICE;
12793   BitWidth = ICE.get();
12794 
12795   if (Value != 0 && ZeroWidth)
12796     *ZeroWidth = false;
12797 
12798   // Zero-width bitfield is ok for anonymous field.
12799   if (Value == 0 && FieldName)
12800     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12801 
12802   if (Value.isSigned() && Value.isNegative()) {
12803     if (FieldName)
12804       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12805                << FieldName << Value.toString(10);
12806     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12807       << Value.toString(10);
12808   }
12809 
12810   if (!FieldTy->isDependentType()) {
12811     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12812     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12813     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12814 
12815     // Over-wide bitfields are an error in C or when using the MSVC bitfield
12816     // ABI.
12817     bool CStdConstraintViolation =
12818         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12819     bool MSBitfieldViolation =
12820         Value.ugt(TypeStorageSize) &&
12821         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12822     if (CStdConstraintViolation || MSBitfieldViolation) {
12823       unsigned DiagWidth =
12824           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12825       if (FieldName)
12826         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12827                << FieldName << (unsigned)Value.getZExtValue()
12828                << !CStdConstraintViolation << DiagWidth;
12829 
12830       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12831              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12832              << DiagWidth;
12833     }
12834 
12835     // Warn on types where the user might conceivably expect to get all
12836     // specified bits as value bits: that's all integral types other than
12837     // 'bool'.
12838     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12839       if (FieldName)
12840         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12841             << FieldName << (unsigned)Value.getZExtValue()
12842             << (unsigned)TypeWidth;
12843       else
12844         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12845             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12846     }
12847   }
12848 
12849   return BitWidth;
12850 }
12851 
12852 /// ActOnField - Each field of a C struct/union is passed into this in order
12853 /// to create a FieldDecl object for it.
12854 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12855                        Declarator &D, Expr *BitfieldWidth) {
12856   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12857                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12858                                /*InitStyle=*/ICIS_NoInit, AS_public);
12859   return Res;
12860 }
12861 
12862 /// HandleField - Analyze a field of a C struct or a C++ data member.
12863 ///
12864 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12865                              SourceLocation DeclStart,
12866                              Declarator &D, Expr *BitWidth,
12867                              InClassInitStyle InitStyle,
12868                              AccessSpecifier AS) {
12869   IdentifierInfo *II = D.getIdentifier();
12870   SourceLocation Loc = DeclStart;
12871   if (II) Loc = D.getIdentifierLoc();
12872 
12873   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12874   QualType T = TInfo->getType();
12875   if (getLangOpts().CPlusPlus) {
12876     CheckExtraCXXDefaultArguments(D);
12877 
12878     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12879                                         UPPC_DataMemberType)) {
12880       D.setInvalidType();
12881       T = Context.IntTy;
12882       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12883     }
12884   }
12885 
12886   // TR 18037 does not allow fields to be declared with address spaces.
12887   if (T.getQualifiers().hasAddressSpace()) {
12888     Diag(Loc, diag::err_field_with_address_space);
12889     D.setInvalidType();
12890   }
12891 
12892   // OpenCL 1.2 spec, s6.9 r:
12893   // The event type cannot be used to declare a structure or union field.
12894   if (LangOpts.OpenCL && T->isEventT()) {
12895     Diag(Loc, diag::err_event_t_struct_field);
12896     D.setInvalidType();
12897   }
12898 
12899   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12900 
12901   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12902     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12903          diag::err_invalid_thread)
12904       << DeclSpec::getSpecifierName(TSCS);
12905 
12906   // Check to see if this name was declared as a member previously
12907   NamedDecl *PrevDecl = nullptr;
12908   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12909   LookupName(Previous, S);
12910   switch (Previous.getResultKind()) {
12911     case LookupResult::Found:
12912     case LookupResult::FoundUnresolvedValue:
12913       PrevDecl = Previous.getAsSingle<NamedDecl>();
12914       break;
12915 
12916     case LookupResult::FoundOverloaded:
12917       PrevDecl = Previous.getRepresentativeDecl();
12918       break;
12919 
12920     case LookupResult::NotFound:
12921     case LookupResult::NotFoundInCurrentInstantiation:
12922     case LookupResult::Ambiguous:
12923       break;
12924   }
12925   Previous.suppressDiagnostics();
12926 
12927   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12928     // Maybe we will complain about the shadowed template parameter.
12929     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12930     // Just pretend that we didn't see the previous declaration.
12931     PrevDecl = nullptr;
12932   }
12933 
12934   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12935     PrevDecl = nullptr;
12936 
12937   bool Mutable
12938     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12939   SourceLocation TSSL = D.getLocStart();
12940   FieldDecl *NewFD
12941     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12942                      TSSL, AS, PrevDecl, &D);
12943 
12944   if (NewFD->isInvalidDecl())
12945     Record->setInvalidDecl();
12946 
12947   if (D.getDeclSpec().isModulePrivateSpecified())
12948     NewFD->setModulePrivate();
12949 
12950   if (NewFD->isInvalidDecl() && PrevDecl) {
12951     // Don't introduce NewFD into scope; there's already something
12952     // with the same name in the same scope.
12953   } else if (II) {
12954     PushOnScopeChains(NewFD, S);
12955   } else
12956     Record->addDecl(NewFD);
12957 
12958   return NewFD;
12959 }
12960 
12961 /// \brief Build a new FieldDecl and check its well-formedness.
12962 ///
12963 /// This routine builds a new FieldDecl given the fields name, type,
12964 /// record, etc. \p PrevDecl should refer to any previous declaration
12965 /// with the same name and in the same scope as the field to be
12966 /// created.
12967 ///
12968 /// \returns a new FieldDecl.
12969 ///
12970 /// \todo The Declarator argument is a hack. It will be removed once
12971 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12972                                 TypeSourceInfo *TInfo,
12973                                 RecordDecl *Record, SourceLocation Loc,
12974                                 bool Mutable, Expr *BitWidth,
12975                                 InClassInitStyle InitStyle,
12976                                 SourceLocation TSSL,
12977                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12978                                 Declarator *D) {
12979   IdentifierInfo *II = Name.getAsIdentifierInfo();
12980   bool InvalidDecl = false;
12981   if (D) InvalidDecl = D->isInvalidType();
12982 
12983   // If we receive a broken type, recover by assuming 'int' and
12984   // marking this declaration as invalid.
12985   if (T.isNull()) {
12986     InvalidDecl = true;
12987     T = Context.IntTy;
12988   }
12989 
12990   QualType EltTy = Context.getBaseElementType(T);
12991   if (!EltTy->isDependentType()) {
12992     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12993       // Fields of incomplete type force their record to be invalid.
12994       Record->setInvalidDecl();
12995       InvalidDecl = true;
12996     } else {
12997       NamedDecl *Def;
12998       EltTy->isIncompleteType(&Def);
12999       if (Def && Def->isInvalidDecl()) {
13000         Record->setInvalidDecl();
13001         InvalidDecl = true;
13002       }
13003     }
13004   }
13005 
13006   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13007   if (BitWidth && getLangOpts().OpenCL) {
13008     Diag(Loc, diag::err_opencl_bitfields);
13009     InvalidDecl = true;
13010   }
13011 
13012   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13013   // than a variably modified type.
13014   if (!InvalidDecl && T->isVariablyModifiedType()) {
13015     bool SizeIsNegative;
13016     llvm::APSInt Oversized;
13017 
13018     TypeSourceInfo *FixedTInfo =
13019       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13020                                                     SizeIsNegative,
13021                                                     Oversized);
13022     if (FixedTInfo) {
13023       Diag(Loc, diag::warn_illegal_constant_array_size);
13024       TInfo = FixedTInfo;
13025       T = FixedTInfo->getType();
13026     } else {
13027       if (SizeIsNegative)
13028         Diag(Loc, diag::err_typecheck_negative_array_size);
13029       else if (Oversized.getBoolValue())
13030         Diag(Loc, diag::err_array_too_large)
13031           << Oversized.toString(10);
13032       else
13033         Diag(Loc, diag::err_typecheck_field_variable_size);
13034       InvalidDecl = true;
13035     }
13036   }
13037 
13038   // Fields can not have abstract class types
13039   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13040                                              diag::err_abstract_type_in_decl,
13041                                              AbstractFieldType))
13042     InvalidDecl = true;
13043 
13044   bool ZeroWidth = false;
13045   if (InvalidDecl)
13046     BitWidth = nullptr;
13047   // If this is declared as a bit-field, check the bit-field.
13048   if (BitWidth) {
13049     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13050                               &ZeroWidth).get();
13051     if (!BitWidth) {
13052       InvalidDecl = true;
13053       BitWidth = nullptr;
13054       ZeroWidth = false;
13055     }
13056   }
13057 
13058   // Check that 'mutable' is consistent with the type of the declaration.
13059   if (!InvalidDecl && Mutable) {
13060     unsigned DiagID = 0;
13061     if (T->isReferenceType())
13062       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13063                                         : diag::err_mutable_reference;
13064     else if (T.isConstQualified())
13065       DiagID = diag::err_mutable_const;
13066 
13067     if (DiagID) {
13068       SourceLocation ErrLoc = Loc;
13069       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13070         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13071       Diag(ErrLoc, DiagID);
13072       if (DiagID != diag::ext_mutable_reference) {
13073         Mutable = false;
13074         InvalidDecl = true;
13075       }
13076     }
13077   }
13078 
13079   // C++11 [class.union]p8 (DR1460):
13080   //   At most one variant member of a union may have a
13081   //   brace-or-equal-initializer.
13082   if (InitStyle != ICIS_NoInit)
13083     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13084 
13085   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13086                                        BitWidth, Mutable, InitStyle);
13087   if (InvalidDecl)
13088     NewFD->setInvalidDecl();
13089 
13090   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13091     Diag(Loc, diag::err_duplicate_member) << II;
13092     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13093     NewFD->setInvalidDecl();
13094   }
13095 
13096   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13097     if (Record->isUnion()) {
13098       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13099         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13100         if (RDecl->getDefinition()) {
13101           // C++ [class.union]p1: An object of a class with a non-trivial
13102           // constructor, a non-trivial copy constructor, a non-trivial
13103           // destructor, or a non-trivial copy assignment operator
13104           // cannot be a member of a union, nor can an array of such
13105           // objects.
13106           if (CheckNontrivialField(NewFD))
13107             NewFD->setInvalidDecl();
13108         }
13109       }
13110 
13111       // C++ [class.union]p1: If a union contains a member of reference type,
13112       // the program is ill-formed, except when compiling with MSVC extensions
13113       // enabled.
13114       if (EltTy->isReferenceType()) {
13115         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13116                                     diag::ext_union_member_of_reference_type :
13117                                     diag::err_union_member_of_reference_type)
13118           << NewFD->getDeclName() << EltTy;
13119         if (!getLangOpts().MicrosoftExt)
13120           NewFD->setInvalidDecl();
13121       }
13122     }
13123   }
13124 
13125   // FIXME: We need to pass in the attributes given an AST
13126   // representation, not a parser representation.
13127   if (D) {
13128     // FIXME: The current scope is almost... but not entirely... correct here.
13129     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13130 
13131     if (NewFD->hasAttrs())
13132       CheckAlignasUnderalignment(NewFD);
13133   }
13134 
13135   // In auto-retain/release, infer strong retension for fields of
13136   // retainable type.
13137   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13138     NewFD->setInvalidDecl();
13139 
13140   if (T.isObjCGCWeak())
13141     Diag(Loc, diag::warn_attribute_weak_on_field);
13142 
13143   NewFD->setAccess(AS);
13144   return NewFD;
13145 }
13146 
13147 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13148   assert(FD);
13149   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13150 
13151   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13152     return false;
13153 
13154   QualType EltTy = Context.getBaseElementType(FD->getType());
13155   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13156     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13157     if (RDecl->getDefinition()) {
13158       // We check for copy constructors before constructors
13159       // because otherwise we'll never get complaints about
13160       // copy constructors.
13161 
13162       CXXSpecialMember member = CXXInvalid;
13163       // We're required to check for any non-trivial constructors. Since the
13164       // implicit default constructor is suppressed if there are any
13165       // user-declared constructors, we just need to check that there is a
13166       // trivial default constructor and a trivial copy constructor. (We don't
13167       // worry about move constructors here, since this is a C++98 check.)
13168       if (RDecl->hasNonTrivialCopyConstructor())
13169         member = CXXCopyConstructor;
13170       else if (!RDecl->hasTrivialDefaultConstructor())
13171         member = CXXDefaultConstructor;
13172       else if (RDecl->hasNonTrivialCopyAssignment())
13173         member = CXXCopyAssignment;
13174       else if (RDecl->hasNonTrivialDestructor())
13175         member = CXXDestructor;
13176 
13177       if (member != CXXInvalid) {
13178         if (!getLangOpts().CPlusPlus11 &&
13179             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13180           // Objective-C++ ARC: it is an error to have a non-trivial field of
13181           // a union. However, system headers in Objective-C programs
13182           // occasionally have Objective-C lifetime objects within unions,
13183           // and rather than cause the program to fail, we make those
13184           // members unavailable.
13185           SourceLocation Loc = FD->getLocation();
13186           if (getSourceManager().isInSystemHeader(Loc)) {
13187             if (!FD->hasAttr<UnavailableAttr>())
13188               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13189                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13190             return false;
13191           }
13192         }
13193 
13194         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13195                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13196                diag::err_illegal_union_or_anon_struct_member)
13197           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13198         DiagnoseNontrivial(RDecl, member);
13199         return !getLangOpts().CPlusPlus11;
13200       }
13201     }
13202   }
13203 
13204   return false;
13205 }
13206 
13207 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13208 ///  AST enum value.
13209 static ObjCIvarDecl::AccessControl
13210 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13211   switch (ivarVisibility) {
13212   default: llvm_unreachable("Unknown visitibility kind");
13213   case tok::objc_private: return ObjCIvarDecl::Private;
13214   case tok::objc_public: return ObjCIvarDecl::Public;
13215   case tok::objc_protected: return ObjCIvarDecl::Protected;
13216   case tok::objc_package: return ObjCIvarDecl::Package;
13217   }
13218 }
13219 
13220 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13221 /// in order to create an IvarDecl object for it.
13222 Decl *Sema::ActOnIvar(Scope *S,
13223                                 SourceLocation DeclStart,
13224                                 Declarator &D, Expr *BitfieldWidth,
13225                                 tok::ObjCKeywordKind Visibility) {
13226 
13227   IdentifierInfo *II = D.getIdentifier();
13228   Expr *BitWidth = (Expr*)BitfieldWidth;
13229   SourceLocation Loc = DeclStart;
13230   if (II) Loc = D.getIdentifierLoc();
13231 
13232   // FIXME: Unnamed fields can be handled in various different ways, for
13233   // example, unnamed unions inject all members into the struct namespace!
13234 
13235   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13236   QualType T = TInfo->getType();
13237 
13238   if (BitWidth) {
13239     // 6.7.2.1p3, 6.7.2.1p4
13240     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13241     if (!BitWidth)
13242       D.setInvalidType();
13243   } else {
13244     // Not a bitfield.
13245 
13246     // validate II.
13247 
13248   }
13249   if (T->isReferenceType()) {
13250     Diag(Loc, diag::err_ivar_reference_type);
13251     D.setInvalidType();
13252   }
13253   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13254   // than a variably modified type.
13255   else if (T->isVariablyModifiedType()) {
13256     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13257     D.setInvalidType();
13258   }
13259 
13260   // Get the visibility (access control) for this ivar.
13261   ObjCIvarDecl::AccessControl ac =
13262     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13263                                         : ObjCIvarDecl::None;
13264   // Must set ivar's DeclContext to its enclosing interface.
13265   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13266   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13267     return nullptr;
13268   ObjCContainerDecl *EnclosingContext;
13269   if (ObjCImplementationDecl *IMPDecl =
13270       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13271     if (LangOpts.ObjCRuntime.isFragile()) {
13272     // Case of ivar declared in an implementation. Context is that of its class.
13273       EnclosingContext = IMPDecl->getClassInterface();
13274       assert(EnclosingContext && "Implementation has no class interface!");
13275     }
13276     else
13277       EnclosingContext = EnclosingDecl;
13278   } else {
13279     if (ObjCCategoryDecl *CDecl =
13280         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13281       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13282         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13283         return nullptr;
13284       }
13285     }
13286     EnclosingContext = EnclosingDecl;
13287   }
13288 
13289   // Construct the decl.
13290   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13291                                              DeclStart, Loc, II, T,
13292                                              TInfo, ac, (Expr *)BitfieldWidth);
13293 
13294   if (II) {
13295     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13296                                            ForRedeclaration);
13297     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13298         && !isa<TagDecl>(PrevDecl)) {
13299       Diag(Loc, diag::err_duplicate_member) << II;
13300       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13301       NewID->setInvalidDecl();
13302     }
13303   }
13304 
13305   // Process attributes attached to the ivar.
13306   ProcessDeclAttributes(S, NewID, D);
13307 
13308   if (D.isInvalidType())
13309     NewID->setInvalidDecl();
13310 
13311   // In ARC, infer 'retaining' for ivars of retainable type.
13312   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13313     NewID->setInvalidDecl();
13314 
13315   if (D.getDeclSpec().isModulePrivateSpecified())
13316     NewID->setModulePrivate();
13317 
13318   if (II) {
13319     // FIXME: When interfaces are DeclContexts, we'll need to add
13320     // these to the interface.
13321     S->AddDecl(NewID);
13322     IdResolver.AddDecl(NewID);
13323   }
13324 
13325   if (LangOpts.ObjCRuntime.isNonFragile() &&
13326       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13327     Diag(Loc, diag::warn_ivars_in_interface);
13328 
13329   return NewID;
13330 }
13331 
13332 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13333 /// class and class extensions. For every class \@interface and class
13334 /// extension \@interface, if the last ivar is a bitfield of any type,
13335 /// then add an implicit `char :0` ivar to the end of that interface.
13336 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13337                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13338   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13339     return;
13340 
13341   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13342   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13343 
13344   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13345     return;
13346   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13347   if (!ID) {
13348     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13349       if (!CD->IsClassExtension())
13350         return;
13351     }
13352     // No need to add this to end of @implementation.
13353     else
13354       return;
13355   }
13356   // All conditions are met. Add a new bitfield to the tail end of ivars.
13357   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13358   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13359 
13360   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13361                               DeclLoc, DeclLoc, nullptr,
13362                               Context.CharTy,
13363                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13364                                                                DeclLoc),
13365                               ObjCIvarDecl::Private, BW,
13366                               true);
13367   AllIvarDecls.push_back(Ivar);
13368 }
13369 
13370 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13371                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13372                        SourceLocation RBrac, AttributeList *Attr) {
13373   assert(EnclosingDecl && "missing record or interface decl");
13374 
13375   // If this is an Objective-C @implementation or category and we have
13376   // new fields here we should reset the layout of the interface since
13377   // it will now change.
13378   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13379     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13380     switch (DC->getKind()) {
13381     default: break;
13382     case Decl::ObjCCategory:
13383       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13384       break;
13385     case Decl::ObjCImplementation:
13386       Context.
13387         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13388       break;
13389     }
13390   }
13391 
13392   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13393 
13394   // Start counting up the number of named members; make sure to include
13395   // members of anonymous structs and unions in the total.
13396   unsigned NumNamedMembers = 0;
13397   if (Record) {
13398     for (const auto *I : Record->decls()) {
13399       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13400         if (IFD->getDeclName())
13401           ++NumNamedMembers;
13402     }
13403   }
13404 
13405   // Verify that all the fields are okay.
13406   SmallVector<FieldDecl*, 32> RecFields;
13407 
13408   bool ARCErrReported = false;
13409   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13410        i != end; ++i) {
13411     FieldDecl *FD = cast<FieldDecl>(*i);
13412 
13413     // Get the type for the field.
13414     const Type *FDTy = FD->getType().getTypePtr();
13415 
13416     if (!FD->isAnonymousStructOrUnion()) {
13417       // Remember all fields written by the user.
13418       RecFields.push_back(FD);
13419     }
13420 
13421     // If the field is already invalid for some reason, don't emit more
13422     // diagnostics about it.
13423     if (FD->isInvalidDecl()) {
13424       EnclosingDecl->setInvalidDecl();
13425       continue;
13426     }
13427 
13428     // C99 6.7.2.1p2:
13429     //   A structure or union shall not contain a member with
13430     //   incomplete or function type (hence, a structure shall not
13431     //   contain an instance of itself, but may contain a pointer to
13432     //   an instance of itself), except that the last member of a
13433     //   structure with more than one named member may have incomplete
13434     //   array type; such a structure (and any union containing,
13435     //   possibly recursively, a member that is such a structure)
13436     //   shall not be a member of a structure or an element of an
13437     //   array.
13438     if (FDTy->isFunctionType()) {
13439       // Field declared as a function.
13440       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13441         << FD->getDeclName();
13442       FD->setInvalidDecl();
13443       EnclosingDecl->setInvalidDecl();
13444       continue;
13445     } else if (FDTy->isIncompleteArrayType() && Record &&
13446                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13447                 ((getLangOpts().MicrosoftExt ||
13448                   getLangOpts().CPlusPlus) &&
13449                  (i + 1 == Fields.end() || Record->isUnion())))) {
13450       // Flexible array member.
13451       // Microsoft and g++ is more permissive regarding flexible array.
13452       // It will accept flexible array in union and also
13453       // as the sole element of a struct/class.
13454       unsigned DiagID = 0;
13455       if (Record->isUnion())
13456         DiagID = getLangOpts().MicrosoftExt
13457                      ? diag::ext_flexible_array_union_ms
13458                      : getLangOpts().CPlusPlus
13459                            ? diag::ext_flexible_array_union_gnu
13460                            : diag::err_flexible_array_union;
13461       else if (Fields.size() == 1)
13462         DiagID = getLangOpts().MicrosoftExt
13463                      ? diag::ext_flexible_array_empty_aggregate_ms
13464                      : getLangOpts().CPlusPlus
13465                            ? diag::ext_flexible_array_empty_aggregate_gnu
13466                            : NumNamedMembers < 1
13467                                  ? diag::err_flexible_array_empty_aggregate
13468                                  : 0;
13469 
13470       if (DiagID)
13471         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13472                                         << Record->getTagKind();
13473       // While the layout of types that contain virtual bases is not specified
13474       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13475       // virtual bases after the derived members.  This would make a flexible
13476       // array member declared at the end of an object not adjacent to the end
13477       // of the type.
13478       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13479         if (RD->getNumVBases() != 0)
13480           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13481             << FD->getDeclName() << Record->getTagKind();
13482       if (!getLangOpts().C99)
13483         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13484           << FD->getDeclName() << Record->getTagKind();
13485 
13486       // If the element type has a non-trivial destructor, we would not
13487       // implicitly destroy the elements, so disallow it for now.
13488       //
13489       // FIXME: GCC allows this. We should probably either implicitly delete
13490       // the destructor of the containing class, or just allow this.
13491       QualType BaseElem = Context.getBaseElementType(FD->getType());
13492       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13493         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13494           << FD->getDeclName() << FD->getType();
13495         FD->setInvalidDecl();
13496         EnclosingDecl->setInvalidDecl();
13497         continue;
13498       }
13499       // Okay, we have a legal flexible array member at the end of the struct.
13500       Record->setHasFlexibleArrayMember(true);
13501     } else if (!FDTy->isDependentType() &&
13502                RequireCompleteType(FD->getLocation(), FD->getType(),
13503                                    diag::err_field_incomplete)) {
13504       // Incomplete type
13505       FD->setInvalidDecl();
13506       EnclosingDecl->setInvalidDecl();
13507       continue;
13508     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13509       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13510         // A type which contains a flexible array member is considered to be a
13511         // flexible array member.
13512         Record->setHasFlexibleArrayMember(true);
13513         if (!Record->isUnion()) {
13514           // If this is a struct/class and this is not the last element, reject
13515           // it.  Note that GCC supports variable sized arrays in the middle of
13516           // structures.
13517           if (i + 1 != Fields.end())
13518             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13519               << FD->getDeclName() << FD->getType();
13520           else {
13521             // We support flexible arrays at the end of structs in
13522             // other structs as an extension.
13523             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13524               << FD->getDeclName();
13525           }
13526         }
13527       }
13528       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13529           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13530                                  diag::err_abstract_type_in_decl,
13531                                  AbstractIvarType)) {
13532         // Ivars can not have abstract class types
13533         FD->setInvalidDecl();
13534       }
13535       if (Record && FDTTy->getDecl()->hasObjectMember())
13536         Record->setHasObjectMember(true);
13537       if (Record && FDTTy->getDecl()->hasVolatileMember())
13538         Record->setHasVolatileMember(true);
13539     } else if (FDTy->isObjCObjectType()) {
13540       /// A field cannot be an Objective-c object
13541       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13542         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13543       QualType T = Context.getObjCObjectPointerType(FD->getType());
13544       FD->setType(T);
13545     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13546                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13547       // It's an error in ARC if a field has lifetime.
13548       // We don't want to report this in a system header, though,
13549       // so we just make the field unavailable.
13550       // FIXME: that's really not sufficient; we need to make the type
13551       // itself invalid to, say, initialize or copy.
13552       QualType T = FD->getType();
13553       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13554       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13555         SourceLocation loc = FD->getLocation();
13556         if (getSourceManager().isInSystemHeader(loc)) {
13557           if (!FD->hasAttr<UnavailableAttr>()) {
13558             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13559                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13560           }
13561         } else {
13562           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13563             << T->isBlockPointerType() << Record->getTagKind();
13564         }
13565         ARCErrReported = true;
13566       }
13567     } else if (getLangOpts().ObjC1 &&
13568                getLangOpts().getGC() != LangOptions::NonGC &&
13569                Record && !Record->hasObjectMember()) {
13570       if (FD->getType()->isObjCObjectPointerType() ||
13571           FD->getType().isObjCGCStrong())
13572         Record->setHasObjectMember(true);
13573       else if (Context.getAsArrayType(FD->getType())) {
13574         QualType BaseType = Context.getBaseElementType(FD->getType());
13575         if (BaseType->isRecordType() &&
13576             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13577           Record->setHasObjectMember(true);
13578         else if (BaseType->isObjCObjectPointerType() ||
13579                  BaseType.isObjCGCStrong())
13580                Record->setHasObjectMember(true);
13581       }
13582     }
13583     if (Record && FD->getType().isVolatileQualified())
13584       Record->setHasVolatileMember(true);
13585     // Keep track of the number of named members.
13586     if (FD->getIdentifier())
13587       ++NumNamedMembers;
13588   }
13589 
13590   // Okay, we successfully defined 'Record'.
13591   if (Record) {
13592     bool Completed = false;
13593     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13594       if (!CXXRecord->isInvalidDecl()) {
13595         // Set access bits correctly on the directly-declared conversions.
13596         for (CXXRecordDecl::conversion_iterator
13597                I = CXXRecord->conversion_begin(),
13598                E = CXXRecord->conversion_end(); I != E; ++I)
13599           I.setAccess((*I)->getAccess());
13600 
13601         if (!CXXRecord->isDependentType()) {
13602           if (CXXRecord->hasUserDeclaredDestructor()) {
13603             // Adjust user-defined destructor exception spec.
13604             if (getLangOpts().CPlusPlus11)
13605               AdjustDestructorExceptionSpec(CXXRecord,
13606                                             CXXRecord->getDestructor());
13607           }
13608 
13609           // Add any implicitly-declared members to this class.
13610           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13611 
13612           // If we have virtual base classes, we may end up finding multiple
13613           // final overriders for a given virtual function. Check for this
13614           // problem now.
13615           if (CXXRecord->getNumVBases()) {
13616             CXXFinalOverriderMap FinalOverriders;
13617             CXXRecord->getFinalOverriders(FinalOverriders);
13618 
13619             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13620                                              MEnd = FinalOverriders.end();
13621                  M != MEnd; ++M) {
13622               for (OverridingMethods::iterator SO = M->second.begin(),
13623                                             SOEnd = M->second.end();
13624                    SO != SOEnd; ++SO) {
13625                 assert(SO->second.size() > 0 &&
13626                        "Virtual function without overridding functions?");
13627                 if (SO->second.size() == 1)
13628                   continue;
13629 
13630                 // C++ [class.virtual]p2:
13631                 //   In a derived class, if a virtual member function of a base
13632                 //   class subobject has more than one final overrider the
13633                 //   program is ill-formed.
13634                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13635                   << (const NamedDecl *)M->first << Record;
13636                 Diag(M->first->getLocation(),
13637                      diag::note_overridden_virtual_function);
13638                 for (OverridingMethods::overriding_iterator
13639                           OM = SO->second.begin(),
13640                        OMEnd = SO->second.end();
13641                      OM != OMEnd; ++OM)
13642                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13643                     << (const NamedDecl *)M->first << OM->Method->getParent();
13644 
13645                 Record->setInvalidDecl();
13646               }
13647             }
13648             CXXRecord->completeDefinition(&FinalOverriders);
13649             Completed = true;
13650           }
13651         }
13652       }
13653     }
13654 
13655     if (!Completed)
13656       Record->completeDefinition();
13657 
13658     if (Record->hasAttrs()) {
13659       CheckAlignasUnderalignment(Record);
13660 
13661       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13662         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13663                                            IA->getRange(), IA->getBestCase(),
13664                                            IA->getSemanticSpelling());
13665     }
13666 
13667     // Check if the structure/union declaration is a type that can have zero
13668     // size in C. For C this is a language extension, for C++ it may cause
13669     // compatibility problems.
13670     bool CheckForZeroSize;
13671     if (!getLangOpts().CPlusPlus) {
13672       CheckForZeroSize = true;
13673     } else {
13674       // For C++ filter out types that cannot be referenced in C code.
13675       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13676       CheckForZeroSize =
13677           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13678           !CXXRecord->isDependentType() &&
13679           CXXRecord->isCLike();
13680     }
13681     if (CheckForZeroSize) {
13682       bool ZeroSize = true;
13683       bool IsEmpty = true;
13684       unsigned NonBitFields = 0;
13685       for (RecordDecl::field_iterator I = Record->field_begin(),
13686                                       E = Record->field_end();
13687            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13688         IsEmpty = false;
13689         if (I->isUnnamedBitfield()) {
13690           if (I->getBitWidthValue(Context) > 0)
13691             ZeroSize = false;
13692         } else {
13693           ++NonBitFields;
13694           QualType FieldType = I->getType();
13695           if (FieldType->isIncompleteType() ||
13696               !Context.getTypeSizeInChars(FieldType).isZero())
13697             ZeroSize = false;
13698         }
13699       }
13700 
13701       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13702       // allowed in C++, but warn if its declaration is inside
13703       // extern "C" block.
13704       if (ZeroSize) {
13705         Diag(RecLoc, getLangOpts().CPlusPlus ?
13706                          diag::warn_zero_size_struct_union_in_extern_c :
13707                          diag::warn_zero_size_struct_union_compat)
13708           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13709       }
13710 
13711       // Structs without named members are extension in C (C99 6.7.2.1p7),
13712       // but are accepted by GCC.
13713       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13714         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13715                                diag::ext_no_named_members_in_struct_union)
13716           << Record->isUnion();
13717       }
13718     }
13719   } else {
13720     ObjCIvarDecl **ClsFields =
13721       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13722     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13723       ID->setEndOfDefinitionLoc(RBrac);
13724       // Add ivar's to class's DeclContext.
13725       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13726         ClsFields[i]->setLexicalDeclContext(ID);
13727         ID->addDecl(ClsFields[i]);
13728       }
13729       // Must enforce the rule that ivars in the base classes may not be
13730       // duplicates.
13731       if (ID->getSuperClass())
13732         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13733     } else if (ObjCImplementationDecl *IMPDecl =
13734                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13735       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13736       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13737         // Ivar declared in @implementation never belongs to the implementation.
13738         // Only it is in implementation's lexical context.
13739         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13740       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13741       IMPDecl->setIvarLBraceLoc(LBrac);
13742       IMPDecl->setIvarRBraceLoc(RBrac);
13743     } else if (ObjCCategoryDecl *CDecl =
13744                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13745       // case of ivars in class extension; all other cases have been
13746       // reported as errors elsewhere.
13747       // FIXME. Class extension does not have a LocEnd field.
13748       // CDecl->setLocEnd(RBrac);
13749       // Add ivar's to class extension's DeclContext.
13750       // Diagnose redeclaration of private ivars.
13751       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13752       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13753         if (IDecl) {
13754           if (const ObjCIvarDecl *ClsIvar =
13755               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13756             Diag(ClsFields[i]->getLocation(),
13757                  diag::err_duplicate_ivar_declaration);
13758             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13759             continue;
13760           }
13761           for (const auto *Ext : IDecl->known_extensions()) {
13762             if (const ObjCIvarDecl *ClsExtIvar
13763                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13764               Diag(ClsFields[i]->getLocation(),
13765                    diag::err_duplicate_ivar_declaration);
13766               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13767               continue;
13768             }
13769           }
13770         }
13771         ClsFields[i]->setLexicalDeclContext(CDecl);
13772         CDecl->addDecl(ClsFields[i]);
13773       }
13774       CDecl->setIvarLBraceLoc(LBrac);
13775       CDecl->setIvarRBraceLoc(RBrac);
13776     }
13777   }
13778 
13779   if (Attr)
13780     ProcessDeclAttributeList(S, Record, Attr);
13781 }
13782 
13783 /// \brief Determine whether the given integral value is representable within
13784 /// the given type T.
13785 static bool isRepresentableIntegerValue(ASTContext &Context,
13786                                         llvm::APSInt &Value,
13787                                         QualType T) {
13788   assert(T->isIntegralType(Context) && "Integral type required!");
13789   unsigned BitWidth = Context.getIntWidth(T);
13790 
13791   if (Value.isUnsigned() || Value.isNonNegative()) {
13792     if (T->isSignedIntegerOrEnumerationType())
13793       --BitWidth;
13794     return Value.getActiveBits() <= BitWidth;
13795   }
13796   return Value.getMinSignedBits() <= BitWidth;
13797 }
13798 
13799 // \brief Given an integral type, return the next larger integral type
13800 // (or a NULL type of no such type exists).
13801 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13802   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13803   // enum checking below.
13804   assert(T->isIntegralType(Context) && "Integral type required!");
13805   const unsigned NumTypes = 4;
13806   QualType SignedIntegralTypes[NumTypes] = {
13807     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13808   };
13809   QualType UnsignedIntegralTypes[NumTypes] = {
13810     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13811     Context.UnsignedLongLongTy
13812   };
13813 
13814   unsigned BitWidth = Context.getTypeSize(T);
13815   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13816                                                         : UnsignedIntegralTypes;
13817   for (unsigned I = 0; I != NumTypes; ++I)
13818     if (Context.getTypeSize(Types[I]) > BitWidth)
13819       return Types[I];
13820 
13821   return QualType();
13822 }
13823 
13824 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13825                                           EnumConstantDecl *LastEnumConst,
13826                                           SourceLocation IdLoc,
13827                                           IdentifierInfo *Id,
13828                                           Expr *Val) {
13829   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13830   llvm::APSInt EnumVal(IntWidth);
13831   QualType EltTy;
13832 
13833   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13834     Val = nullptr;
13835 
13836   if (Val)
13837     Val = DefaultLvalueConversion(Val).get();
13838 
13839   if (Val) {
13840     if (Enum->isDependentType() || Val->isTypeDependent())
13841       EltTy = Context.DependentTy;
13842     else {
13843       SourceLocation ExpLoc;
13844       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13845           !getLangOpts().MSVCCompat) {
13846         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13847         // constant-expression in the enumerator-definition shall be a converted
13848         // constant expression of the underlying type.
13849         EltTy = Enum->getIntegerType();
13850         ExprResult Converted =
13851           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13852                                            CCEK_Enumerator);
13853         if (Converted.isInvalid())
13854           Val = nullptr;
13855         else
13856           Val = Converted.get();
13857       } else if (!Val->isValueDependent() &&
13858                  !(Val = VerifyIntegerConstantExpression(Val,
13859                                                          &EnumVal).get())) {
13860         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13861       } else {
13862         if (Enum->isFixed()) {
13863           EltTy = Enum->getIntegerType();
13864 
13865           // In Obj-C and Microsoft mode, require the enumeration value to be
13866           // representable in the underlying type of the enumeration. In C++11,
13867           // we perform a non-narrowing conversion as part of converted constant
13868           // expression checking.
13869           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13870             if (getLangOpts().MSVCCompat) {
13871               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13872               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13873             } else
13874               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13875           } else
13876             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13877         } else if (getLangOpts().CPlusPlus) {
13878           // C++11 [dcl.enum]p5:
13879           //   If the underlying type is not fixed, the type of each enumerator
13880           //   is the type of its initializing value:
13881           //     - If an initializer is specified for an enumerator, the
13882           //       initializing value has the same type as the expression.
13883           EltTy = Val->getType();
13884         } else {
13885           // C99 6.7.2.2p2:
13886           //   The expression that defines the value of an enumeration constant
13887           //   shall be an integer constant expression that has a value
13888           //   representable as an int.
13889 
13890           // Complain if the value is not representable in an int.
13891           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13892             Diag(IdLoc, diag::ext_enum_value_not_int)
13893               << EnumVal.toString(10) << Val->getSourceRange()
13894               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13895           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13896             // Force the type of the expression to 'int'.
13897             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13898           }
13899           EltTy = Val->getType();
13900         }
13901       }
13902     }
13903   }
13904 
13905   if (!Val) {
13906     if (Enum->isDependentType())
13907       EltTy = Context.DependentTy;
13908     else if (!LastEnumConst) {
13909       // C++0x [dcl.enum]p5:
13910       //   If the underlying type is not fixed, the type of each enumerator
13911       //   is the type of its initializing value:
13912       //     - If no initializer is specified for the first enumerator, the
13913       //       initializing value has an unspecified integral type.
13914       //
13915       // GCC uses 'int' for its unspecified integral type, as does
13916       // C99 6.7.2.2p3.
13917       if (Enum->isFixed()) {
13918         EltTy = Enum->getIntegerType();
13919       }
13920       else {
13921         EltTy = Context.IntTy;
13922       }
13923     } else {
13924       // Assign the last value + 1.
13925       EnumVal = LastEnumConst->getInitVal();
13926       ++EnumVal;
13927       EltTy = LastEnumConst->getType();
13928 
13929       // Check for overflow on increment.
13930       if (EnumVal < LastEnumConst->getInitVal()) {
13931         // C++0x [dcl.enum]p5:
13932         //   If the underlying type is not fixed, the type of each enumerator
13933         //   is the type of its initializing value:
13934         //
13935         //     - Otherwise the type of the initializing value is the same as
13936         //       the type of the initializing value of the preceding enumerator
13937         //       unless the incremented value is not representable in that type,
13938         //       in which case the type is an unspecified integral type
13939         //       sufficient to contain the incremented value. If no such type
13940         //       exists, the program is ill-formed.
13941         QualType T = getNextLargerIntegralType(Context, EltTy);
13942         if (T.isNull() || Enum->isFixed()) {
13943           // There is no integral type larger enough to represent this
13944           // value. Complain, then allow the value to wrap around.
13945           EnumVal = LastEnumConst->getInitVal();
13946           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13947           ++EnumVal;
13948           if (Enum->isFixed())
13949             // When the underlying type is fixed, this is ill-formed.
13950             Diag(IdLoc, diag::err_enumerator_wrapped)
13951               << EnumVal.toString(10)
13952               << EltTy;
13953           else
13954             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13955               << EnumVal.toString(10);
13956         } else {
13957           EltTy = T;
13958         }
13959 
13960         // Retrieve the last enumerator's value, extent that type to the
13961         // type that is supposed to be large enough to represent the incremented
13962         // value, then increment.
13963         EnumVal = LastEnumConst->getInitVal();
13964         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13965         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13966         ++EnumVal;
13967 
13968         // If we're not in C++, diagnose the overflow of enumerator values,
13969         // which in C99 means that the enumerator value is not representable in
13970         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13971         // permits enumerator values that are representable in some larger
13972         // integral type.
13973         if (!getLangOpts().CPlusPlus && !T.isNull())
13974           Diag(IdLoc, diag::warn_enum_value_overflow);
13975       } else if (!getLangOpts().CPlusPlus &&
13976                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13977         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13978         Diag(IdLoc, diag::ext_enum_value_not_int)
13979           << EnumVal.toString(10) << 1;
13980       }
13981     }
13982   }
13983 
13984   if (!EltTy->isDependentType()) {
13985     // Make the enumerator value match the signedness and size of the
13986     // enumerator's type.
13987     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13988     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13989   }
13990 
13991   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13992                                   Val, EnumVal);
13993 }
13994 
13995 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
13996                                                 SourceLocation IILoc) {
13997   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
13998       !getLangOpts().CPlusPlus)
13999     return SkipBodyInfo();
14000 
14001   // We have an anonymous enum definition. Look up the first enumerator to
14002   // determine if we should merge the definition with an existing one and
14003   // skip the body.
14004   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14005                                          ForRedeclaration);
14006   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14007   if (!PrevECD)
14008     return SkipBodyInfo();
14009 
14010   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14011   NamedDecl *Hidden;
14012   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14013     SkipBodyInfo Skip;
14014     Skip.Previous = Hidden;
14015     return Skip;
14016   }
14017 
14018   return SkipBodyInfo();
14019 }
14020 
14021 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14022                               SourceLocation IdLoc, IdentifierInfo *Id,
14023                               AttributeList *Attr,
14024                               SourceLocation EqualLoc, Expr *Val) {
14025   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14026   EnumConstantDecl *LastEnumConst =
14027     cast_or_null<EnumConstantDecl>(lastEnumConst);
14028 
14029   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14030   // we find one that is.
14031   S = getNonFieldDeclScope(S);
14032 
14033   // Verify that there isn't already something declared with this name in this
14034   // scope.
14035   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14036                                          ForRedeclaration);
14037   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14038     // Maybe we will complain about the shadowed template parameter.
14039     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14040     // Just pretend that we didn't see the previous declaration.
14041     PrevDecl = nullptr;
14042   }
14043 
14044   // C++ [class.mem]p15:
14045   // If T is the name of a class, then each of the following shall have a name
14046   // different from T:
14047   // - every enumerator of every member of class T that is an unscoped
14048   // enumerated type
14049   if (!TheEnumDecl->isScoped())
14050     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14051                             DeclarationNameInfo(Id, IdLoc));
14052 
14053   EnumConstantDecl *New =
14054     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14055   if (!New)
14056     return nullptr;
14057 
14058   if (PrevDecl) {
14059     // When in C++, we may get a TagDecl with the same name; in this case the
14060     // enum constant will 'hide' the tag.
14061     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14062            "Received TagDecl when not in C++!");
14063     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14064         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14065       if (isa<EnumConstantDecl>(PrevDecl))
14066         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14067       else
14068         Diag(IdLoc, diag::err_redefinition) << Id;
14069       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14070       return nullptr;
14071     }
14072   }
14073 
14074   // Process attributes.
14075   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14076 
14077   // Register this decl in the current scope stack.
14078   New->setAccess(TheEnumDecl->getAccess());
14079   PushOnScopeChains(New, S);
14080 
14081   ActOnDocumentableDecl(New);
14082 
14083   return New;
14084 }
14085 
14086 // Returns true when the enum initial expression does not trigger the
14087 // duplicate enum warning.  A few common cases are exempted as follows:
14088 // Element2 = Element1
14089 // Element2 = Element1 + 1
14090 // Element2 = Element1 - 1
14091 // Where Element2 and Element1 are from the same enum.
14092 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14093   Expr *InitExpr = ECD->getInitExpr();
14094   if (!InitExpr)
14095     return true;
14096   InitExpr = InitExpr->IgnoreImpCasts();
14097 
14098   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14099     if (!BO->isAdditiveOp())
14100       return true;
14101     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14102     if (!IL)
14103       return true;
14104     if (IL->getValue() != 1)
14105       return true;
14106 
14107     InitExpr = BO->getLHS();
14108   }
14109 
14110   // This checks if the elements are from the same enum.
14111   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14112   if (!DRE)
14113     return true;
14114 
14115   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14116   if (!EnumConstant)
14117     return true;
14118 
14119   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14120       Enum)
14121     return true;
14122 
14123   return false;
14124 }
14125 
14126 namespace {
14127 struct DupKey {
14128   int64_t val;
14129   bool isTombstoneOrEmptyKey;
14130   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14131     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14132 };
14133 
14134 static DupKey GetDupKey(const llvm::APSInt& Val) {
14135   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14136                 false);
14137 }
14138 
14139 struct DenseMapInfoDupKey {
14140   static DupKey getEmptyKey() { return DupKey(0, true); }
14141   static DupKey getTombstoneKey() { return DupKey(1, true); }
14142   static unsigned getHashValue(const DupKey Key) {
14143     return (unsigned)(Key.val * 37);
14144   }
14145   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14146     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14147            LHS.val == RHS.val;
14148   }
14149 };
14150 } // end anonymous namespace
14151 
14152 // Emits a warning when an element is implicitly set a value that
14153 // a previous element has already been set to.
14154 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14155                                         EnumDecl *Enum,
14156                                         QualType EnumType) {
14157   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14158     return;
14159   // Avoid anonymous enums
14160   if (!Enum->getIdentifier())
14161     return;
14162 
14163   // Only check for small enums.
14164   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14165     return;
14166 
14167   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14168   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14169 
14170   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14171   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14172           ValueToVectorMap;
14173 
14174   DuplicatesVector DupVector;
14175   ValueToVectorMap EnumMap;
14176 
14177   // Populate the EnumMap with all values represented by enum constants without
14178   // an initialier.
14179   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14180     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14181 
14182     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14183     // this constant.  Skip this enum since it may be ill-formed.
14184     if (!ECD) {
14185       return;
14186     }
14187 
14188     if (ECD->getInitExpr())
14189       continue;
14190 
14191     DupKey Key = GetDupKey(ECD->getInitVal());
14192     DeclOrVector &Entry = EnumMap[Key];
14193 
14194     // First time encountering this value.
14195     if (Entry.isNull())
14196       Entry = ECD;
14197   }
14198 
14199   // Create vectors for any values that has duplicates.
14200   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14201     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14202     if (!ValidDuplicateEnum(ECD, Enum))
14203       continue;
14204 
14205     DupKey Key = GetDupKey(ECD->getInitVal());
14206 
14207     DeclOrVector& Entry = EnumMap[Key];
14208     if (Entry.isNull())
14209       continue;
14210 
14211     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14212       // Ensure constants are different.
14213       if (D == ECD)
14214         continue;
14215 
14216       // Create new vector and push values onto it.
14217       ECDVector *Vec = new ECDVector();
14218       Vec->push_back(D);
14219       Vec->push_back(ECD);
14220 
14221       // Update entry to point to the duplicates vector.
14222       Entry = Vec;
14223 
14224       // Store the vector somewhere we can consult later for quick emission of
14225       // diagnostics.
14226       DupVector.push_back(Vec);
14227       continue;
14228     }
14229 
14230     ECDVector *Vec = Entry.get<ECDVector*>();
14231     // Make sure constants are not added more than once.
14232     if (*Vec->begin() == ECD)
14233       continue;
14234 
14235     Vec->push_back(ECD);
14236   }
14237 
14238   // Emit diagnostics.
14239   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14240                                   DupVectorEnd = DupVector.end();
14241        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14242     ECDVector *Vec = *DupVectorIter;
14243     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14244 
14245     // Emit warning for one enum constant.
14246     ECDVector::iterator I = Vec->begin();
14247     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14248       << (*I)->getName() << (*I)->getInitVal().toString(10)
14249       << (*I)->getSourceRange();
14250     ++I;
14251 
14252     // Emit one note for each of the remaining enum constants with
14253     // the same value.
14254     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14255       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14256         << (*I)->getName() << (*I)->getInitVal().toString(10)
14257         << (*I)->getSourceRange();
14258     delete Vec;
14259   }
14260 }
14261 
14262 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14263                              bool AllowMask) const {
14264   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14265   assert(ED->isCompleteDefinition() && "expected enum definition");
14266 
14267   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14268   llvm::APInt &FlagBits = R.first->second;
14269 
14270   if (R.second) {
14271     for (auto *E : ED->enumerators()) {
14272       const auto &EVal = E->getInitVal();
14273       // Only single-bit enumerators introduce new flag values.
14274       if (EVal.isPowerOf2())
14275         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14276     }
14277   }
14278 
14279   // A value is in a flag enum if either its bits are a subset of the enum's
14280   // flag bits (the first condition) or we are allowing masks and the same is
14281   // true of its complement (the second condition). When masks are allowed, we
14282   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14283   //
14284   // While it's true that any value could be used as a mask, the assumption is
14285   // that a mask will have all of the insignificant bits set. Anything else is
14286   // likely a logic error.
14287   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14288   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14289 }
14290 
14291 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14292                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14293                          ArrayRef<Decl *> Elements,
14294                          Scope *S, AttributeList *Attr) {
14295   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14296   QualType EnumType = Context.getTypeDeclType(Enum);
14297 
14298   if (Attr)
14299     ProcessDeclAttributeList(S, Enum, Attr);
14300 
14301   if (Enum->isDependentType()) {
14302     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14303       EnumConstantDecl *ECD =
14304         cast_or_null<EnumConstantDecl>(Elements[i]);
14305       if (!ECD) continue;
14306 
14307       ECD->setType(EnumType);
14308     }
14309 
14310     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14311     return;
14312   }
14313 
14314   // TODO: If the result value doesn't fit in an int, it must be a long or long
14315   // long value.  ISO C does not support this, but GCC does as an extension,
14316   // emit a warning.
14317   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14318   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14319   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14320 
14321   // Verify that all the values are okay, compute the size of the values, and
14322   // reverse the list.
14323   unsigned NumNegativeBits = 0;
14324   unsigned NumPositiveBits = 0;
14325 
14326   // Keep track of whether all elements have type int.
14327   bool AllElementsInt = true;
14328 
14329   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14330     EnumConstantDecl *ECD =
14331       cast_or_null<EnumConstantDecl>(Elements[i]);
14332     if (!ECD) continue;  // Already issued a diagnostic.
14333 
14334     const llvm::APSInt &InitVal = ECD->getInitVal();
14335 
14336     // Keep track of the size of positive and negative values.
14337     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14338       NumPositiveBits = std::max(NumPositiveBits,
14339                                  (unsigned)InitVal.getActiveBits());
14340     else
14341       NumNegativeBits = std::max(NumNegativeBits,
14342                                  (unsigned)InitVal.getMinSignedBits());
14343 
14344     // Keep track of whether every enum element has type int (very commmon).
14345     if (AllElementsInt)
14346       AllElementsInt = ECD->getType() == Context.IntTy;
14347   }
14348 
14349   // Figure out the type that should be used for this enum.
14350   QualType BestType;
14351   unsigned BestWidth;
14352 
14353   // C++0x N3000 [conv.prom]p3:
14354   //   An rvalue of an unscoped enumeration type whose underlying
14355   //   type is not fixed can be converted to an rvalue of the first
14356   //   of the following types that can represent all the values of
14357   //   the enumeration: int, unsigned int, long int, unsigned long
14358   //   int, long long int, or unsigned long long int.
14359   // C99 6.4.4.3p2:
14360   //   An identifier declared as an enumeration constant has type int.
14361   // The C99 rule is modified by a gcc extension
14362   QualType BestPromotionType;
14363 
14364   bool Packed = Enum->hasAttr<PackedAttr>();
14365   // -fshort-enums is the equivalent to specifying the packed attribute on all
14366   // enum definitions.
14367   if (LangOpts.ShortEnums)
14368     Packed = true;
14369 
14370   if (Enum->isFixed()) {
14371     BestType = Enum->getIntegerType();
14372     if (BestType->isPromotableIntegerType())
14373       BestPromotionType = Context.getPromotedIntegerType(BestType);
14374     else
14375       BestPromotionType = BestType;
14376 
14377     BestWidth = Context.getIntWidth(BestType);
14378   }
14379   else if (NumNegativeBits) {
14380     // If there is a negative value, figure out the smallest integer type (of
14381     // int/long/longlong) that fits.
14382     // If it's packed, check also if it fits a char or a short.
14383     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14384       BestType = Context.SignedCharTy;
14385       BestWidth = CharWidth;
14386     } else if (Packed && NumNegativeBits <= ShortWidth &&
14387                NumPositiveBits < ShortWidth) {
14388       BestType = Context.ShortTy;
14389       BestWidth = ShortWidth;
14390     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14391       BestType = Context.IntTy;
14392       BestWidth = IntWidth;
14393     } else {
14394       BestWidth = Context.getTargetInfo().getLongWidth();
14395 
14396       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14397         BestType = Context.LongTy;
14398       } else {
14399         BestWidth = Context.getTargetInfo().getLongLongWidth();
14400 
14401         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14402           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14403         BestType = Context.LongLongTy;
14404       }
14405     }
14406     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14407   } else {
14408     // If there is no negative value, figure out the smallest type that fits
14409     // all of the enumerator values.
14410     // If it's packed, check also if it fits a char or a short.
14411     if (Packed && NumPositiveBits <= CharWidth) {
14412       BestType = Context.UnsignedCharTy;
14413       BestPromotionType = Context.IntTy;
14414       BestWidth = CharWidth;
14415     } else if (Packed && NumPositiveBits <= ShortWidth) {
14416       BestType = Context.UnsignedShortTy;
14417       BestPromotionType = Context.IntTy;
14418       BestWidth = ShortWidth;
14419     } else if (NumPositiveBits <= IntWidth) {
14420       BestType = Context.UnsignedIntTy;
14421       BestWidth = IntWidth;
14422       BestPromotionType
14423         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14424                            ? Context.UnsignedIntTy : Context.IntTy;
14425     } else if (NumPositiveBits <=
14426                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14427       BestType = Context.UnsignedLongTy;
14428       BestPromotionType
14429         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14430                            ? Context.UnsignedLongTy : Context.LongTy;
14431     } else {
14432       BestWidth = Context.getTargetInfo().getLongLongWidth();
14433       assert(NumPositiveBits <= BestWidth &&
14434              "How could an initializer get larger than ULL?");
14435       BestType = Context.UnsignedLongLongTy;
14436       BestPromotionType
14437         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14438                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14439     }
14440   }
14441 
14442   // Loop over all of the enumerator constants, changing their types to match
14443   // the type of the enum if needed.
14444   for (auto *D : Elements) {
14445     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14446     if (!ECD) continue;  // Already issued a diagnostic.
14447 
14448     // Standard C says the enumerators have int type, but we allow, as an
14449     // extension, the enumerators to be larger than int size.  If each
14450     // enumerator value fits in an int, type it as an int, otherwise type it the
14451     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14452     // that X has type 'int', not 'unsigned'.
14453 
14454     // Determine whether the value fits into an int.
14455     llvm::APSInt InitVal = ECD->getInitVal();
14456 
14457     // If it fits into an integer type, force it.  Otherwise force it to match
14458     // the enum decl type.
14459     QualType NewTy;
14460     unsigned NewWidth;
14461     bool NewSign;
14462     if (!getLangOpts().CPlusPlus &&
14463         !Enum->isFixed() &&
14464         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14465       NewTy = Context.IntTy;
14466       NewWidth = IntWidth;
14467       NewSign = true;
14468     } else if (ECD->getType() == BestType) {
14469       // Already the right type!
14470       if (getLangOpts().CPlusPlus)
14471         // C++ [dcl.enum]p4: Following the closing brace of an
14472         // enum-specifier, each enumerator has the type of its
14473         // enumeration.
14474         ECD->setType(EnumType);
14475       continue;
14476     } else {
14477       NewTy = BestType;
14478       NewWidth = BestWidth;
14479       NewSign = BestType->isSignedIntegerOrEnumerationType();
14480     }
14481 
14482     // Adjust the APSInt value.
14483     InitVal = InitVal.extOrTrunc(NewWidth);
14484     InitVal.setIsSigned(NewSign);
14485     ECD->setInitVal(InitVal);
14486 
14487     // Adjust the Expr initializer and type.
14488     if (ECD->getInitExpr() &&
14489         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14490       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14491                                                 CK_IntegralCast,
14492                                                 ECD->getInitExpr(),
14493                                                 /*base paths*/ nullptr,
14494                                                 VK_RValue));
14495     if (getLangOpts().CPlusPlus)
14496       // C++ [dcl.enum]p4: Following the closing brace of an
14497       // enum-specifier, each enumerator has the type of its
14498       // enumeration.
14499       ECD->setType(EnumType);
14500     else
14501       ECD->setType(NewTy);
14502   }
14503 
14504   Enum->completeDefinition(BestType, BestPromotionType,
14505                            NumPositiveBits, NumNegativeBits);
14506 
14507   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14508 
14509   if (Enum->hasAttr<FlagEnumAttr>()) {
14510     for (Decl *D : Elements) {
14511       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14512       if (!ECD) continue;  // Already issued a diagnostic.
14513 
14514       llvm::APSInt InitVal = ECD->getInitVal();
14515       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14516           !IsValueInFlagEnum(Enum, InitVal, true))
14517         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14518           << ECD << Enum;
14519     }
14520   }
14521 
14522   // Now that the enum type is defined, ensure it's not been underaligned.
14523   if (Enum->hasAttrs())
14524     CheckAlignasUnderalignment(Enum);
14525 }
14526 
14527 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14528                                   SourceLocation StartLoc,
14529                                   SourceLocation EndLoc) {
14530   StringLiteral *AsmString = cast<StringLiteral>(expr);
14531 
14532   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14533                                                    AsmString, StartLoc,
14534                                                    EndLoc);
14535   CurContext->addDecl(New);
14536   return New;
14537 }
14538 
14539 static void checkModuleImportContext(Sema &S, Module *M,
14540                                      SourceLocation ImportLoc, DeclContext *DC,
14541                                      bool FromInclude = false) {
14542   SourceLocation ExternCLoc;
14543 
14544   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14545     switch (LSD->getLanguage()) {
14546     case LinkageSpecDecl::lang_c:
14547       if (ExternCLoc.isInvalid())
14548         ExternCLoc = LSD->getLocStart();
14549       break;
14550     case LinkageSpecDecl::lang_cxx:
14551       break;
14552     }
14553     DC = LSD->getParent();
14554   }
14555 
14556   while (isa<LinkageSpecDecl>(DC))
14557     DC = DC->getParent();
14558 
14559   if (!isa<TranslationUnitDecl>(DC)) {
14560     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14561                           ? diag::ext_module_import_not_at_top_level_noop
14562                           : diag::err_module_import_not_at_top_level_fatal)
14563         << M->getFullModuleName() << DC;
14564     S.Diag(cast<Decl>(DC)->getLocStart(),
14565            diag::note_module_import_not_at_top_level) << DC;
14566   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14567     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14568       << M->getFullModuleName();
14569     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14570   }
14571 }
14572 
14573 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14574   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14575 }
14576 
14577 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14578                                    SourceLocation ImportLoc,
14579                                    ModuleIdPath Path) {
14580   Module *Mod =
14581       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14582                                    /*IsIncludeDirective=*/false);
14583   if (!Mod)
14584     return true;
14585 
14586   VisibleModules.setVisible(Mod, ImportLoc);
14587 
14588   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14589 
14590   // FIXME: we should support importing a submodule within a different submodule
14591   // of the same top-level module. Until we do, make it an error rather than
14592   // silently ignoring the import.
14593   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14594     Diag(ImportLoc, diag::err_module_self_import)
14595         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14596   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14597     Diag(ImportLoc, diag::err_module_import_in_implementation)
14598         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14599 
14600   SmallVector<SourceLocation, 2> IdentifierLocs;
14601   Module *ModCheck = Mod;
14602   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14603     // If we've run out of module parents, just drop the remaining identifiers.
14604     // We need the length to be consistent.
14605     if (!ModCheck)
14606       break;
14607     ModCheck = ModCheck->Parent;
14608 
14609     IdentifierLocs.push_back(Path[I].second);
14610   }
14611 
14612   ImportDecl *Import = ImportDecl::Create(Context,
14613                                           Context.getTranslationUnitDecl(),
14614                                           AtLoc.isValid()? AtLoc : ImportLoc,
14615                                           Mod, IdentifierLocs);
14616   Context.getTranslationUnitDecl()->addDecl(Import);
14617   return Import;
14618 }
14619 
14620 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14621   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14622 
14623   // Determine whether we're in the #include buffer for a module. The #includes
14624   // in that buffer do not qualify as module imports; they're just an
14625   // implementation detail of us building the module.
14626   //
14627   // FIXME: Should we even get ActOnModuleInclude calls for those?
14628   bool IsInModuleIncludes =
14629       TUKind == TU_Module &&
14630       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14631 
14632   // If this module import was due to an inclusion directive, create an
14633   // implicit import declaration to capture it in the AST.
14634   if (!IsInModuleIncludes) {
14635     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14636     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14637                                                      DirectiveLoc, Mod,
14638                                                      DirectiveLoc);
14639     TU->addDecl(ImportD);
14640     Consumer.HandleImplicitImportDecl(ImportD);
14641   }
14642 
14643   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14644   VisibleModules.setVisible(Mod, DirectiveLoc);
14645 }
14646 
14647 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14648   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14649 
14650   if (getLangOpts().ModulesLocalVisibility)
14651     VisibleModulesStack.push_back(std::move(VisibleModules));
14652   VisibleModules.setVisible(Mod, DirectiveLoc);
14653 }
14654 
14655 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14656   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14657 
14658   if (getLangOpts().ModulesLocalVisibility) {
14659     VisibleModules = std::move(VisibleModulesStack.back());
14660     VisibleModulesStack.pop_back();
14661     VisibleModules.setVisible(Mod, DirectiveLoc);
14662   }
14663 }
14664 
14665 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14666                                                       Module *Mod) {
14667   // Bail if we're not allowed to implicitly import a module here.
14668   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14669     return;
14670 
14671   // Create the implicit import declaration.
14672   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14673   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14674                                                    Loc, Mod, Loc);
14675   TU->addDecl(ImportD);
14676   Consumer.HandleImplicitImportDecl(ImportD);
14677 
14678   // Make the module visible.
14679   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14680   VisibleModules.setVisible(Mod, Loc);
14681 }
14682 
14683 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14684                                       IdentifierInfo* AliasName,
14685                                       SourceLocation PragmaLoc,
14686                                       SourceLocation NameLoc,
14687                                       SourceLocation AliasNameLoc) {
14688   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14689                                          LookupOrdinaryName);
14690   AsmLabelAttr *Attr =
14691       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14692 
14693   // If a declaration that:
14694   // 1) declares a function or a variable
14695   // 2) has external linkage
14696   // already exists, add a label attribute to it.
14697   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14698     if (isDeclExternC(PrevDecl))
14699       PrevDecl->addAttr(Attr);
14700     else
14701       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14702           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14703   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14704   } else
14705     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14706 }
14707 
14708 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14709                              SourceLocation PragmaLoc,
14710                              SourceLocation NameLoc) {
14711   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14712 
14713   if (PrevDecl) {
14714     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14715   } else {
14716     (void)WeakUndeclaredIdentifiers.insert(
14717       std::pair<IdentifierInfo*,WeakInfo>
14718         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14719   }
14720 }
14721 
14722 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14723                                 IdentifierInfo* AliasName,
14724                                 SourceLocation PragmaLoc,
14725                                 SourceLocation NameLoc,
14726                                 SourceLocation AliasNameLoc) {
14727   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14728                                     LookupOrdinaryName);
14729   WeakInfo W = WeakInfo(Name, NameLoc);
14730 
14731   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14732     if (!PrevDecl->hasAttr<AliasAttr>())
14733       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14734         DeclApplyPragmaWeak(TUScope, ND, W);
14735   } else {
14736     (void)WeakUndeclaredIdentifiers.insert(
14737       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14738   }
14739 }
14740 
14741 Decl *Sema::getObjCDeclContext() const {
14742   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14743 }
14744 
14745 AvailabilityResult Sema::getCurContextAvailability() const {
14746   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14747   if (!D)
14748     return AR_Available;
14749 
14750   // If we are within an Objective-C method, we should consult
14751   // both the availability of the method as well as the
14752   // enclosing class.  If the class is (say) deprecated,
14753   // the entire method is considered deprecated from the
14754   // purpose of checking if the current context is deprecated.
14755   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14756     AvailabilityResult R = MD->getAvailability();
14757     if (R != AR_Available)
14758       return R;
14759     D = MD->getClassInterface();
14760   }
14761   // If we are within an Objective-c @implementation, it
14762   // gets the same availability context as the @interface.
14763   else if (const ObjCImplementationDecl *ID =
14764             dyn_cast<ObjCImplementationDecl>(D)) {
14765     D = ID->getClassInterface();
14766   }
14767   // Recover from user error.
14768   return D ? D->getAvailability() : AR_Available;
14769 }
14770