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 nullptr;
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 nullptr;
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 nullptr;
283     }
284 
285     if (!LookupCtx->isDependentContext() &&
286         RequireCompleteDeclContext(*SS, LookupCtx))
287       return nullptr;
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, nullptr, false,
350                            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 nullptr;
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 nullptr;
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 nullptr;
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 nullptr;
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 = nullptr;
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 =
596           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
597                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
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, nullptr, 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 forgot 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.getFoundDecl();
817         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
818         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
819             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
820           UnqualifiedDiag = diag::err_no_template_suggest;
821           QualifiedDiag = diag::err_no_member_template_suggest;
822         } else if (UnderlyingFirstDecl &&
823                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
824                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
825                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
826           UnqualifiedDiag = diag::err_unknown_typename_suggest;
827           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
828         }
829 
830         if (SS.isEmpty()) {
831           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
832         } else {// FIXME: is this even reachable? Test it.
833           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
834           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
835                                   Name->getName().equals(CorrectedStr);
836           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
837                                     << Name << computeDeclContext(SS, false)
838                                     << DroppedSpecifier << SS.getRange());
839         }
840 
841         // Update the name, so that the caller has the new name.
842         Name = Corrected.getCorrectionAsIdentifierInfo();
843 
844         // Typo correction corrected to a keyword.
845         if (Corrected.isKeyword())
846           return Name;
847 
848         // Also update the LookupResult...
849         // FIXME: This should probably go away at some point
850         Result.clear();
851         Result.setLookupName(Corrected.getCorrection());
852         if (FirstDecl)
853           Result.addDecl(FirstDecl);
854 
855         // If we found an Objective-C instance variable, let
856         // LookupInObjCMethod build the appropriate expression to
857         // reference the ivar.
858         // FIXME: This is a gross hack.
859         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
860           Result.clear();
861           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
862           return E;
863         }
864 
865         goto Corrected;
866       }
867     }
868 
869     // We failed to correct; just fall through and let the parser deal with it.
870     Result.suppressDiagnostics();
871     return NameClassification::Unknown();
872 
873   case LookupResult::NotFoundInCurrentInstantiation: {
874     // We performed name lookup into the current instantiation, and there were
875     // dependent bases, so we treat this result the same way as any other
876     // dependent nested-name-specifier.
877 
878     // C++ [temp.res]p2:
879     //   A name used in a template declaration or definition and that is
880     //   dependent on a template-parameter is assumed not to name a type
881     //   unless the applicable name lookup finds a type name or the name is
882     //   qualified by the keyword typename.
883     //
884     // FIXME: If the next token is '<', we might want to ask the parser to
885     // perform some heroics to see if we actually have a
886     // template-argument-list, which would indicate a missing 'template'
887     // keyword here.
888     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
889                                       NameInfo, IsAddressOfOperand,
890                                       /*TemplateArgs=*/nullptr);
891   }
892 
893   case LookupResult::Found:
894   case LookupResult::FoundOverloaded:
895   case LookupResult::FoundUnresolvedValue:
896     break;
897 
898   case LookupResult::Ambiguous:
899     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
900         hasAnyAcceptableTemplateNames(Result)) {
901       // C++ [temp.local]p3:
902       //   A lookup that finds an injected-class-name (10.2) can result in an
903       //   ambiguity in certain cases (for example, if it is found in more than
904       //   one base class). If all of the injected-class-names that are found
905       //   refer to specializations of the same class template, and if the name
906       //   is followed by a template-argument-list, the reference refers to the
907       //   class template itself and not a specialization thereof, and is not
908       //   ambiguous.
909       //
910       // This filtering can make an ambiguous result into an unambiguous one,
911       // so try again after filtering out template names.
912       FilterAcceptableTemplateNames(Result);
913       if (!Result.isAmbiguous()) {
914         IsFilteredTemplateName = true;
915         break;
916       }
917     }
918 
919     // Diagnose the ambiguity and return an error.
920     return NameClassification::Error();
921   }
922 
923   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
924       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
925     // C++ [temp.names]p3:
926     //   After name lookup (3.4) finds that a name is a template-name or that
927     //   an operator-function-id or a literal- operator-id refers to a set of
928     //   overloaded functions any member of which is a function template if
929     //   this is followed by a <, the < is always taken as the delimiter of a
930     //   template-argument-list and never as the less-than operator.
931     if (!IsFilteredTemplateName)
932       FilterAcceptableTemplateNames(Result);
933 
934     if (!Result.empty()) {
935       bool IsFunctionTemplate;
936       bool IsVarTemplate;
937       TemplateName Template;
938       if (Result.end() - Result.begin() > 1) {
939         IsFunctionTemplate = true;
940         Template = Context.getOverloadedTemplateName(Result.begin(),
941                                                      Result.end());
942       } else {
943         TemplateDecl *TD
944           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
945         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
946         IsVarTemplate = isa<VarTemplateDecl>(TD);
947 
948         if (SS.isSet() && !SS.isInvalid())
949           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
950                                                     /*TemplateKeyword=*/false,
951                                                       TD);
952         else
953           Template = TemplateName(TD);
954       }
955 
956       if (IsFunctionTemplate) {
957         // Function templates always go through overload resolution, at which
958         // point we'll perform the various checks (e.g., accessibility) we need
959         // to based on which function we selected.
960         Result.suppressDiagnostics();
961 
962         return NameClassification::FunctionTemplate(Template);
963       }
964 
965       return IsVarTemplate ? NameClassification::VarTemplate(Template)
966                            : NameClassification::TypeTemplate(Template);
967     }
968   }
969 
970   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
971   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
972     DiagnoseUseOfDecl(Type, NameLoc);
973     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
974     QualType T = Context.getTypeDeclType(Type);
975     if (SS.isNotEmpty())
976       return buildNestedType(*this, SS, T, NameLoc);
977     return ParsedType::make(T);
978   }
979 
980   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
981   if (!Class) {
982     // FIXME: It's unfortunate that we don't have a Type node for handling this.
983     if (ObjCCompatibleAliasDecl *Alias =
984             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
985       Class = Alias->getClassInterface();
986   }
987 
988   if (Class) {
989     DiagnoseUseOfDecl(Class, NameLoc);
990 
991     if (NextToken.is(tok::period)) {
992       // Interface. <something> is parsed as a property reference expression.
993       // Just return "unknown" as a fall-through for now.
994       Result.suppressDiagnostics();
995       return NameClassification::Unknown();
996     }
997 
998     QualType T = Context.getObjCInterfaceType(Class);
999     return ParsedType::make(T);
1000   }
1001 
1002   // We can have a type template here if we're classifying a template argument.
1003   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1004     return NameClassification::TypeTemplate(
1005         TemplateName(cast<TemplateDecl>(FirstDecl)));
1006 
1007   // Check for a tag type hidden by a non-type decl in a few cases where it
1008   // seems likely a type is wanted instead of the non-type that was found.
1009   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1010   if ((NextToken.is(tok::identifier) ||
1011        (NextIsOp &&
1012         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1013       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1014     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1015     DiagnoseUseOfDecl(Type, NameLoc);
1016     QualType T = Context.getTypeDeclType(Type);
1017     if (SS.isNotEmpty())
1018       return buildNestedType(*this, SS, T, NameLoc);
1019     return ParsedType::make(T);
1020   }
1021 
1022   if (FirstDecl->isCXXClassMember())
1023     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1024                                            nullptr, S);
1025 
1026   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1027   return BuildDeclarationNameExpr(SS, Result, ADL);
1028 }
1029 
1030 // Determines the context to return to after temporarily entering a
1031 // context.  This depends in an unnecessarily complicated way on the
1032 // exact ordering of callbacks from the parser.
1033 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1034 
1035   // Functions defined inline within classes aren't parsed until we've
1036   // finished parsing the top-level class, so the top-level class is
1037   // the context we'll need to return to.
1038   // A Lambda call operator whose parent is a class must not be treated
1039   // as an inline member function.  A Lambda can be used legally
1040   // either as an in-class member initializer or a default argument.  These
1041   // are parsed once the class has been marked complete and so the containing
1042   // context would be the nested class (when the lambda is defined in one);
1043   // If the class is not complete, then the lambda is being used in an
1044   // ill-formed fashion (such as to specify the width of a bit-field, or
1045   // in an array-bound) - in which case we still want to return the
1046   // lexically containing DC (which could be a nested class).
1047   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1048     DC = DC->getLexicalParent();
1049 
1050     // A function not defined within a class will always return to its
1051     // lexical context.
1052     if (!isa<CXXRecordDecl>(DC))
1053       return DC;
1054 
1055     // A C++ inline method/friend is parsed *after* the topmost class
1056     // it was declared in is fully parsed ("complete");  the topmost
1057     // class is the context we need to return to.
1058     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1059       DC = RD;
1060 
1061     // Return the declaration context of the topmost class the inline method is
1062     // declared in.
1063     return DC;
1064   }
1065 
1066   return DC->getLexicalParent();
1067 }
1068 
1069 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1070   assert(getContainingDC(DC) == CurContext &&
1071       "The next DeclContext should be lexically contained in the current one.");
1072   CurContext = DC;
1073   S->setEntity(DC);
1074 }
1075 
1076 void Sema::PopDeclContext() {
1077   assert(CurContext && "DeclContext imbalance!");
1078 
1079   CurContext = getContainingDC(CurContext);
1080   assert(CurContext && "Popped translation unit!");
1081 }
1082 
1083 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1084                                                                     Decl *D) {
1085   // Unlike PushDeclContext, the context to which we return is not necessarily
1086   // the containing DC of TD, because the new context will be some pre-existing
1087   // TagDecl definition instead of a fresh one.
1088   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1089   CurContext = cast<TagDecl>(D)->getDefinition();
1090   assert(CurContext && "skipping definition of undefined tag");
1091   // Start lookups from the parent of the current context; we don't want to look
1092   // into the pre-existing complete definition.
1093   S->setEntity(CurContext->getLookupParent());
1094   return Result;
1095 }
1096 
1097 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1098   CurContext = static_cast<decltype(CurContext)>(Context);
1099 }
1100 
1101 /// EnterDeclaratorContext - Used when we must lookup names in the context
1102 /// of a declarator's nested name specifier.
1103 ///
1104 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1105   // C++0x [basic.lookup.unqual]p13:
1106   //   A name used in the definition of a static data member of class
1107   //   X (after the qualified-id of the static member) is looked up as
1108   //   if the name was used in a member function of X.
1109   // C++0x [basic.lookup.unqual]p14:
1110   //   If a variable member of a namespace is defined outside of the
1111   //   scope of its namespace then any name used in the definition of
1112   //   the variable member (after the declarator-id) is looked up as
1113   //   if the definition of the variable member occurred in its
1114   //   namespace.
1115   // Both of these imply that we should push a scope whose context
1116   // is the semantic context of the declaration.  We can't use
1117   // PushDeclContext here because that context is not necessarily
1118   // lexically contained in the current context.  Fortunately,
1119   // the containing scope should have the appropriate information.
1120 
1121   assert(!S->getEntity() && "scope already has entity");
1122 
1123 #ifndef NDEBUG
1124   Scope *Ancestor = S->getParent();
1125   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1126   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1127 #endif
1128 
1129   CurContext = DC;
1130   S->setEntity(DC);
1131 }
1132 
1133 void Sema::ExitDeclaratorContext(Scope *S) {
1134   assert(S->getEntity() == CurContext && "Context imbalance!");
1135 
1136   // Switch back to the lexical context.  The safety of this is
1137   // enforced by an assert in EnterDeclaratorContext.
1138   Scope *Ancestor = S->getParent();
1139   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1140   CurContext = Ancestor->getEntity();
1141 
1142   // We don't need to do anything with the scope, which is going to
1143   // disappear.
1144 }
1145 
1146 
1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1148   // We assume that the caller has already called
1149   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1150   FunctionDecl *FD = D->getAsFunction();
1151   if (!FD)
1152     return;
1153 
1154   // Same implementation as PushDeclContext, but enters the context
1155   // from the lexical parent, rather than the top-level class.
1156   assert(CurContext == FD->getLexicalParent() &&
1157     "The next DeclContext should be lexically contained in the current one.");
1158   CurContext = FD;
1159   S->setEntity(CurContext);
1160 
1161   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1162     ParmVarDecl *Param = FD->getParamDecl(P);
1163     // If the parameter has an identifier, then add it to the scope
1164     if (Param->getIdentifier()) {
1165       S->AddDecl(Param);
1166       IdResolver.AddDecl(Param);
1167     }
1168   }
1169 }
1170 
1171 
1172 void Sema::ActOnExitFunctionContext() {
1173   // Same implementation as PopDeclContext, but returns to the lexical parent,
1174   // rather than the top-level class.
1175   assert(CurContext && "DeclContext imbalance!");
1176   CurContext = CurContext->getLexicalParent();
1177   assert(CurContext && "Popped translation unit!");
1178 }
1179 
1180 
1181 /// \brief Determine whether we allow overloading of the function
1182 /// PrevDecl with another declaration.
1183 ///
1184 /// This routine determines whether overloading is possible, not
1185 /// whether some new function is actually an overload. It will return
1186 /// true in C++ (where we can always provide overloads) or, as an
1187 /// extension, in C when the previous function is already an
1188 /// overloaded function declaration or has the "overloadable"
1189 /// attribute.
1190 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1191                                        ASTContext &Context) {
1192   if (Context.getLangOpts().CPlusPlus)
1193     return true;
1194 
1195   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1196     return true;
1197 
1198   return (Previous.getResultKind() == LookupResult::Found
1199           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1200 }
1201 
1202 /// Add this decl to the scope shadowed decl chains.
1203 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1204   // Move up the scope chain until we find the nearest enclosing
1205   // non-transparent context. The declaration will be introduced into this
1206   // scope.
1207   while (S->getEntity() && S->getEntity()->isTransparentContext())
1208     S = S->getParent();
1209 
1210   // Add scoped declarations into their context, so that they can be
1211   // found later. Declarations without a context won't be inserted
1212   // into any context.
1213   if (AddToContext)
1214     CurContext->addDecl(D);
1215 
1216   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1217   // are function-local declarations.
1218   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1219       !D->getDeclContext()->getRedeclContext()->Equals(
1220         D->getLexicalDeclContext()->getRedeclContext()) &&
1221       !D->getLexicalDeclContext()->isFunctionOrMethod())
1222     return;
1223 
1224   // Template instantiations should also not be pushed into scope.
1225   if (isa<FunctionDecl>(D) &&
1226       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1227     return;
1228 
1229   // If this replaces anything in the current scope,
1230   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1231                                IEnd = IdResolver.end();
1232   for (; I != IEnd; ++I) {
1233     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1234       S->RemoveDecl(*I);
1235       IdResolver.RemoveDecl(*I);
1236 
1237       // Should only need to replace one decl.
1238       break;
1239     }
1240   }
1241 
1242   S->AddDecl(D);
1243 
1244   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1245     // Implicitly-generated labels may end up getting generated in an order that
1246     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1247     // the label at the appropriate place in the identifier chain.
1248     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1249       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1250       if (IDC == CurContext) {
1251         if (!S->isDeclScope(*I))
1252           continue;
1253       } else if (IDC->Encloses(CurContext))
1254         break;
1255     }
1256 
1257     IdResolver.InsertDeclAfter(I, D);
1258   } else {
1259     IdResolver.AddDecl(D);
1260   }
1261 }
1262 
1263 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1264   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1265     TUScope->AddDecl(D);
1266 }
1267 
1268 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1269                          bool AllowInlineNamespace) {
1270   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1271 }
1272 
1273 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1274   DeclContext *TargetDC = DC->getPrimaryContext();
1275   do {
1276     if (DeclContext *ScopeDC = S->getEntity())
1277       if (ScopeDC->getPrimaryContext() == TargetDC)
1278         return S;
1279   } while ((S = S->getParent()));
1280 
1281   return nullptr;
1282 }
1283 
1284 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1285                                             DeclContext*,
1286                                             ASTContext&);
1287 
1288 /// Filters out lookup results that don't fall within the given scope
1289 /// as determined by isDeclInScope.
1290 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1291                                 bool ConsiderLinkage,
1292                                 bool AllowInlineNamespace) {
1293   LookupResult::Filter F = R.makeFilter();
1294   while (F.hasNext()) {
1295     NamedDecl *D = F.next();
1296 
1297     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1298       continue;
1299 
1300     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1301       continue;
1302 
1303     F.erase();
1304   }
1305 
1306   F.done();
1307 }
1308 
1309 static bool isUsingDecl(NamedDecl *D) {
1310   return isa<UsingShadowDecl>(D) ||
1311          isa<UnresolvedUsingTypenameDecl>(D) ||
1312          isa<UnresolvedUsingValueDecl>(D);
1313 }
1314 
1315 /// Removes using shadow declarations from the lookup results.
1316 static void RemoveUsingDecls(LookupResult &R) {
1317   LookupResult::Filter F = R.makeFilter();
1318   while (F.hasNext())
1319     if (isUsingDecl(F.next()))
1320       F.erase();
1321 
1322   F.done();
1323 }
1324 
1325 /// \brief Check for this common pattern:
1326 /// @code
1327 /// class S {
1328 ///   S(const S&); // DO NOT IMPLEMENT
1329 ///   void operator=(const S&); // DO NOT IMPLEMENT
1330 /// };
1331 /// @endcode
1332 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1333   // FIXME: Should check for private access too but access is set after we get
1334   // the decl here.
1335   if (D->doesThisDeclarationHaveABody())
1336     return false;
1337 
1338   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1339     return CD->isCopyConstructor();
1340   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1341     return Method->isCopyAssignmentOperator();
1342   return false;
1343 }
1344 
1345 // We need this to handle
1346 //
1347 // typedef struct {
1348 //   void *foo() { return 0; }
1349 // } A;
1350 //
1351 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1352 // for example. If 'A', foo will have external linkage. If we have '*A',
1353 // foo will have no linkage. Since we can't know until we get to the end
1354 // of the typedef, this function finds out if D might have non-external linkage.
1355 // Callers should verify at the end of the TU if it D has external linkage or
1356 // not.
1357 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1358   const DeclContext *DC = D->getDeclContext();
1359   while (!DC->isTranslationUnit()) {
1360     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1361       if (!RD->hasNameForLinkage())
1362         return true;
1363     }
1364     DC = DC->getParent();
1365   }
1366 
1367   return !D->isExternallyVisible();
1368 }
1369 
1370 // FIXME: This needs to be refactored; some other isInMainFile users want
1371 // these semantics.
1372 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1373   if (S.TUKind != TU_Complete)
1374     return false;
1375   return S.SourceMgr.isInMainFile(Loc);
1376 }
1377 
1378 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1379   assert(D);
1380 
1381   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1382     return false;
1383 
1384   // Ignore all entities declared within templates, and out-of-line definitions
1385   // of members of class templates.
1386   if (D->getDeclContext()->isDependentContext() ||
1387       D->getLexicalDeclContext()->isDependentContext())
1388     return false;
1389 
1390   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1391     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1392       return false;
1393 
1394     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1395       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1396         return false;
1397     } else {
1398       // 'static inline' functions are defined in headers; don't warn.
1399       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1400         return false;
1401     }
1402 
1403     if (FD->doesThisDeclarationHaveABody() &&
1404         Context.DeclMustBeEmitted(FD))
1405       return false;
1406   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1407     // Constants and utility variables are defined in headers with internal
1408     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1409     // like "inline".)
1410     if (!isMainFileLoc(*this, VD->getLocation()))
1411       return false;
1412 
1413     if (Context.DeclMustBeEmitted(VD))
1414       return false;
1415 
1416     if (VD->isStaticDataMember() &&
1417         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1418       return false;
1419   } else {
1420     return false;
1421   }
1422 
1423   // Only warn for unused decls internal to the translation unit.
1424   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1425   // for inline functions defined in the main source file, for instance.
1426   return mightHaveNonExternalLinkage(D);
1427 }
1428 
1429 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1430   if (!D)
1431     return;
1432 
1433   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1434     const FunctionDecl *First = FD->getFirstDecl();
1435     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1436       return; // First should already be in the vector.
1437   }
1438 
1439   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1440     const VarDecl *First = VD->getFirstDecl();
1441     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1442       return; // First should already be in the vector.
1443   }
1444 
1445   if (ShouldWarnIfUnusedFileScopedDecl(D))
1446     UnusedFileScopedDecls.push_back(D);
1447 }
1448 
1449 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1450   if (D->isInvalidDecl())
1451     return false;
1452 
1453   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1454       D->hasAttr<ObjCPreciseLifetimeAttr>())
1455     return false;
1456 
1457   if (isa<LabelDecl>(D))
1458     return true;
1459 
1460   // Except for labels, we only care about unused decls that are local to
1461   // functions.
1462   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1463   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1464     // For dependent types, the diagnostic is deferred.
1465     WithinFunction =
1466         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1467   if (!WithinFunction)
1468     return false;
1469 
1470   if (isa<TypedefNameDecl>(D))
1471     return true;
1472 
1473   // White-list anything that isn't a local variable.
1474   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1475     return false;
1476 
1477   // Types of valid local variables should be complete, so this should succeed.
1478   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1479 
1480     // White-list anything with an __attribute__((unused)) type.
1481     QualType Ty = VD->getType();
1482 
1483     // Only look at the outermost level of typedef.
1484     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1485       if (TT->getDecl()->hasAttr<UnusedAttr>())
1486         return false;
1487     }
1488 
1489     // If we failed to complete the type for some reason, or if the type is
1490     // dependent, don't diagnose the variable.
1491     if (Ty->isIncompleteType() || Ty->isDependentType())
1492       return false;
1493 
1494     if (const TagType *TT = Ty->getAs<TagType>()) {
1495       const TagDecl *Tag = TT->getDecl();
1496       if (Tag->hasAttr<UnusedAttr>())
1497         return false;
1498 
1499       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1500         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1501           return false;
1502 
1503         if (const Expr *Init = VD->getInit()) {
1504           if (const ExprWithCleanups *Cleanups =
1505                   dyn_cast<ExprWithCleanups>(Init))
1506             Init = Cleanups->getSubExpr();
1507           const CXXConstructExpr *Construct =
1508             dyn_cast<CXXConstructExpr>(Init);
1509           if (Construct && !Construct->isElidable()) {
1510             CXXConstructorDecl *CD = Construct->getConstructor();
1511             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1512               return false;
1513           }
1514         }
1515       }
1516     }
1517 
1518     // TODO: __attribute__((unused)) templates?
1519   }
1520 
1521   return true;
1522 }
1523 
1524 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1525                                      FixItHint &Hint) {
1526   if (isa<LabelDecl>(D)) {
1527     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1528                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1529     if (AfterColon.isInvalid())
1530       return;
1531     Hint = FixItHint::CreateRemoval(CharSourceRange::
1532                                     getCharRange(D->getLocStart(), AfterColon));
1533   }
1534   return;
1535 }
1536 
1537 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1538   if (D->getTypeForDecl()->isDependentType())
1539     return;
1540 
1541   for (auto *TmpD : D->decls()) {
1542     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1543       DiagnoseUnusedDecl(T);
1544     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1545       DiagnoseUnusedNestedTypedefs(R);
1546   }
1547 }
1548 
1549 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1550 /// unless they are marked attr(unused).
1551 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1552   if (!ShouldDiagnoseUnusedDecl(D))
1553     return;
1554 
1555   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1556     // typedefs can be referenced later on, so the diagnostics are emitted
1557     // at end-of-translation-unit.
1558     UnusedLocalTypedefNameCandidates.insert(TD);
1559     return;
1560   }
1561 
1562   FixItHint Hint;
1563   GenerateFixForUnusedDecl(D, Context, Hint);
1564 
1565   unsigned DiagID;
1566   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1567     DiagID = diag::warn_unused_exception_param;
1568   else if (isa<LabelDecl>(D))
1569     DiagID = diag::warn_unused_label;
1570   else
1571     DiagID = diag::warn_unused_variable;
1572 
1573   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1574 }
1575 
1576 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1577   // Verify that we have no forward references left.  If so, there was a goto
1578   // or address of a label taken, but no definition of it.  Label fwd
1579   // definitions are indicated with a null substmt which is also not a resolved
1580   // MS inline assembly label name.
1581   bool Diagnose = false;
1582   if (L->isMSAsmLabel())
1583     Diagnose = !L->isResolvedMSAsmLabel();
1584   else
1585     Diagnose = L->getStmt() == nullptr;
1586   if (Diagnose)
1587     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1588 }
1589 
1590 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1591   S->mergeNRVOIntoParent();
1592 
1593   if (S->decl_empty()) return;
1594   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1595          "Scope shouldn't contain decls!");
1596 
1597   for (auto *TmpD : S->decls()) {
1598     assert(TmpD && "This decl didn't get pushed??");
1599 
1600     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1601     NamedDecl *D = cast<NamedDecl>(TmpD);
1602 
1603     if (!D->getDeclName()) continue;
1604 
1605     // Diagnose unused variables in this scope.
1606     if (!S->hasUnrecoverableErrorOccurred()) {
1607       DiagnoseUnusedDecl(D);
1608       if (const auto *RD = dyn_cast<RecordDecl>(D))
1609         DiagnoseUnusedNestedTypedefs(RD);
1610     }
1611 
1612     // If this was a forward reference to a label, verify it was defined.
1613     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1614       CheckPoppedLabel(LD, *this);
1615 
1616     // Remove this name from our lexical scope.
1617     IdResolver.RemoveDecl(D);
1618   }
1619 }
1620 
1621 /// \brief Look for an Objective-C class in the translation unit.
1622 ///
1623 /// \param Id The name of the Objective-C class we're looking for. If
1624 /// typo-correction fixes this name, the Id will be updated
1625 /// to the fixed name.
1626 ///
1627 /// \param IdLoc The location of the name in the translation unit.
1628 ///
1629 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1630 /// if there is no class with the given name.
1631 ///
1632 /// \returns The declaration of the named Objective-C class, or NULL if the
1633 /// class could not be found.
1634 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1635                                               SourceLocation IdLoc,
1636                                               bool DoTypoCorrection) {
1637   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1638   // creation from this context.
1639   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1640 
1641   if (!IDecl && DoTypoCorrection) {
1642     // Perform typo correction at the given location, but only if we
1643     // find an Objective-C class name.
1644     if (TypoCorrection C = CorrectTypo(
1645             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1646             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1647             CTK_ErrorRecovery)) {
1648       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1649       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1650       Id = IDecl->getIdentifier();
1651     }
1652   }
1653   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1654   // This routine must always return a class definition, if any.
1655   if (Def && Def->getDefinition())
1656       Def = Def->getDefinition();
1657   return Def;
1658 }
1659 
1660 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1661 /// from S, where a non-field would be declared. This routine copes
1662 /// with the difference between C and C++ scoping rules in structs and
1663 /// unions. For example, the following code is well-formed in C but
1664 /// ill-formed in C++:
1665 /// @code
1666 /// struct S6 {
1667 ///   enum { BAR } e;
1668 /// };
1669 ///
1670 /// void test_S6() {
1671 ///   struct S6 a;
1672 ///   a.e = BAR;
1673 /// }
1674 /// @endcode
1675 /// For the declaration of BAR, this routine will return a different
1676 /// scope. The scope S will be the scope of the unnamed enumeration
1677 /// within S6. In C++, this routine will return the scope associated
1678 /// with S6, because the enumeration's scope is a transparent
1679 /// context but structures can contain non-field names. In C, this
1680 /// routine will return the translation unit scope, since the
1681 /// enumeration's scope is a transparent context and structures cannot
1682 /// contain non-field names.
1683 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1684   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1685          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1686          (S->isClassScope() && !getLangOpts().CPlusPlus))
1687     S = S->getParent();
1688   return S;
1689 }
1690 
1691 /// \brief Looks up the declaration of "struct objc_super" and
1692 /// saves it for later use in building builtin declaration of
1693 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1694 /// pre-existing declaration exists no action takes place.
1695 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1696                                         IdentifierInfo *II) {
1697   if (!II->isStr("objc_msgSendSuper"))
1698     return;
1699   ASTContext &Context = ThisSema.Context;
1700 
1701   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1702                       SourceLocation(), Sema::LookupTagName);
1703   ThisSema.LookupName(Result, S);
1704   if (Result.getResultKind() == LookupResult::Found)
1705     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1706       Context.setObjCSuperType(Context.getTagDeclType(TD));
1707 }
1708 
1709 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1710   switch (Error) {
1711   case ASTContext::GE_None:
1712     return "";
1713   case ASTContext::GE_Missing_stdio:
1714     return "stdio.h";
1715   case ASTContext::GE_Missing_setjmp:
1716     return "setjmp.h";
1717   case ASTContext::GE_Missing_ucontext:
1718     return "ucontext.h";
1719   }
1720   llvm_unreachable("unhandled error kind");
1721 }
1722 
1723 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1724 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1725 /// if we're creating this built-in in anticipation of redeclaring the
1726 /// built-in.
1727 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1728                                      Scope *S, bool ForRedeclaration,
1729                                      SourceLocation Loc) {
1730   LookupPredefedObjCSuperType(*this, S, II);
1731 
1732   ASTContext::GetBuiltinTypeError Error;
1733   QualType R = Context.GetBuiltinType(ID, Error);
1734   if (Error) {
1735     if (ForRedeclaration)
1736       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1737           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1738     return nullptr;
1739   }
1740 
1741   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1742     Diag(Loc, diag::ext_implicit_lib_function_decl)
1743         << Context.BuiltinInfo.getName(ID) << R;
1744     if (Context.BuiltinInfo.getHeaderName(ID) &&
1745         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1746       Diag(Loc, diag::note_include_header_or_declare)
1747           << Context.BuiltinInfo.getHeaderName(ID)
1748           << Context.BuiltinInfo.getName(ID);
1749   }
1750 
1751   if (R.isNull())
1752     return nullptr;
1753 
1754   DeclContext *Parent = Context.getTranslationUnitDecl();
1755   if (getLangOpts().CPlusPlus) {
1756     LinkageSpecDecl *CLinkageDecl =
1757         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1758                                 LinkageSpecDecl::lang_c, false);
1759     CLinkageDecl->setImplicit();
1760     Parent->addDecl(CLinkageDecl);
1761     Parent = CLinkageDecl;
1762   }
1763 
1764   FunctionDecl *New = FunctionDecl::Create(Context,
1765                                            Parent,
1766                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1767                                            SC_Extern,
1768                                            false,
1769                                            R->isFunctionProtoType());
1770   New->setImplicit();
1771 
1772   // Create Decl objects for each parameter, adding them to the
1773   // FunctionDecl.
1774   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1775     SmallVector<ParmVarDecl*, 16> Params;
1776     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1777       ParmVarDecl *parm =
1778           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1779                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1780                               SC_None, nullptr);
1781       parm->setScopeInfo(0, i);
1782       Params.push_back(parm);
1783     }
1784     New->setParams(Params);
1785   }
1786 
1787   AddKnownFunctionAttributes(New);
1788   RegisterLocallyScopedExternCDecl(New, S);
1789 
1790   // TUScope is the translation-unit scope to insert this function into.
1791   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1792   // relate Scopes to DeclContexts, and probably eliminate CurContext
1793   // entirely, but we're not there yet.
1794   DeclContext *SavedContext = CurContext;
1795   CurContext = Parent;
1796   PushOnScopeChains(New, TUScope);
1797   CurContext = SavedContext;
1798   return New;
1799 }
1800 
1801 /// Typedef declarations don't have linkage, but they still denote the same
1802 /// entity if their types are the same.
1803 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1804 /// isSameEntity.
1805 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1806                                                      TypedefNameDecl *Decl,
1807                                                      LookupResult &Previous) {
1808   // This is only interesting when modules are enabled.
1809   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1810     return;
1811 
1812   // Empty sets are uninteresting.
1813   if (Previous.empty())
1814     return;
1815 
1816   LookupResult::Filter Filter = Previous.makeFilter();
1817   while (Filter.hasNext()) {
1818     NamedDecl *Old = Filter.next();
1819 
1820     // Non-hidden declarations are never ignored.
1821     if (S.isVisible(Old))
1822       continue;
1823 
1824     // Declarations of the same entity are not ignored, even if they have
1825     // different linkages.
1826     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1827       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1828                                 Decl->getUnderlyingType()))
1829         continue;
1830 
1831       // If both declarations give a tag declaration a typedef name for linkage
1832       // purposes, then they declare the same entity.
1833       if (S.getLangOpts().CPlusPlus &&
1834           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1835           Decl->getAnonDeclWithTypedefName())
1836         continue;
1837     }
1838 
1839     Filter.erase();
1840   }
1841 
1842   Filter.done();
1843 }
1844 
1845 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1846   QualType OldType;
1847   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1848     OldType = OldTypedef->getUnderlyingType();
1849   else
1850     OldType = Context.getTypeDeclType(Old);
1851   QualType NewType = New->getUnderlyingType();
1852 
1853   if (NewType->isVariablyModifiedType()) {
1854     // Must not redefine a typedef with a variably-modified type.
1855     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1856     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1857       << Kind << NewType;
1858     if (Old->getLocation().isValid())
1859       Diag(Old->getLocation(), diag::note_previous_definition);
1860     New->setInvalidDecl();
1861     return true;
1862   }
1863 
1864   if (OldType != NewType &&
1865       !OldType->isDependentType() &&
1866       !NewType->isDependentType() &&
1867       !Context.hasSameType(OldType, NewType)) {
1868     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1869     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1870       << Kind << NewType << OldType;
1871     if (Old->getLocation().isValid())
1872       Diag(Old->getLocation(), diag::note_previous_definition);
1873     New->setInvalidDecl();
1874     return true;
1875   }
1876   return false;
1877 }
1878 
1879 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1880 /// same name and scope as a previous declaration 'Old'.  Figure out
1881 /// how to resolve this situation, merging decls or emitting
1882 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1883 ///
1884 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1885                                 LookupResult &OldDecls) {
1886   // If the new decl is known invalid already, don't bother doing any
1887   // merging checks.
1888   if (New->isInvalidDecl()) return;
1889 
1890   // Allow multiple definitions for ObjC built-in typedefs.
1891   // FIXME: Verify the underlying types are equivalent!
1892   if (getLangOpts().ObjC1) {
1893     const IdentifierInfo *TypeID = New->getIdentifier();
1894     switch (TypeID->getLength()) {
1895     default: break;
1896     case 2:
1897       {
1898         if (!TypeID->isStr("id"))
1899           break;
1900         QualType T = New->getUnderlyingType();
1901         if (!T->isPointerType())
1902           break;
1903         if (!T->isVoidPointerType()) {
1904           QualType PT = T->getAs<PointerType>()->getPointeeType();
1905           if (!PT->isStructureType())
1906             break;
1907         }
1908         Context.setObjCIdRedefinitionType(T);
1909         // Install the built-in type for 'id', ignoring the current definition.
1910         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1911         return;
1912       }
1913     case 5:
1914       if (!TypeID->isStr("Class"))
1915         break;
1916       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1917       // Install the built-in type for 'Class', ignoring the current definition.
1918       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1919       return;
1920     case 3:
1921       if (!TypeID->isStr("SEL"))
1922         break;
1923       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1924       // Install the built-in type for 'SEL', ignoring the current definition.
1925       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1926       return;
1927     }
1928     // Fall through - the typedef name was not a builtin type.
1929   }
1930 
1931   // Verify the old decl was also a type.
1932   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1933   if (!Old) {
1934     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1935       << New->getDeclName();
1936 
1937     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1938     if (OldD->getLocation().isValid())
1939       Diag(OldD->getLocation(), diag::note_previous_definition);
1940 
1941     return New->setInvalidDecl();
1942   }
1943 
1944   // If the old declaration is invalid, just give up here.
1945   if (Old->isInvalidDecl())
1946     return New->setInvalidDecl();
1947 
1948   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1949     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1950     auto *NewTag = New->getAnonDeclWithTypedefName();
1951     NamedDecl *Hidden = nullptr;
1952     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1953         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1954         !hasVisibleDefinition(OldTag, &Hidden)) {
1955       // There is a definition of this tag, but it is not visible. Use it
1956       // instead of our tag.
1957       New->setTypeForDecl(OldTD->getTypeForDecl());
1958       if (OldTD->isModed())
1959         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1960                                     OldTD->getUnderlyingType());
1961       else
1962         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1963 
1964       // Make the old tag definition visible.
1965       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1966 
1967       // If this was an unscoped enumeration, yank all of its enumerators
1968       // out of the scope.
1969       if (isa<EnumDecl>(NewTag)) {
1970         Scope *EnumScope = getNonFieldDeclScope(S);
1971         for (auto *D : NewTag->decls()) {
1972           auto *ED = cast<EnumConstantDecl>(D);
1973           assert(EnumScope->isDeclScope(ED));
1974           EnumScope->RemoveDecl(ED);
1975           IdResolver.RemoveDecl(ED);
1976           ED->getLexicalDeclContext()->removeDecl(ED);
1977         }
1978       }
1979     }
1980   }
1981 
1982   // If the typedef types are not identical, reject them in all languages and
1983   // with any extensions enabled.
1984   if (isIncompatibleTypedef(Old, New))
1985     return;
1986 
1987   // The types match.  Link up the redeclaration chain and merge attributes if
1988   // the old declaration was a typedef.
1989   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1990     New->setPreviousDecl(Typedef);
1991     mergeDeclAttributes(New, Old);
1992   }
1993 
1994   if (getLangOpts().MicrosoftExt)
1995     return;
1996 
1997   if (getLangOpts().CPlusPlus) {
1998     // C++ [dcl.typedef]p2:
1999     //   In a given non-class scope, a typedef specifier can be used to
2000     //   redefine the name of any type declared in that scope to refer
2001     //   to the type to which it already refers.
2002     if (!isa<CXXRecordDecl>(CurContext))
2003       return;
2004 
2005     // C++0x [dcl.typedef]p4:
2006     //   In a given class scope, a typedef specifier can be used to redefine
2007     //   any class-name declared in that scope that is not also a typedef-name
2008     //   to refer to the type to which it already refers.
2009     //
2010     // This wording came in via DR424, which was a correction to the
2011     // wording in DR56, which accidentally banned code like:
2012     //
2013     //   struct S {
2014     //     typedef struct A { } A;
2015     //   };
2016     //
2017     // in the C++03 standard. We implement the C++0x semantics, which
2018     // allow the above but disallow
2019     //
2020     //   struct S {
2021     //     typedef int I;
2022     //     typedef int I;
2023     //   };
2024     //
2025     // since that was the intent of DR56.
2026     if (!isa<TypedefNameDecl>(Old))
2027       return;
2028 
2029     Diag(New->getLocation(), diag::err_redefinition)
2030       << New->getDeclName();
2031     Diag(Old->getLocation(), diag::note_previous_definition);
2032     return New->setInvalidDecl();
2033   }
2034 
2035   // Modules always permit redefinition of typedefs, as does C11.
2036   if (getLangOpts().Modules || getLangOpts().C11)
2037     return;
2038 
2039   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2040   // is normally mapped to an error, but can be controlled with
2041   // -Wtypedef-redefinition.  If either the original or the redefinition is
2042   // in a system header, don't emit this for compatibility with GCC.
2043   if (getDiagnostics().getSuppressSystemWarnings() &&
2044       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2045        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2046     return;
2047 
2048   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2049     << New->getDeclName();
2050   Diag(Old->getLocation(), diag::note_previous_definition);
2051 }
2052 
2053 /// DeclhasAttr - returns true if decl Declaration already has the target
2054 /// attribute.
2055 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2056   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2057   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2058   for (const auto *i : D->attrs())
2059     if (i->getKind() == A->getKind()) {
2060       if (Ann) {
2061         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2062           return true;
2063         continue;
2064       }
2065       // FIXME: Don't hardcode this check
2066       if (OA && isa<OwnershipAttr>(i))
2067         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2068       return true;
2069     }
2070 
2071   return false;
2072 }
2073 
2074 static bool isAttributeTargetADefinition(Decl *D) {
2075   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2076     return VD->isThisDeclarationADefinition();
2077   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2078     return TD->isCompleteDefinition() || TD->isBeingDefined();
2079   return true;
2080 }
2081 
2082 /// Merge alignment attributes from \p Old to \p New, taking into account the
2083 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2084 ///
2085 /// \return \c true if any attributes were added to \p New.
2086 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2087   // Look for alignas attributes on Old, and pick out whichever attribute
2088   // specifies the strictest alignment requirement.
2089   AlignedAttr *OldAlignasAttr = nullptr;
2090   AlignedAttr *OldStrictestAlignAttr = nullptr;
2091   unsigned OldAlign = 0;
2092   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2093     // FIXME: We have no way of representing inherited dependent alignments
2094     // in a case like:
2095     //   template<int A, int B> struct alignas(A) X;
2096     //   template<int A, int B> struct alignas(B) X {};
2097     // For now, we just ignore any alignas attributes which are not on the
2098     // definition in such a case.
2099     if (I->isAlignmentDependent())
2100       return false;
2101 
2102     if (I->isAlignas())
2103       OldAlignasAttr = I;
2104 
2105     unsigned Align = I->getAlignment(S.Context);
2106     if (Align > OldAlign) {
2107       OldAlign = Align;
2108       OldStrictestAlignAttr = I;
2109     }
2110   }
2111 
2112   // Look for alignas attributes on New.
2113   AlignedAttr *NewAlignasAttr = nullptr;
2114   unsigned NewAlign = 0;
2115   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2116     if (I->isAlignmentDependent())
2117       return false;
2118 
2119     if (I->isAlignas())
2120       NewAlignasAttr = I;
2121 
2122     unsigned Align = I->getAlignment(S.Context);
2123     if (Align > NewAlign)
2124       NewAlign = Align;
2125   }
2126 
2127   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2128     // Both declarations have 'alignas' attributes. We require them to match.
2129     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2130     // fall short. (If two declarations both have alignas, they must both match
2131     // every definition, and so must match each other if there is a definition.)
2132 
2133     // If either declaration only contains 'alignas(0)' specifiers, then it
2134     // specifies the natural alignment for the type.
2135     if (OldAlign == 0 || NewAlign == 0) {
2136       QualType Ty;
2137       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2138         Ty = VD->getType();
2139       else
2140         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2141 
2142       if (OldAlign == 0)
2143         OldAlign = S.Context.getTypeAlign(Ty);
2144       if (NewAlign == 0)
2145         NewAlign = S.Context.getTypeAlign(Ty);
2146     }
2147 
2148     if (OldAlign != NewAlign) {
2149       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2150         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2151         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2152       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2153     }
2154   }
2155 
2156   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2157     // C++11 [dcl.align]p6:
2158     //   if any declaration of an entity has an alignment-specifier,
2159     //   every defining declaration of that entity shall specify an
2160     //   equivalent alignment.
2161     // C11 6.7.5/7:
2162     //   If the definition of an object does not have an alignment
2163     //   specifier, any other declaration of that object shall also
2164     //   have no alignment specifier.
2165     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2166       << OldAlignasAttr;
2167     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2168       << OldAlignasAttr;
2169   }
2170 
2171   bool AnyAdded = false;
2172 
2173   // Ensure we have an attribute representing the strictest alignment.
2174   if (OldAlign > NewAlign) {
2175     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2176     Clone->setInherited(true);
2177     New->addAttr(Clone);
2178     AnyAdded = true;
2179   }
2180 
2181   // Ensure we have an alignas attribute if the old declaration had one.
2182   if (OldAlignasAttr && !NewAlignasAttr &&
2183       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2184     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2185     Clone->setInherited(true);
2186     New->addAttr(Clone);
2187     AnyAdded = true;
2188   }
2189 
2190   return AnyAdded;
2191 }
2192 
2193 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2194                                const InheritableAttr *Attr,
2195                                Sema::AvailabilityMergeKind AMK) {
2196   InheritableAttr *NewAttr = nullptr;
2197   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2198   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2199     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2200                                       AA->getIntroduced(), AA->getDeprecated(),
2201                                       AA->getObsoleted(), AA->getUnavailable(),
2202                                       AA->getMessage(), AMK,
2203                                       AttrSpellingListIndex);
2204   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2205     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2206                                     AttrSpellingListIndex);
2207   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2208     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2209                                         AttrSpellingListIndex);
2210   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2211     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2212                                    AttrSpellingListIndex);
2213   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2214     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2215                                    AttrSpellingListIndex);
2216   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2217     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2218                                 FA->getFormatIdx(), FA->getFirstArg(),
2219                                 AttrSpellingListIndex);
2220   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2221     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2222                                  AttrSpellingListIndex);
2223   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2224     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2225                                        AttrSpellingListIndex,
2226                                        IA->getSemanticSpelling());
2227   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2228     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2229                                       &S.Context.Idents.get(AA->getSpelling()),
2230                                       AttrSpellingListIndex);
2231   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2232     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2233   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2234     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2235   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2236     NewAttr = S.mergeInternalLinkageAttr(
2237         D, InternalLinkageA->getRange(),
2238         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2239         AttrSpellingListIndex);
2240   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2241     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2242                                 &S.Context.Idents.get(CommonA->getSpelling()),
2243                                 AttrSpellingListIndex);
2244   else if (isa<AlignedAttr>(Attr))
2245     // AlignedAttrs are handled separately, because we need to handle all
2246     // such attributes on a declaration at the same time.
2247     NewAttr = nullptr;
2248   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2249            (AMK == Sema::AMK_Override ||
2250             AMK == Sema::AMK_ProtocolImplementation))
2251     NewAttr = nullptr;
2252   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2253     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2254 
2255   if (NewAttr) {
2256     NewAttr->setInherited(true);
2257     D->addAttr(NewAttr);
2258     if (isa<MSInheritanceAttr>(NewAttr))
2259       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2260     return true;
2261   }
2262 
2263   return false;
2264 }
2265 
2266 static const Decl *getDefinition(const Decl *D) {
2267   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2268     return TD->getDefinition();
2269   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2270     const VarDecl *Def = VD->getDefinition();
2271     if (Def)
2272       return Def;
2273     return VD->getActingDefinition();
2274   }
2275   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2276     const FunctionDecl* Def;
2277     if (FD->isDefined(Def))
2278       return Def;
2279   }
2280   return nullptr;
2281 }
2282 
2283 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2284   for (const auto *Attribute : D->attrs())
2285     if (Attribute->getKind() == Kind)
2286       return true;
2287   return false;
2288 }
2289 
2290 /// checkNewAttributesAfterDef - If we already have a definition, check that
2291 /// there are no new attributes in this declaration.
2292 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2293   if (!New->hasAttrs())
2294     return;
2295 
2296   const Decl *Def = getDefinition(Old);
2297   if (!Def || Def == New)
2298     return;
2299 
2300   AttrVec &NewAttributes = New->getAttrs();
2301   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2302     const Attr *NewAttribute = NewAttributes[I];
2303 
2304     if (isa<AliasAttr>(NewAttribute)) {
2305       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2306         Sema::SkipBodyInfo SkipBody;
2307         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2308 
2309         // If we're skipping this definition, drop the "alias" attribute.
2310         if (SkipBody.ShouldSkip) {
2311           NewAttributes.erase(NewAttributes.begin() + I);
2312           --E;
2313           continue;
2314         }
2315       } else {
2316         VarDecl *VD = cast<VarDecl>(New);
2317         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2318                                 VarDecl::TentativeDefinition
2319                             ? diag::err_alias_after_tentative
2320                             : diag::err_redefinition;
2321         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2322         S.Diag(Def->getLocation(), diag::note_previous_definition);
2323         VD->setInvalidDecl();
2324       }
2325       ++I;
2326       continue;
2327     }
2328 
2329     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2330       // Tentative definitions are only interesting for the alias check above.
2331       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2332         ++I;
2333         continue;
2334       }
2335     }
2336 
2337     if (hasAttribute(Def, NewAttribute->getKind())) {
2338       ++I;
2339       continue; // regular attr merging will take care of validating this.
2340     }
2341 
2342     if (isa<C11NoReturnAttr>(NewAttribute)) {
2343       // C's _Noreturn is allowed to be added to a function after it is defined.
2344       ++I;
2345       continue;
2346     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2347       if (AA->isAlignas()) {
2348         // C++11 [dcl.align]p6:
2349         //   if any declaration of an entity has an alignment-specifier,
2350         //   every defining declaration of that entity shall specify an
2351         //   equivalent alignment.
2352         // C11 6.7.5/7:
2353         //   If the definition of an object does not have an alignment
2354         //   specifier, any other declaration of that object shall also
2355         //   have no alignment specifier.
2356         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2357           << AA;
2358         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2359           << AA;
2360         NewAttributes.erase(NewAttributes.begin() + I);
2361         --E;
2362         continue;
2363       }
2364     }
2365 
2366     S.Diag(NewAttribute->getLocation(),
2367            diag::warn_attribute_precede_definition);
2368     S.Diag(Def->getLocation(), diag::note_previous_definition);
2369     NewAttributes.erase(NewAttributes.begin() + I);
2370     --E;
2371   }
2372 }
2373 
2374 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2375 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2376                                AvailabilityMergeKind AMK) {
2377   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2378     UsedAttr *NewAttr = OldAttr->clone(Context);
2379     NewAttr->setInherited(true);
2380     New->addAttr(NewAttr);
2381   }
2382 
2383   if (!Old->hasAttrs() && !New->hasAttrs())
2384     return;
2385 
2386   // Attributes declared post-definition are currently ignored.
2387   checkNewAttributesAfterDef(*this, New, Old);
2388 
2389   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2390     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2391       if (OldA->getLabel() != NewA->getLabel()) {
2392         // This redeclaration changes __asm__ label.
2393         Diag(New->getLocation(), diag::err_different_asm_label);
2394         Diag(OldA->getLocation(), diag::note_previous_declaration);
2395       }
2396     } else if (Old->isUsed()) {
2397       // This redeclaration adds an __asm__ label to a declaration that has
2398       // already been ODR-used.
2399       Diag(New->getLocation(), diag::err_late_asm_label_name)
2400         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2401     }
2402   }
2403 
2404   if (!Old->hasAttrs())
2405     return;
2406 
2407   bool foundAny = New->hasAttrs();
2408 
2409   // Ensure that any moving of objects within the allocated map is done before
2410   // we process them.
2411   if (!foundAny) New->setAttrs(AttrVec());
2412 
2413   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2414     // Ignore deprecated/unavailable/availability attributes if requested.
2415     AvailabilityMergeKind LocalAMK = AMK_None;
2416     if (isa<DeprecatedAttr>(I) ||
2417         isa<UnavailableAttr>(I) ||
2418         isa<AvailabilityAttr>(I)) {
2419       switch (AMK) {
2420       case AMK_None:
2421         continue;
2422 
2423       case AMK_Redeclaration:
2424       case AMK_Override:
2425       case AMK_ProtocolImplementation:
2426         LocalAMK = AMK;
2427         break;
2428       }
2429     }
2430 
2431     // Already handled.
2432     if (isa<UsedAttr>(I))
2433       continue;
2434 
2435     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2436       foundAny = true;
2437   }
2438 
2439   if (mergeAlignedAttrs(*this, New, Old))
2440     foundAny = true;
2441 
2442   if (!foundAny) New->dropAttrs();
2443 }
2444 
2445 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2446 /// to the new one.
2447 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2448                                      const ParmVarDecl *oldDecl,
2449                                      Sema &S) {
2450   // C++11 [dcl.attr.depend]p2:
2451   //   The first declaration of a function shall specify the
2452   //   carries_dependency attribute for its declarator-id if any declaration
2453   //   of the function specifies the carries_dependency attribute.
2454   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2455   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2456     S.Diag(CDA->getLocation(),
2457            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2458     // Find the first declaration of the parameter.
2459     // FIXME: Should we build redeclaration chains for function parameters?
2460     const FunctionDecl *FirstFD =
2461       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2462     const ParmVarDecl *FirstVD =
2463       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2464     S.Diag(FirstVD->getLocation(),
2465            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2466   }
2467 
2468   if (!oldDecl->hasAttrs())
2469     return;
2470 
2471   bool foundAny = newDecl->hasAttrs();
2472 
2473   // Ensure that any moving of objects within the allocated map is
2474   // done before we process them.
2475   if (!foundAny) newDecl->setAttrs(AttrVec());
2476 
2477   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2478     if (!DeclHasAttr(newDecl, I)) {
2479       InheritableAttr *newAttr =
2480         cast<InheritableParamAttr>(I->clone(S.Context));
2481       newAttr->setInherited(true);
2482       newDecl->addAttr(newAttr);
2483       foundAny = true;
2484     }
2485   }
2486 
2487   if (!foundAny) newDecl->dropAttrs();
2488 }
2489 
2490 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2491                                 const ParmVarDecl *OldParam,
2492                                 Sema &S) {
2493   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2494     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2495       if (*Oldnullability != *Newnullability) {
2496         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2497           << DiagNullabilityKind(
2498                *Newnullability,
2499                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2500                 != 0))
2501           << DiagNullabilityKind(
2502                *Oldnullability,
2503                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2504                 != 0));
2505         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2506       }
2507     } else {
2508       QualType NewT = NewParam->getType();
2509       NewT = S.Context.getAttributedType(
2510                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2511                          NewT, NewT);
2512       NewParam->setType(NewT);
2513     }
2514   }
2515 }
2516 
2517 namespace {
2518 
2519 /// Used in MergeFunctionDecl to keep track of function parameters in
2520 /// C.
2521 struct GNUCompatibleParamWarning {
2522   ParmVarDecl *OldParm;
2523   ParmVarDecl *NewParm;
2524   QualType PromotedType;
2525 };
2526 
2527 }
2528 
2529 /// getSpecialMember - get the special member enum for a method.
2530 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2531   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2532     if (Ctor->isDefaultConstructor())
2533       return Sema::CXXDefaultConstructor;
2534 
2535     if (Ctor->isCopyConstructor())
2536       return Sema::CXXCopyConstructor;
2537 
2538     if (Ctor->isMoveConstructor())
2539       return Sema::CXXMoveConstructor;
2540   } else if (isa<CXXDestructorDecl>(MD)) {
2541     return Sema::CXXDestructor;
2542   } else if (MD->isCopyAssignmentOperator()) {
2543     return Sema::CXXCopyAssignment;
2544   } else if (MD->isMoveAssignmentOperator()) {
2545     return Sema::CXXMoveAssignment;
2546   }
2547 
2548   return Sema::CXXInvalid;
2549 }
2550 
2551 // Determine whether the previous declaration was a definition, implicit
2552 // declaration, or a declaration.
2553 template <typename T>
2554 static std::pair<diag::kind, SourceLocation>
2555 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2556   diag::kind PrevDiag;
2557   SourceLocation OldLocation = Old->getLocation();
2558   if (Old->isThisDeclarationADefinition())
2559     PrevDiag = diag::note_previous_definition;
2560   else if (Old->isImplicit()) {
2561     PrevDiag = diag::note_previous_implicit_declaration;
2562     if (OldLocation.isInvalid())
2563       OldLocation = New->getLocation();
2564   } else
2565     PrevDiag = diag::note_previous_declaration;
2566   return std::make_pair(PrevDiag, OldLocation);
2567 }
2568 
2569 /// canRedefineFunction - checks if a function can be redefined. Currently,
2570 /// only extern inline functions can be redefined, and even then only in
2571 /// GNU89 mode.
2572 static bool canRedefineFunction(const FunctionDecl *FD,
2573                                 const LangOptions& LangOpts) {
2574   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2575           !LangOpts.CPlusPlus &&
2576           FD->isInlineSpecified() &&
2577           FD->getStorageClass() == SC_Extern);
2578 }
2579 
2580 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2581   const AttributedType *AT = T->getAs<AttributedType>();
2582   while (AT && !AT->isCallingConv())
2583     AT = AT->getModifiedType()->getAs<AttributedType>();
2584   return AT;
2585 }
2586 
2587 template <typename T>
2588 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2589   const DeclContext *DC = Old->getDeclContext();
2590   if (DC->isRecord())
2591     return false;
2592 
2593   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2594   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2595     return true;
2596   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2597     return true;
2598   return false;
2599 }
2600 
2601 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2602 static bool isExternC(VarTemplateDecl *) { return false; }
2603 
2604 /// \brief Check whether a redeclaration of an entity introduced by a
2605 /// using-declaration is valid, given that we know it's not an overload
2606 /// (nor a hidden tag declaration).
2607 template<typename ExpectedDecl>
2608 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2609                                    ExpectedDecl *New) {
2610   // C++11 [basic.scope.declarative]p4:
2611   //   Given a set of declarations in a single declarative region, each of
2612   //   which specifies the same unqualified name,
2613   //   -- they shall all refer to the same entity, or all refer to functions
2614   //      and function templates; or
2615   //   -- exactly one declaration shall declare a class name or enumeration
2616   //      name that is not a typedef name and the other declarations shall all
2617   //      refer to the same variable or enumerator, or all refer to functions
2618   //      and function templates; in this case the class name or enumeration
2619   //      name is hidden (3.3.10).
2620 
2621   // C++11 [namespace.udecl]p14:
2622   //   If a function declaration in namespace scope or block scope has the
2623   //   same name and the same parameter-type-list as a function introduced
2624   //   by a using-declaration, and the declarations do not declare the same
2625   //   function, the program is ill-formed.
2626 
2627   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2628   if (Old &&
2629       !Old->getDeclContext()->getRedeclContext()->Equals(
2630           New->getDeclContext()->getRedeclContext()) &&
2631       !(isExternC(Old) && isExternC(New)))
2632     Old = nullptr;
2633 
2634   if (!Old) {
2635     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2636     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2637     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2638     return true;
2639   }
2640   return false;
2641 }
2642 
2643 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2644                                             const FunctionDecl *B) {
2645   assert(A->getNumParams() == B->getNumParams());
2646 
2647   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2648     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2649     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2650     if (AttrA == AttrB)
2651       return true;
2652     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2653   };
2654 
2655   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2656 }
2657 
2658 /// MergeFunctionDecl - We just parsed a function 'New' from
2659 /// declarator D which has the same name and scope as a previous
2660 /// declaration 'Old'.  Figure out how to resolve this situation,
2661 /// merging decls or emitting diagnostics as appropriate.
2662 ///
2663 /// In C++, New and Old must be declarations that are not
2664 /// overloaded. Use IsOverload to determine whether New and Old are
2665 /// overloaded, and to select the Old declaration that New should be
2666 /// merged with.
2667 ///
2668 /// Returns true if there was an error, false otherwise.
2669 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2670                              Scope *S, bool MergeTypeWithOld) {
2671   // Verify the old decl was also a function.
2672   FunctionDecl *Old = OldD->getAsFunction();
2673   if (!Old) {
2674     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2675       if (New->getFriendObjectKind()) {
2676         Diag(New->getLocation(), diag::err_using_decl_friend);
2677         Diag(Shadow->getTargetDecl()->getLocation(),
2678              diag::note_using_decl_target);
2679         Diag(Shadow->getUsingDecl()->getLocation(),
2680              diag::note_using_decl) << 0;
2681         return true;
2682       }
2683 
2684       // Check whether the two declarations might declare the same function.
2685       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2686         return true;
2687       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2688     } else {
2689       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2690         << New->getDeclName();
2691       Diag(OldD->getLocation(), diag::note_previous_definition);
2692       return true;
2693     }
2694   }
2695 
2696   // If the old declaration is invalid, just give up here.
2697   if (Old->isInvalidDecl())
2698     return true;
2699 
2700   diag::kind PrevDiag;
2701   SourceLocation OldLocation;
2702   std::tie(PrevDiag, OldLocation) =
2703       getNoteDiagForInvalidRedeclaration(Old, New);
2704 
2705   // Don't complain about this if we're in GNU89 mode and the old function
2706   // is an extern inline function.
2707   // Don't complain about specializations. They are not supposed to have
2708   // storage classes.
2709   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2710       New->getStorageClass() == SC_Static &&
2711       Old->hasExternalFormalLinkage() &&
2712       !New->getTemplateSpecializationInfo() &&
2713       !canRedefineFunction(Old, getLangOpts())) {
2714     if (getLangOpts().MicrosoftExt) {
2715       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2716       Diag(OldLocation, PrevDiag);
2717     } else {
2718       Diag(New->getLocation(), diag::err_static_non_static) << New;
2719       Diag(OldLocation, PrevDiag);
2720       return true;
2721     }
2722   }
2723 
2724   if (New->hasAttr<InternalLinkageAttr>() &&
2725       !Old->hasAttr<InternalLinkageAttr>()) {
2726     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2727         << New->getDeclName();
2728     Diag(Old->getLocation(), diag::note_previous_definition);
2729     New->dropAttr<InternalLinkageAttr>();
2730   }
2731 
2732   // If a function is first declared with a calling convention, but is later
2733   // declared or defined without one, all following decls assume the calling
2734   // convention of the first.
2735   //
2736   // It's OK if a function is first declared without a calling convention,
2737   // but is later declared or defined with the default calling convention.
2738   //
2739   // To test if either decl has an explicit calling convention, we look for
2740   // AttributedType sugar nodes on the type as written.  If they are missing or
2741   // were canonicalized away, we assume the calling convention was implicit.
2742   //
2743   // Note also that we DO NOT return at this point, because we still have
2744   // other tests to run.
2745   QualType OldQType = Context.getCanonicalType(Old->getType());
2746   QualType NewQType = Context.getCanonicalType(New->getType());
2747   const FunctionType *OldType = cast<FunctionType>(OldQType);
2748   const FunctionType *NewType = cast<FunctionType>(NewQType);
2749   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2750   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2751   bool RequiresAdjustment = false;
2752 
2753   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2754     FunctionDecl *First = Old->getFirstDecl();
2755     const FunctionType *FT =
2756         First->getType().getCanonicalType()->castAs<FunctionType>();
2757     FunctionType::ExtInfo FI = FT->getExtInfo();
2758     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2759     if (!NewCCExplicit) {
2760       // Inherit the CC from the previous declaration if it was specified
2761       // there but not here.
2762       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2763       RequiresAdjustment = true;
2764     } else {
2765       // Calling conventions aren't compatible, so complain.
2766       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2767       Diag(New->getLocation(), diag::err_cconv_change)
2768         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2769         << !FirstCCExplicit
2770         << (!FirstCCExplicit ? "" :
2771             FunctionType::getNameForCallConv(FI.getCC()));
2772 
2773       // Put the note on the first decl, since it is the one that matters.
2774       Diag(First->getLocation(), diag::note_previous_declaration);
2775       return true;
2776     }
2777   }
2778 
2779   // FIXME: diagnose the other way around?
2780   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2781     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2782     RequiresAdjustment = true;
2783   }
2784 
2785   // Merge regparm attribute.
2786   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2787       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2788     if (NewTypeInfo.getHasRegParm()) {
2789       Diag(New->getLocation(), diag::err_regparm_mismatch)
2790         << NewType->getRegParmType()
2791         << OldType->getRegParmType();
2792       Diag(OldLocation, diag::note_previous_declaration);
2793       return true;
2794     }
2795 
2796     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2797     RequiresAdjustment = true;
2798   }
2799 
2800   // Merge ns_returns_retained attribute.
2801   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2802     if (NewTypeInfo.getProducesResult()) {
2803       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2804       Diag(OldLocation, diag::note_previous_declaration);
2805       return true;
2806     }
2807 
2808     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2809     RequiresAdjustment = true;
2810   }
2811 
2812   if (RequiresAdjustment) {
2813     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2814     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2815     New->setType(QualType(AdjustedType, 0));
2816     NewQType = Context.getCanonicalType(New->getType());
2817     NewType = cast<FunctionType>(NewQType);
2818   }
2819 
2820   // If this redeclaration makes the function inline, we may need to add it to
2821   // UndefinedButUsed.
2822   if (!Old->isInlined() && New->isInlined() &&
2823       !New->hasAttr<GNUInlineAttr>() &&
2824       !getLangOpts().GNUInline &&
2825       Old->isUsed(false) &&
2826       !Old->isDefined() && !New->isThisDeclarationADefinition())
2827     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2828                                            SourceLocation()));
2829 
2830   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2831   // about it.
2832   if (New->hasAttr<GNUInlineAttr>() &&
2833       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2834     UndefinedButUsed.erase(Old->getCanonicalDecl());
2835   }
2836 
2837   // If pass_object_size params don't match up perfectly, this isn't a valid
2838   // redeclaration.
2839   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2840       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2841     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2842         << New->getDeclName();
2843     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2844     return true;
2845   }
2846 
2847   if (getLangOpts().CPlusPlus) {
2848     // (C++98 13.1p2):
2849     //   Certain function declarations cannot be overloaded:
2850     //     -- Function declarations that differ only in the return type
2851     //        cannot be overloaded.
2852 
2853     // Go back to the type source info to compare the declared return types,
2854     // per C++1y [dcl.type.auto]p13:
2855     //   Redeclarations or specializations of a function or function template
2856     //   with a declared return type that uses a placeholder type shall also
2857     //   use that placeholder, not a deduced type.
2858     QualType OldDeclaredReturnType =
2859         (Old->getTypeSourceInfo()
2860              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2861              : OldType)->getReturnType();
2862     QualType NewDeclaredReturnType =
2863         (New->getTypeSourceInfo()
2864              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2865              : NewType)->getReturnType();
2866     QualType ResQT;
2867     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2868         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2869           New->isLocalExternDecl())) {
2870       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2871           OldDeclaredReturnType->isObjCObjectPointerType())
2872         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2873       if (ResQT.isNull()) {
2874         if (New->isCXXClassMember() && New->isOutOfLine())
2875           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2876               << New << New->getReturnTypeSourceRange();
2877         else
2878           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2879               << New->getReturnTypeSourceRange();
2880         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2881                                     << Old->getReturnTypeSourceRange();
2882         return true;
2883       }
2884       else
2885         NewQType = ResQT;
2886     }
2887 
2888     QualType OldReturnType = OldType->getReturnType();
2889     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2890     if (OldReturnType != NewReturnType) {
2891       // If this function has a deduced return type and has already been
2892       // defined, copy the deduced value from the old declaration.
2893       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2894       if (OldAT && OldAT->isDeduced()) {
2895         New->setType(
2896             SubstAutoType(New->getType(),
2897                           OldAT->isDependentType() ? Context.DependentTy
2898                                                    : OldAT->getDeducedType()));
2899         NewQType = Context.getCanonicalType(
2900             SubstAutoType(NewQType,
2901                           OldAT->isDependentType() ? Context.DependentTy
2902                                                    : OldAT->getDeducedType()));
2903       }
2904     }
2905 
2906     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2907     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2908     if (OldMethod && NewMethod) {
2909       // Preserve triviality.
2910       NewMethod->setTrivial(OldMethod->isTrivial());
2911 
2912       // MSVC allows explicit template specialization at class scope:
2913       // 2 CXXMethodDecls referring to the same function will be injected.
2914       // We don't want a redeclaration error.
2915       bool IsClassScopeExplicitSpecialization =
2916                               OldMethod->isFunctionTemplateSpecialization() &&
2917                               NewMethod->isFunctionTemplateSpecialization();
2918       bool isFriend = NewMethod->getFriendObjectKind();
2919 
2920       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2921           !IsClassScopeExplicitSpecialization) {
2922         //    -- Member function declarations with the same name and the
2923         //       same parameter types cannot be overloaded if any of them
2924         //       is a static member function declaration.
2925         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2926           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2927           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2928           return true;
2929         }
2930 
2931         // C++ [class.mem]p1:
2932         //   [...] A member shall not be declared twice in the
2933         //   member-specification, except that a nested class or member
2934         //   class template can be declared and then later defined.
2935         if (ActiveTemplateInstantiations.empty()) {
2936           unsigned NewDiag;
2937           if (isa<CXXConstructorDecl>(OldMethod))
2938             NewDiag = diag::err_constructor_redeclared;
2939           else if (isa<CXXDestructorDecl>(NewMethod))
2940             NewDiag = diag::err_destructor_redeclared;
2941           else if (isa<CXXConversionDecl>(NewMethod))
2942             NewDiag = diag::err_conv_function_redeclared;
2943           else
2944             NewDiag = diag::err_member_redeclared;
2945 
2946           Diag(New->getLocation(), NewDiag);
2947         } else {
2948           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2949             << New << New->getType();
2950         }
2951         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2952         return true;
2953 
2954       // Complain if this is an explicit declaration of a special
2955       // member that was initially declared implicitly.
2956       //
2957       // As an exception, it's okay to befriend such methods in order
2958       // to permit the implicit constructor/destructor/operator calls.
2959       } else if (OldMethod->isImplicit()) {
2960         if (isFriend) {
2961           NewMethod->setImplicit();
2962         } else {
2963           Diag(NewMethod->getLocation(),
2964                diag::err_definition_of_implicitly_declared_member)
2965             << New << getSpecialMember(OldMethod);
2966           return true;
2967         }
2968       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2969         Diag(NewMethod->getLocation(),
2970              diag::err_definition_of_explicitly_defaulted_member)
2971           << getSpecialMember(OldMethod);
2972         return true;
2973       }
2974     }
2975 
2976     // C++11 [dcl.attr.noreturn]p1:
2977     //   The first declaration of a function shall specify the noreturn
2978     //   attribute if any declaration of that function specifies the noreturn
2979     //   attribute.
2980     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2981     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2982       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2983       Diag(Old->getFirstDecl()->getLocation(),
2984            diag::note_noreturn_missing_first_decl);
2985     }
2986 
2987     // C++11 [dcl.attr.depend]p2:
2988     //   The first declaration of a function shall specify the
2989     //   carries_dependency attribute for its declarator-id if any declaration
2990     //   of the function specifies the carries_dependency attribute.
2991     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2992     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2993       Diag(CDA->getLocation(),
2994            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2995       Diag(Old->getFirstDecl()->getLocation(),
2996            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2997     }
2998 
2999     // (C++98 8.3.5p3):
3000     //   All declarations for a function shall agree exactly in both the
3001     //   return type and the parameter-type-list.
3002     // We also want to respect all the extended bits except noreturn.
3003 
3004     // noreturn should now match unless the old type info didn't have it.
3005     QualType OldQTypeForComparison = OldQType;
3006     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3007       assert(OldQType == QualType(OldType, 0));
3008       const FunctionType *OldTypeForComparison
3009         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3010       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3011       assert(OldQTypeForComparison.isCanonical());
3012     }
3013 
3014     if (haveIncompatibleLanguageLinkages(Old, New)) {
3015       // As a special case, retain the language linkage from previous
3016       // declarations of a friend function as an extension.
3017       //
3018       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3019       // and is useful because there's otherwise no way to specify language
3020       // linkage within class scope.
3021       //
3022       // Check cautiously as the friend object kind isn't yet complete.
3023       if (New->getFriendObjectKind() != Decl::FOK_None) {
3024         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3025         Diag(OldLocation, PrevDiag);
3026       } else {
3027         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3028         Diag(OldLocation, PrevDiag);
3029         return true;
3030       }
3031     }
3032 
3033     if (OldQTypeForComparison == NewQType)
3034       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3035 
3036     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3037         New->isLocalExternDecl()) {
3038       // It's OK if we couldn't merge types for a local function declaraton
3039       // if either the old or new type is dependent. We'll merge the types
3040       // when we instantiate the function.
3041       return false;
3042     }
3043 
3044     // Fall through for conflicting redeclarations and redefinitions.
3045   }
3046 
3047   // C: Function types need to be compatible, not identical. This handles
3048   // duplicate function decls like "void f(int); void f(enum X);" properly.
3049   if (!getLangOpts().CPlusPlus &&
3050       Context.typesAreCompatible(OldQType, NewQType)) {
3051     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3052     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3053     const FunctionProtoType *OldProto = nullptr;
3054     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3055         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3056       // The old declaration provided a function prototype, but the
3057       // new declaration does not. Merge in the prototype.
3058       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3059       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3060       NewQType =
3061           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3062                                   OldProto->getExtProtoInfo());
3063       New->setType(NewQType);
3064       New->setHasInheritedPrototype();
3065 
3066       // Synthesize parameters with the same types.
3067       SmallVector<ParmVarDecl*, 16> Params;
3068       for (const auto &ParamType : OldProto->param_types()) {
3069         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3070                                                  SourceLocation(), nullptr,
3071                                                  ParamType, /*TInfo=*/nullptr,
3072                                                  SC_None, nullptr);
3073         Param->setScopeInfo(0, Params.size());
3074         Param->setImplicit();
3075         Params.push_back(Param);
3076       }
3077 
3078       New->setParams(Params);
3079     }
3080 
3081     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3082   }
3083 
3084   // GNU C permits a K&R definition to follow a prototype declaration
3085   // if the declared types of the parameters in the K&R definition
3086   // match the types in the prototype declaration, even when the
3087   // promoted types of the parameters from the K&R definition differ
3088   // from the types in the prototype. GCC then keeps the types from
3089   // the prototype.
3090   //
3091   // If a variadic prototype is followed by a non-variadic K&R definition,
3092   // the K&R definition becomes variadic.  This is sort of an edge case, but
3093   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3094   // C99 6.9.1p8.
3095   if (!getLangOpts().CPlusPlus &&
3096       Old->hasPrototype() && !New->hasPrototype() &&
3097       New->getType()->getAs<FunctionProtoType>() &&
3098       Old->getNumParams() == New->getNumParams()) {
3099     SmallVector<QualType, 16> ArgTypes;
3100     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3101     const FunctionProtoType *OldProto
3102       = Old->getType()->getAs<FunctionProtoType>();
3103     const FunctionProtoType *NewProto
3104       = New->getType()->getAs<FunctionProtoType>();
3105 
3106     // Determine whether this is the GNU C extension.
3107     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3108                                                NewProto->getReturnType());
3109     bool LooseCompatible = !MergedReturn.isNull();
3110     for (unsigned Idx = 0, End = Old->getNumParams();
3111          LooseCompatible && Idx != End; ++Idx) {
3112       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3113       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3114       if (Context.typesAreCompatible(OldParm->getType(),
3115                                      NewProto->getParamType(Idx))) {
3116         ArgTypes.push_back(NewParm->getType());
3117       } else if (Context.typesAreCompatible(OldParm->getType(),
3118                                             NewParm->getType(),
3119                                             /*CompareUnqualified=*/true)) {
3120         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3121                                            NewProto->getParamType(Idx) };
3122         Warnings.push_back(Warn);
3123         ArgTypes.push_back(NewParm->getType());
3124       } else
3125         LooseCompatible = false;
3126     }
3127 
3128     if (LooseCompatible) {
3129       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3130         Diag(Warnings[Warn].NewParm->getLocation(),
3131              diag::ext_param_promoted_not_compatible_with_prototype)
3132           << Warnings[Warn].PromotedType
3133           << Warnings[Warn].OldParm->getType();
3134         if (Warnings[Warn].OldParm->getLocation().isValid())
3135           Diag(Warnings[Warn].OldParm->getLocation(),
3136                diag::note_previous_declaration);
3137       }
3138 
3139       if (MergeTypeWithOld)
3140         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3141                                              OldProto->getExtProtoInfo()));
3142       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3143     }
3144 
3145     // Fall through to diagnose conflicting types.
3146   }
3147 
3148   // A function that has already been declared has been redeclared or
3149   // defined with a different type; show an appropriate diagnostic.
3150 
3151   // If the previous declaration was an implicitly-generated builtin
3152   // declaration, then at the very least we should use a specialized note.
3153   unsigned BuiltinID;
3154   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3155     // If it's actually a library-defined builtin function like 'malloc'
3156     // or 'printf', just warn about the incompatible redeclaration.
3157     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3158       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3159       Diag(OldLocation, diag::note_previous_builtin_declaration)
3160         << Old << Old->getType();
3161 
3162       // If this is a global redeclaration, just forget hereafter
3163       // about the "builtin-ness" of the function.
3164       //
3165       // Doing this for local extern declarations is problematic.  If
3166       // the builtin declaration remains visible, a second invalid
3167       // local declaration will produce a hard error; if it doesn't
3168       // remain visible, a single bogus local redeclaration (which is
3169       // actually only a warning) could break all the downstream code.
3170       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3171         New->getIdentifier()->revertBuiltin();
3172 
3173       return false;
3174     }
3175 
3176     PrevDiag = diag::note_previous_builtin_declaration;
3177   }
3178 
3179   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3180   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3181   return true;
3182 }
3183 
3184 /// \brief Completes the merge of two function declarations that are
3185 /// known to be compatible.
3186 ///
3187 /// This routine handles the merging of attributes and other
3188 /// properties of function declarations from the old declaration to
3189 /// the new declaration, once we know that New is in fact a
3190 /// redeclaration of Old.
3191 ///
3192 /// \returns false
3193 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3194                                         Scope *S, bool MergeTypeWithOld) {
3195   // Merge the attributes
3196   mergeDeclAttributes(New, Old);
3197 
3198   // Merge "pure" flag.
3199   if (Old->isPure())
3200     New->setPure();
3201 
3202   // Merge "used" flag.
3203   if (Old->getMostRecentDecl()->isUsed(false))
3204     New->setIsUsed();
3205 
3206   // Merge attributes from the parameters.  These can mismatch with K&R
3207   // declarations.
3208   if (New->getNumParams() == Old->getNumParams())
3209       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3210         ParmVarDecl *NewParam = New->getParamDecl(i);
3211         ParmVarDecl *OldParam = Old->getParamDecl(i);
3212         mergeParamDeclAttributes(NewParam, OldParam, *this);
3213         mergeParamDeclTypes(NewParam, OldParam, *this);
3214       }
3215 
3216   if (getLangOpts().CPlusPlus)
3217     return MergeCXXFunctionDecl(New, Old, S);
3218 
3219   // Merge the function types so the we get the composite types for the return
3220   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3221   // was visible.
3222   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3223   if (!Merged.isNull() && MergeTypeWithOld)
3224     New->setType(Merged);
3225 
3226   return false;
3227 }
3228 
3229 
3230 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3231                                 ObjCMethodDecl *oldMethod) {
3232 
3233   // Merge the attributes, including deprecated/unavailable
3234   AvailabilityMergeKind MergeKind =
3235     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3236       ? AMK_ProtocolImplementation
3237       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3238                                                        : AMK_Override;
3239 
3240   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3241 
3242   // Merge attributes from the parameters.
3243   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3244                                        oe = oldMethod->param_end();
3245   for (ObjCMethodDecl::param_iterator
3246          ni = newMethod->param_begin(), ne = newMethod->param_end();
3247        ni != ne && oi != oe; ++ni, ++oi)
3248     mergeParamDeclAttributes(*ni, *oi, *this);
3249 
3250   CheckObjCMethodOverride(newMethod, oldMethod);
3251 }
3252 
3253 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3254 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3255 /// emitting diagnostics as appropriate.
3256 ///
3257 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3258 /// to here in AddInitializerToDecl. We can't check them before the initializer
3259 /// is attached.
3260 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3261                              bool MergeTypeWithOld) {
3262   if (New->isInvalidDecl() || Old->isInvalidDecl())
3263     return;
3264 
3265   QualType MergedT;
3266   if (getLangOpts().CPlusPlus) {
3267     if (New->getType()->isUndeducedType()) {
3268       // We don't know what the new type is until the initializer is attached.
3269       return;
3270     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3271       // These could still be something that needs exception specs checked.
3272       return MergeVarDeclExceptionSpecs(New, Old);
3273     }
3274     // C++ [basic.link]p10:
3275     //   [...] the types specified by all declarations referring to a given
3276     //   object or function shall be identical, except that declarations for an
3277     //   array object can specify array types that differ by the presence or
3278     //   absence of a major array bound (8.3.4).
3279     else if (Old->getType()->isIncompleteArrayType() &&
3280              New->getType()->isArrayType()) {
3281       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3282       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3283       if (Context.hasSameType(OldArray->getElementType(),
3284                               NewArray->getElementType()))
3285         MergedT = New->getType();
3286     } else if (Old->getType()->isArrayType() &&
3287                New->getType()->isIncompleteArrayType()) {
3288       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3289       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3290       if (Context.hasSameType(OldArray->getElementType(),
3291                               NewArray->getElementType()))
3292         MergedT = Old->getType();
3293     } else if (New->getType()->isObjCObjectPointerType() &&
3294                Old->getType()->isObjCObjectPointerType()) {
3295       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3296                                               Old->getType());
3297     }
3298   } else {
3299     // C 6.2.7p2:
3300     //   All declarations that refer to the same object or function shall have
3301     //   compatible type.
3302     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3303   }
3304   if (MergedT.isNull()) {
3305     // It's OK if we couldn't merge types if either type is dependent, for a
3306     // block-scope variable. In other cases (static data members of class
3307     // templates, variable templates, ...), we require the types to be
3308     // equivalent.
3309     // FIXME: The C++ standard doesn't say anything about this.
3310     if ((New->getType()->isDependentType() ||
3311          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3312       // If the old type was dependent, we can't merge with it, so the new type
3313       // becomes dependent for now. We'll reproduce the original type when we
3314       // instantiate the TypeSourceInfo for the variable.
3315       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3316         New->setType(Context.DependentTy);
3317       return;
3318     }
3319 
3320     // FIXME: Even if this merging succeeds, some other non-visible declaration
3321     // of this variable might have an incompatible type. For instance:
3322     //
3323     //   extern int arr[];
3324     //   void f() { extern int arr[2]; }
3325     //   void g() { extern int arr[3]; }
3326     //
3327     // Neither C nor C++ requires a diagnostic for this, but we should still try
3328     // to diagnose it.
3329     Diag(New->getLocation(), New->isThisDeclarationADefinition()
3330                                  ? diag::err_redefinition_different_type
3331                                  : diag::err_redeclaration_different_type)
3332         << New->getDeclName() << New->getType() << Old->getType();
3333 
3334     diag::kind PrevDiag;
3335     SourceLocation OldLocation;
3336     std::tie(PrevDiag, OldLocation) =
3337         getNoteDiagForInvalidRedeclaration(Old, New);
3338     Diag(OldLocation, PrevDiag);
3339     return New->setInvalidDecl();
3340   }
3341 
3342   // Don't actually update the type on the new declaration if the old
3343   // declaration was an extern declaration in a different scope.
3344   if (MergeTypeWithOld)
3345     New->setType(MergedT);
3346 }
3347 
3348 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3349                                   LookupResult &Previous) {
3350   // C11 6.2.7p4:
3351   //   For an identifier with internal or external linkage declared
3352   //   in a scope in which a prior declaration of that identifier is
3353   //   visible, if the prior declaration specifies internal or
3354   //   external linkage, the type of the identifier at the later
3355   //   declaration becomes the composite type.
3356   //
3357   // If the variable isn't visible, we do not merge with its type.
3358   if (Previous.isShadowed())
3359     return false;
3360 
3361   if (S.getLangOpts().CPlusPlus) {
3362     // C++11 [dcl.array]p3:
3363     //   If there is a preceding declaration of the entity in the same
3364     //   scope in which the bound was specified, an omitted array bound
3365     //   is taken to be the same as in that earlier declaration.
3366     return NewVD->isPreviousDeclInSameBlockScope() ||
3367            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3368             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3369   } else {
3370     // If the old declaration was function-local, don't merge with its
3371     // type unless we're in the same function.
3372     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3373            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3374   }
3375 }
3376 
3377 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3378 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3379 /// situation, merging decls or emitting diagnostics as appropriate.
3380 ///
3381 /// Tentative definition rules (C99 6.9.2p2) are checked by
3382 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3383 /// definitions here, since the initializer hasn't been attached.
3384 ///
3385 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3386   // If the new decl is already invalid, don't do any other checking.
3387   if (New->isInvalidDecl())
3388     return;
3389 
3390   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3391     return;
3392 
3393   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3394 
3395   // Verify the old decl was also a variable or variable template.
3396   VarDecl *Old = nullptr;
3397   VarTemplateDecl *OldTemplate = nullptr;
3398   if (Previous.isSingleResult()) {
3399     if (NewTemplate) {
3400       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3401       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3402 
3403       if (auto *Shadow =
3404               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3405         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3406           return New->setInvalidDecl();
3407     } else {
3408       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3409 
3410       if (auto *Shadow =
3411               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3412         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3413           return New->setInvalidDecl();
3414     }
3415   }
3416   if (!Old) {
3417     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3418       << New->getDeclName();
3419     Diag(Previous.getRepresentativeDecl()->getLocation(),
3420          diag::note_previous_definition);
3421     return New->setInvalidDecl();
3422   }
3423 
3424   // Ensure the template parameters are compatible.
3425   if (NewTemplate &&
3426       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3427                                       OldTemplate->getTemplateParameters(),
3428                                       /*Complain=*/true, TPL_TemplateMatch))
3429     return New->setInvalidDecl();
3430 
3431   // C++ [class.mem]p1:
3432   //   A member shall not be declared twice in the member-specification [...]
3433   //
3434   // Here, we need only consider static data members.
3435   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3436     Diag(New->getLocation(), diag::err_duplicate_member)
3437       << New->getIdentifier();
3438     Diag(Old->getLocation(), diag::note_previous_declaration);
3439     New->setInvalidDecl();
3440   }
3441 
3442   mergeDeclAttributes(New, Old);
3443   // Warn if an already-declared variable is made a weak_import in a subsequent
3444   // declaration
3445   if (New->hasAttr<WeakImportAttr>() &&
3446       Old->getStorageClass() == SC_None &&
3447       !Old->hasAttr<WeakImportAttr>()) {
3448     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3449     Diag(Old->getLocation(), diag::note_previous_definition);
3450     // Remove weak_import attribute on new declaration.
3451     New->dropAttr<WeakImportAttr>();
3452   }
3453 
3454   if (New->hasAttr<InternalLinkageAttr>() &&
3455       !Old->hasAttr<InternalLinkageAttr>()) {
3456     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3457         << New->getDeclName();
3458     Diag(Old->getLocation(), diag::note_previous_definition);
3459     New->dropAttr<InternalLinkageAttr>();
3460   }
3461 
3462   // Merge the types.
3463   VarDecl *MostRecent = Old->getMostRecentDecl();
3464   if (MostRecent != Old) {
3465     MergeVarDeclTypes(New, MostRecent,
3466                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3467     if (New->isInvalidDecl())
3468       return;
3469   }
3470 
3471   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3472   if (New->isInvalidDecl())
3473     return;
3474 
3475   diag::kind PrevDiag;
3476   SourceLocation OldLocation;
3477   std::tie(PrevDiag, OldLocation) =
3478       getNoteDiagForInvalidRedeclaration(Old, New);
3479 
3480   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3481   if (New->getStorageClass() == SC_Static &&
3482       !New->isStaticDataMember() &&
3483       Old->hasExternalFormalLinkage()) {
3484     if (getLangOpts().MicrosoftExt) {
3485       Diag(New->getLocation(), diag::ext_static_non_static)
3486           << New->getDeclName();
3487       Diag(OldLocation, PrevDiag);
3488     } else {
3489       Diag(New->getLocation(), diag::err_static_non_static)
3490           << New->getDeclName();
3491       Diag(OldLocation, PrevDiag);
3492       return New->setInvalidDecl();
3493     }
3494   }
3495   // C99 6.2.2p4:
3496   //   For an identifier declared with the storage-class specifier
3497   //   extern in a scope in which a prior declaration of that
3498   //   identifier is visible,23) if the prior declaration specifies
3499   //   internal or external linkage, the linkage of the identifier at
3500   //   the later declaration is the same as the linkage specified at
3501   //   the prior declaration. If no prior declaration is visible, or
3502   //   if the prior declaration specifies no linkage, then the
3503   //   identifier has external linkage.
3504   if (New->hasExternalStorage() && Old->hasLinkage())
3505     /* Okay */;
3506   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3507            !New->isStaticDataMember() &&
3508            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3509     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3510     Diag(OldLocation, PrevDiag);
3511     return New->setInvalidDecl();
3512   }
3513 
3514   // Check if extern is followed by non-extern and vice-versa.
3515   if (New->hasExternalStorage() &&
3516       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3517     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3518     Diag(OldLocation, PrevDiag);
3519     return New->setInvalidDecl();
3520   }
3521   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3522       !New->hasExternalStorage()) {
3523     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3524     Diag(OldLocation, PrevDiag);
3525     return New->setInvalidDecl();
3526   }
3527 
3528   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3529 
3530   // FIXME: The test for external storage here seems wrong? We still
3531   // need to check for mismatches.
3532   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3533       // Don't complain about out-of-line definitions of static members.
3534       !(Old->getLexicalDeclContext()->isRecord() &&
3535         !New->getLexicalDeclContext()->isRecord())) {
3536     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3537     Diag(OldLocation, PrevDiag);
3538     return New->setInvalidDecl();
3539   }
3540 
3541   if (New->getTLSKind() != Old->getTLSKind()) {
3542     if (!Old->getTLSKind()) {
3543       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3544       Diag(OldLocation, PrevDiag);
3545     } else if (!New->getTLSKind()) {
3546       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3547       Diag(OldLocation, PrevDiag);
3548     } else {
3549       // Do not allow redeclaration to change the variable between requiring
3550       // static and dynamic initialization.
3551       // FIXME: GCC allows this, but uses the TLS keyword on the first
3552       // declaration to determine the kind. Do we need to be compatible here?
3553       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3554         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3555       Diag(OldLocation, PrevDiag);
3556     }
3557   }
3558 
3559   // C++ doesn't have tentative definitions, so go right ahead and check here.
3560   VarDecl *Def;
3561   if (getLangOpts().CPlusPlus &&
3562       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3563       (Def = Old->getDefinition())) {
3564     NamedDecl *Hidden = nullptr;
3565     if (!hasVisibleDefinition(Def, &Hidden) &&
3566         (New->getFormalLinkage() == InternalLinkage ||
3567          New->getDescribedVarTemplate() ||
3568          New->getNumTemplateParameterLists() ||
3569          New->getDeclContext()->isDependentContext())) {
3570       // The previous definition is hidden, and multiple definitions are
3571       // permitted (in separate TUs). Form another definition of it.
3572     } else {
3573       Diag(New->getLocation(), diag::err_redefinition) << New;
3574       Diag(Def->getLocation(), diag::note_previous_definition);
3575       New->setInvalidDecl();
3576       return;
3577     }
3578   }
3579 
3580   if (haveIncompatibleLanguageLinkages(Old, New)) {
3581     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3582     Diag(OldLocation, PrevDiag);
3583     New->setInvalidDecl();
3584     return;
3585   }
3586 
3587   // Merge "used" flag.
3588   if (Old->getMostRecentDecl()->isUsed(false))
3589     New->setIsUsed();
3590 
3591   // Keep a chain of previous declarations.
3592   New->setPreviousDecl(Old);
3593   if (NewTemplate)
3594     NewTemplate->setPreviousDecl(OldTemplate);
3595 
3596   // Inherit access appropriately.
3597   New->setAccess(Old->getAccess());
3598   if (NewTemplate)
3599     NewTemplate->setAccess(New->getAccess());
3600 }
3601 
3602 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3603 /// no declarator (e.g. "struct foo;") is parsed.
3604 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3605                                        DeclSpec &DS) {
3606   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3607 }
3608 
3609 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3610 // disambiguate entities defined in different scopes.
3611 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3612 // compatibility.
3613 // We will pick our mangling number depending on which version of MSVC is being
3614 // targeted.
3615 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3616   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3617              ? S->getMSCurManglingNumber()
3618              : S->getMSLastManglingNumber();
3619 }
3620 
3621 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3622   if (!Context.getLangOpts().CPlusPlus)
3623     return;
3624 
3625   if (isa<CXXRecordDecl>(Tag->getParent())) {
3626     // If this tag is the direct child of a class, number it if
3627     // it is anonymous.
3628     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3629       return;
3630     MangleNumberingContext &MCtx =
3631         Context.getManglingNumberContext(Tag->getParent());
3632     Context.setManglingNumber(
3633         Tag, MCtx.getManglingNumber(
3634                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3635     return;
3636   }
3637 
3638   // If this tag isn't a direct child of a class, number it if it is local.
3639   Decl *ManglingContextDecl;
3640   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3641           Tag->getDeclContext(), ManglingContextDecl)) {
3642     Context.setManglingNumber(
3643         Tag, MCtx->getManglingNumber(
3644                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3645   }
3646 }
3647 
3648 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3649                                         TypedefNameDecl *NewTD) {
3650   if (TagFromDeclSpec->isInvalidDecl())
3651     return;
3652 
3653   // Do nothing if the tag already has a name for linkage purposes.
3654   if (TagFromDeclSpec->hasNameForLinkage())
3655     return;
3656 
3657   // A well-formed anonymous tag must always be a TUK_Definition.
3658   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3659 
3660   // The type must match the tag exactly;  no qualifiers allowed.
3661   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3662                            Context.getTagDeclType(TagFromDeclSpec))) {
3663     if (getLangOpts().CPlusPlus)
3664       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3665     return;
3666   }
3667 
3668   // If we've already computed linkage for the anonymous tag, then
3669   // adding a typedef name for the anonymous decl can change that
3670   // linkage, which might be a serious problem.  Diagnose this as
3671   // unsupported and ignore the typedef name.  TODO: we should
3672   // pursue this as a language defect and establish a formal rule
3673   // for how to handle it.
3674   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3675     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3676 
3677     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3678     tagLoc = getLocForEndOfToken(tagLoc);
3679 
3680     llvm::SmallString<40> textToInsert;
3681     textToInsert += ' ';
3682     textToInsert += NewTD->getIdentifier()->getName();
3683     Diag(tagLoc, diag::note_typedef_changes_linkage)
3684         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3685     return;
3686   }
3687 
3688   // Otherwise, set this is the anon-decl typedef for the tag.
3689   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3690 }
3691 
3692 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3693   switch (T) {
3694   case DeclSpec::TST_class:
3695     return 0;
3696   case DeclSpec::TST_struct:
3697     return 1;
3698   case DeclSpec::TST_interface:
3699     return 2;
3700   case DeclSpec::TST_union:
3701     return 3;
3702   case DeclSpec::TST_enum:
3703     return 4;
3704   default:
3705     llvm_unreachable("unexpected type specifier");
3706   }
3707 }
3708 
3709 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3710 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3711 /// parameters to cope with template friend declarations.
3712 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3713                                        DeclSpec &DS,
3714                                        MultiTemplateParamsArg TemplateParams,
3715                                        bool IsExplicitInstantiation) {
3716   Decl *TagD = nullptr;
3717   TagDecl *Tag = nullptr;
3718   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3719       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3720       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3721       DS.getTypeSpecType() == DeclSpec::TST_union ||
3722       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3723     TagD = DS.getRepAsDecl();
3724 
3725     if (!TagD) // We probably had an error
3726       return nullptr;
3727 
3728     // Note that the above type specs guarantee that the
3729     // type rep is a Decl, whereas in many of the others
3730     // it's a Type.
3731     if (isa<TagDecl>(TagD))
3732       Tag = cast<TagDecl>(TagD);
3733     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3734       Tag = CTD->getTemplatedDecl();
3735   }
3736 
3737   if (Tag) {
3738     handleTagNumbering(Tag, S);
3739     Tag->setFreeStanding();
3740     if (Tag->isInvalidDecl())
3741       return Tag;
3742   }
3743 
3744   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3745     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3746     // or incomplete types shall not be restrict-qualified."
3747     if (TypeQuals & DeclSpec::TQ_restrict)
3748       Diag(DS.getRestrictSpecLoc(),
3749            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3750            << DS.getSourceRange();
3751   }
3752 
3753   if (DS.isConstexprSpecified()) {
3754     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3755     // and definitions of functions and variables.
3756     if (Tag)
3757       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3758           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3759     else
3760       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3761     // Don't emit warnings after this error.
3762     return TagD;
3763   }
3764 
3765   if (DS.isConceptSpecified()) {
3766     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3767     // either a function concept and its definition or a variable concept and
3768     // its initializer.
3769     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3770     return TagD;
3771   }
3772 
3773   DiagnoseFunctionSpecifiers(DS);
3774 
3775   if (DS.isFriendSpecified()) {
3776     // If we're dealing with a decl but not a TagDecl, assume that
3777     // whatever routines created it handled the friendship aspect.
3778     if (TagD && !Tag)
3779       return nullptr;
3780     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3781   }
3782 
3783   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3784   bool IsExplicitSpecialization =
3785     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3786   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3787       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3788       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3789     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3790     // nested-name-specifier unless it is an explicit instantiation
3791     // or an explicit specialization.
3792     //
3793     // FIXME: We allow class template partial specializations here too, per the
3794     // obvious intent of DR1819.
3795     //
3796     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3797     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3798         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3799     return nullptr;
3800   }
3801 
3802   // Track whether this decl-specifier declares anything.
3803   bool DeclaresAnything = true;
3804 
3805   // Handle anonymous struct definitions.
3806   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3807     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3808         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3809       if (getLangOpts().CPlusPlus ||
3810           Record->getDeclContext()->isRecord())
3811         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3812                                            Context.getPrintingPolicy());
3813 
3814       DeclaresAnything = false;
3815     }
3816   }
3817 
3818   // C11 6.7.2.1p2:
3819   //   A struct-declaration that does not declare an anonymous structure or
3820   //   anonymous union shall contain a struct-declarator-list.
3821   //
3822   // This rule also existed in C89 and C99; the grammar for struct-declaration
3823   // did not permit a struct-declaration without a struct-declarator-list.
3824   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3825       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3826     // Check for Microsoft C extension: anonymous struct/union member.
3827     // Handle 2 kinds of anonymous struct/union:
3828     //   struct STRUCT;
3829     //   union UNION;
3830     // and
3831     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3832     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3833     if ((Tag && Tag->getDeclName()) ||
3834         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3835       RecordDecl *Record = nullptr;
3836       if (Tag)
3837         Record = dyn_cast<RecordDecl>(Tag);
3838       else if (const RecordType *RT =
3839                    DS.getRepAsType().get()->getAsStructureType())
3840         Record = RT->getDecl();
3841       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3842         Record = UT->getDecl();
3843 
3844       if (Record && getLangOpts().MicrosoftExt) {
3845         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3846           << Record->isUnion() << DS.getSourceRange();
3847         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3848       }
3849 
3850       DeclaresAnything = false;
3851     }
3852   }
3853 
3854   // Skip all the checks below if we have a type error.
3855   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3856       (TagD && TagD->isInvalidDecl()))
3857     return TagD;
3858 
3859   if (getLangOpts().CPlusPlus &&
3860       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3861     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3862       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3863           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3864         DeclaresAnything = false;
3865 
3866   if (!DS.isMissingDeclaratorOk()) {
3867     // Customize diagnostic for a typedef missing a name.
3868     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3869       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3870         << DS.getSourceRange();
3871     else
3872       DeclaresAnything = false;
3873   }
3874 
3875   if (DS.isModulePrivateSpecified() &&
3876       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3877     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3878       << Tag->getTagKind()
3879       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3880 
3881   ActOnDocumentableDecl(TagD);
3882 
3883   // C 6.7/2:
3884   //   A declaration [...] shall declare at least a declarator [...], a tag,
3885   //   or the members of an enumeration.
3886   // C++ [dcl.dcl]p3:
3887   //   [If there are no declarators], and except for the declaration of an
3888   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3889   //   names into the program, or shall redeclare a name introduced by a
3890   //   previous declaration.
3891   if (!DeclaresAnything) {
3892     // In C, we allow this as a (popular) extension / bug. Don't bother
3893     // producing further diagnostics for redundant qualifiers after this.
3894     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3895     return TagD;
3896   }
3897 
3898   // C++ [dcl.stc]p1:
3899   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3900   //   init-declarator-list of the declaration shall not be empty.
3901   // C++ [dcl.fct.spec]p1:
3902   //   If a cv-qualifier appears in a decl-specifier-seq, the
3903   //   init-declarator-list of the declaration shall not be empty.
3904   //
3905   // Spurious qualifiers here appear to be valid in C.
3906   unsigned DiagID = diag::warn_standalone_specifier;
3907   if (getLangOpts().CPlusPlus)
3908     DiagID = diag::ext_standalone_specifier;
3909 
3910   // Note that a linkage-specification sets a storage class, but
3911   // 'extern "C" struct foo;' is actually valid and not theoretically
3912   // useless.
3913   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3914     if (SCS == DeclSpec::SCS_mutable)
3915       // Since mutable is not a viable storage class specifier in C, there is
3916       // no reason to treat it as an extension. Instead, diagnose as an error.
3917       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3918     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3919       Diag(DS.getStorageClassSpecLoc(), DiagID)
3920         << DeclSpec::getSpecifierName(SCS);
3921   }
3922 
3923   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3924     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3925       << DeclSpec::getSpecifierName(TSCS);
3926   if (DS.getTypeQualifiers()) {
3927     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3928       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3929     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3930       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3931     // Restrict is covered above.
3932     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3933       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3934   }
3935 
3936   // Warn about ignored type attributes, for example:
3937   // __attribute__((aligned)) struct A;
3938   // Attributes should be placed after tag to apply to type declaration.
3939   if (!DS.getAttributes().empty()) {
3940     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3941     if (TypeSpecType == DeclSpec::TST_class ||
3942         TypeSpecType == DeclSpec::TST_struct ||
3943         TypeSpecType == DeclSpec::TST_interface ||
3944         TypeSpecType == DeclSpec::TST_union ||
3945         TypeSpecType == DeclSpec::TST_enum) {
3946       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3947            attrs = attrs->getNext())
3948         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3949             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3950     }
3951   }
3952 
3953   return TagD;
3954 }
3955 
3956 /// We are trying to inject an anonymous member into the given scope;
3957 /// check if there's an existing declaration that can't be overloaded.
3958 ///
3959 /// \return true if this is a forbidden redeclaration
3960 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3961                                          Scope *S,
3962                                          DeclContext *Owner,
3963                                          DeclarationName Name,
3964                                          SourceLocation NameLoc,
3965                                          bool IsUnion) {
3966   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3967                  Sema::ForRedeclaration);
3968   if (!SemaRef.LookupName(R, S)) return false;
3969 
3970   // Pick a representative declaration.
3971   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3972   assert(PrevDecl && "Expected a non-null Decl");
3973 
3974   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3975     return false;
3976 
3977   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3978     << IsUnion << Name;
3979   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3980 
3981   return true;
3982 }
3983 
3984 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3985 /// anonymous struct or union AnonRecord into the owning context Owner
3986 /// and scope S. This routine will be invoked just after we realize
3987 /// that an unnamed union or struct is actually an anonymous union or
3988 /// struct, e.g.,
3989 ///
3990 /// @code
3991 /// union {
3992 ///   int i;
3993 ///   float f;
3994 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3995 ///    // f into the surrounding scope.x
3996 /// @endcode
3997 ///
3998 /// This routine is recursive, injecting the names of nested anonymous
3999 /// structs/unions into the owning context and scope as well.
4000 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
4001                                          DeclContext *Owner,
4002                                          RecordDecl *AnonRecord,
4003                                          AccessSpecifier AS,
4004                                          SmallVectorImpl<NamedDecl *> &Chaining,
4005                                          bool MSAnonStruct) {
4006   bool Invalid = false;
4007 
4008   // Look every FieldDecl and IndirectFieldDecl with a name.
4009   for (auto *D : AnonRecord->decls()) {
4010     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4011         cast<NamedDecl>(D)->getDeclName()) {
4012       ValueDecl *VD = cast<ValueDecl>(D);
4013       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4014                                        VD->getLocation(),
4015                                        AnonRecord->isUnion())) {
4016         // C++ [class.union]p2:
4017         //   The names of the members of an anonymous union shall be
4018         //   distinct from the names of any other entity in the
4019         //   scope in which the anonymous union is declared.
4020         Invalid = true;
4021       } else {
4022         // C++ [class.union]p2:
4023         //   For the purpose of name lookup, after the anonymous union
4024         //   definition, the members of the anonymous union are
4025         //   considered to have been defined in the scope in which the
4026         //   anonymous union is declared.
4027         unsigned OldChainingSize = Chaining.size();
4028         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4029           Chaining.append(IF->chain_begin(), IF->chain_end());
4030         else
4031           Chaining.push_back(VD);
4032 
4033         assert(Chaining.size() >= 2);
4034         NamedDecl **NamedChain =
4035           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4036         for (unsigned i = 0; i < Chaining.size(); i++)
4037           NamedChain[i] = Chaining[i];
4038 
4039         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4040             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4041             VD->getType(), NamedChain, Chaining.size());
4042 
4043         for (const auto *Attr : VD->attrs())
4044           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4045 
4046         IndirectField->setAccess(AS);
4047         IndirectField->setImplicit();
4048         SemaRef.PushOnScopeChains(IndirectField, S);
4049 
4050         // That includes picking up the appropriate access specifier.
4051         if (AS != AS_none) IndirectField->setAccess(AS);
4052 
4053         Chaining.resize(OldChainingSize);
4054       }
4055     }
4056   }
4057 
4058   return Invalid;
4059 }
4060 
4061 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4062 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4063 /// illegal input values are mapped to SC_None.
4064 static StorageClass
4065 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4066   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4067   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4068          "Parser allowed 'typedef' as storage class VarDecl.");
4069   switch (StorageClassSpec) {
4070   case DeclSpec::SCS_unspecified:    return SC_None;
4071   case DeclSpec::SCS_extern:
4072     if (DS.isExternInLinkageSpec())
4073       return SC_None;
4074     return SC_Extern;
4075   case DeclSpec::SCS_static:         return SC_Static;
4076   case DeclSpec::SCS_auto:           return SC_Auto;
4077   case DeclSpec::SCS_register:       return SC_Register;
4078   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4079     // Illegal SCSs map to None: error reporting is up to the caller.
4080   case DeclSpec::SCS_mutable:        // Fall through.
4081   case DeclSpec::SCS_typedef:        return SC_None;
4082   }
4083   llvm_unreachable("unknown storage class specifier");
4084 }
4085 
4086 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4087   assert(Record->hasInClassInitializer());
4088 
4089   for (const auto *I : Record->decls()) {
4090     const auto *FD = dyn_cast<FieldDecl>(I);
4091     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4092       FD = IFD->getAnonField();
4093     if (FD && FD->hasInClassInitializer())
4094       return FD->getLocation();
4095   }
4096 
4097   llvm_unreachable("couldn't find in-class initializer");
4098 }
4099 
4100 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4101                                       SourceLocation DefaultInitLoc) {
4102   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4103     return;
4104 
4105   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4106   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4107 }
4108 
4109 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4110                                       CXXRecordDecl *AnonUnion) {
4111   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4112     return;
4113 
4114   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4115 }
4116 
4117 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4118 /// anonymous structure or union. Anonymous unions are a C++ feature
4119 /// (C++ [class.union]) and a C11 feature; anonymous structures
4120 /// are a C11 feature and GNU C++ extension.
4121 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4122                                         AccessSpecifier AS,
4123                                         RecordDecl *Record,
4124                                         const PrintingPolicy &Policy) {
4125   DeclContext *Owner = Record->getDeclContext();
4126 
4127   // Diagnose whether this anonymous struct/union is an extension.
4128   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4129     Diag(Record->getLocation(), diag::ext_anonymous_union);
4130   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4131     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4132   else if (!Record->isUnion() && !getLangOpts().C11)
4133     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4134 
4135   // C and C++ require different kinds of checks for anonymous
4136   // structs/unions.
4137   bool Invalid = false;
4138   if (getLangOpts().CPlusPlus) {
4139     const char *PrevSpec = nullptr;
4140     unsigned DiagID;
4141     if (Record->isUnion()) {
4142       // C++ [class.union]p6:
4143       //   Anonymous unions declared in a named namespace or in the
4144       //   global namespace shall be declared static.
4145       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4146           (isa<TranslationUnitDecl>(Owner) ||
4147            (isa<NamespaceDecl>(Owner) &&
4148             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4149         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4150           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4151 
4152         // Recover by adding 'static'.
4153         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4154                                PrevSpec, DiagID, Policy);
4155       }
4156       // C++ [class.union]p6:
4157       //   A storage class is not allowed in a declaration of an
4158       //   anonymous union in a class scope.
4159       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4160                isa<RecordDecl>(Owner)) {
4161         Diag(DS.getStorageClassSpecLoc(),
4162              diag::err_anonymous_union_with_storage_spec)
4163           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4164 
4165         // Recover by removing the storage specifier.
4166         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4167                                SourceLocation(),
4168                                PrevSpec, DiagID, Context.getPrintingPolicy());
4169       }
4170     }
4171 
4172     // Ignore const/volatile/restrict qualifiers.
4173     if (DS.getTypeQualifiers()) {
4174       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4175         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4176           << Record->isUnion() << "const"
4177           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4178       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4179         Diag(DS.getVolatileSpecLoc(),
4180              diag::ext_anonymous_struct_union_qualified)
4181           << Record->isUnion() << "volatile"
4182           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4183       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4184         Diag(DS.getRestrictSpecLoc(),
4185              diag::ext_anonymous_struct_union_qualified)
4186           << Record->isUnion() << "restrict"
4187           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4188       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4189         Diag(DS.getAtomicSpecLoc(),
4190              diag::ext_anonymous_struct_union_qualified)
4191           << Record->isUnion() << "_Atomic"
4192           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4193 
4194       DS.ClearTypeQualifiers();
4195     }
4196 
4197     // C++ [class.union]p2:
4198     //   The member-specification of an anonymous union shall only
4199     //   define non-static data members. [Note: nested types and
4200     //   functions cannot be declared within an anonymous union. ]
4201     for (auto *Mem : Record->decls()) {
4202       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4203         // C++ [class.union]p3:
4204         //   An anonymous union shall not have private or protected
4205         //   members (clause 11).
4206         assert(FD->getAccess() != AS_none);
4207         if (FD->getAccess() != AS_public) {
4208           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4209             << Record->isUnion() << (FD->getAccess() == AS_protected);
4210           Invalid = true;
4211         }
4212 
4213         // C++ [class.union]p1
4214         //   An object of a class with a non-trivial constructor, a non-trivial
4215         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4216         //   assignment operator cannot be a member of a union, nor can an
4217         //   array of such objects.
4218         if (CheckNontrivialField(FD))
4219           Invalid = true;
4220       } else if (Mem->isImplicit()) {
4221         // Any implicit members are fine.
4222       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4223         // This is a type that showed up in an
4224         // elaborated-type-specifier inside the anonymous struct or
4225         // union, but which actually declares a type outside of the
4226         // anonymous struct or union. It's okay.
4227       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4228         if (!MemRecord->isAnonymousStructOrUnion() &&
4229             MemRecord->getDeclName()) {
4230           // Visual C++ allows type definition in anonymous struct or union.
4231           if (getLangOpts().MicrosoftExt)
4232             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4233               << Record->isUnion();
4234           else {
4235             // This is a nested type declaration.
4236             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4237               << Record->isUnion();
4238             Invalid = true;
4239           }
4240         } else {
4241           // This is an anonymous type definition within another anonymous type.
4242           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4243           // not part of standard C++.
4244           Diag(MemRecord->getLocation(),
4245                diag::ext_anonymous_record_with_anonymous_type)
4246             << Record->isUnion();
4247         }
4248       } else if (isa<AccessSpecDecl>(Mem)) {
4249         // Any access specifier is fine.
4250       } else if (isa<StaticAssertDecl>(Mem)) {
4251         // In C++1z, static_assert declarations are also fine.
4252       } else {
4253         // We have something that isn't a non-static data
4254         // member. Complain about it.
4255         unsigned DK = diag::err_anonymous_record_bad_member;
4256         if (isa<TypeDecl>(Mem))
4257           DK = diag::err_anonymous_record_with_type;
4258         else if (isa<FunctionDecl>(Mem))
4259           DK = diag::err_anonymous_record_with_function;
4260         else if (isa<VarDecl>(Mem))
4261           DK = diag::err_anonymous_record_with_static;
4262 
4263         // Visual C++ allows type definition in anonymous struct or union.
4264         if (getLangOpts().MicrosoftExt &&
4265             DK == diag::err_anonymous_record_with_type)
4266           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4267             << Record->isUnion();
4268         else {
4269           Diag(Mem->getLocation(), DK) << Record->isUnion();
4270           Invalid = true;
4271         }
4272       }
4273     }
4274 
4275     // C++11 [class.union]p8 (DR1460):
4276     //   At most one variant member of a union may have a
4277     //   brace-or-equal-initializer.
4278     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4279         Owner->isRecord())
4280       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4281                                 cast<CXXRecordDecl>(Record));
4282   }
4283 
4284   if (!Record->isUnion() && !Owner->isRecord()) {
4285     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4286       << getLangOpts().CPlusPlus;
4287     Invalid = true;
4288   }
4289 
4290   // Mock up a declarator.
4291   Declarator Dc(DS, Declarator::MemberContext);
4292   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4293   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4294 
4295   // Create a declaration for this anonymous struct/union.
4296   NamedDecl *Anon = nullptr;
4297   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4298     Anon = FieldDecl::Create(Context, OwningClass,
4299                              DS.getLocStart(),
4300                              Record->getLocation(),
4301                              /*IdentifierInfo=*/nullptr,
4302                              Context.getTypeDeclType(Record),
4303                              TInfo,
4304                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4305                              /*InitStyle=*/ICIS_NoInit);
4306     Anon->setAccess(AS);
4307     if (getLangOpts().CPlusPlus)
4308       FieldCollector->Add(cast<FieldDecl>(Anon));
4309   } else {
4310     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4311     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4312     if (SCSpec == DeclSpec::SCS_mutable) {
4313       // mutable can only appear on non-static class members, so it's always
4314       // an error here
4315       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4316       Invalid = true;
4317       SC = SC_None;
4318     }
4319 
4320     Anon = VarDecl::Create(Context, Owner,
4321                            DS.getLocStart(),
4322                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4323                            Context.getTypeDeclType(Record),
4324                            TInfo, SC);
4325 
4326     // Default-initialize the implicit variable. This initialization will be
4327     // trivial in almost all cases, except if a union member has an in-class
4328     // initializer:
4329     //   union { int n = 0; };
4330     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4331   }
4332   Anon->setImplicit();
4333 
4334   // Mark this as an anonymous struct/union type.
4335   Record->setAnonymousStructOrUnion(true);
4336 
4337   // Add the anonymous struct/union object to the current
4338   // context. We'll be referencing this object when we refer to one of
4339   // its members.
4340   Owner->addDecl(Anon);
4341 
4342   // Inject the members of the anonymous struct/union into the owning
4343   // context and into the identifier resolver chain for name lookup
4344   // purposes.
4345   SmallVector<NamedDecl*, 2> Chain;
4346   Chain.push_back(Anon);
4347 
4348   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4349                                           Chain, false))
4350     Invalid = true;
4351 
4352   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4353     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4354       Decl *ManglingContextDecl;
4355       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4356               NewVD->getDeclContext(), ManglingContextDecl)) {
4357         Context.setManglingNumber(
4358             NewVD, MCtx->getManglingNumber(
4359                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4360         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4361       }
4362     }
4363   }
4364 
4365   if (Invalid)
4366     Anon->setInvalidDecl();
4367 
4368   return Anon;
4369 }
4370 
4371 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4372 /// Microsoft C anonymous structure.
4373 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4374 /// Example:
4375 ///
4376 /// struct A { int a; };
4377 /// struct B { struct A; int b; };
4378 ///
4379 /// void foo() {
4380 ///   B var;
4381 ///   var.a = 3;
4382 /// }
4383 ///
4384 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4385                                            RecordDecl *Record) {
4386   assert(Record && "expected a record!");
4387 
4388   // Mock up a declarator.
4389   Declarator Dc(DS, Declarator::TypeNameContext);
4390   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4391   assert(TInfo && "couldn't build declarator info for anonymous struct");
4392 
4393   auto *ParentDecl = cast<RecordDecl>(CurContext);
4394   QualType RecTy = Context.getTypeDeclType(Record);
4395 
4396   // Create a declaration for this anonymous struct.
4397   NamedDecl *Anon = FieldDecl::Create(Context,
4398                              ParentDecl,
4399                              DS.getLocStart(),
4400                              DS.getLocStart(),
4401                              /*IdentifierInfo=*/nullptr,
4402                              RecTy,
4403                              TInfo,
4404                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4405                              /*InitStyle=*/ICIS_NoInit);
4406   Anon->setImplicit();
4407 
4408   // Add the anonymous struct object to the current context.
4409   CurContext->addDecl(Anon);
4410 
4411   // Inject the members of the anonymous struct into the current
4412   // context and into the identifier resolver chain for name lookup
4413   // purposes.
4414   SmallVector<NamedDecl*, 2> Chain;
4415   Chain.push_back(Anon);
4416 
4417   RecordDecl *RecordDef = Record->getDefinition();
4418   if (RequireCompleteType(Anon->getLocation(), RecTy,
4419                           diag::err_field_incomplete) ||
4420       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4421                                           AS_none, Chain, true)) {
4422     Anon->setInvalidDecl();
4423     ParentDecl->setInvalidDecl();
4424   }
4425 
4426   return Anon;
4427 }
4428 
4429 /// GetNameForDeclarator - Determine the full declaration name for the
4430 /// given Declarator.
4431 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4432   return GetNameFromUnqualifiedId(D.getName());
4433 }
4434 
4435 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4436 DeclarationNameInfo
4437 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4438   DeclarationNameInfo NameInfo;
4439   NameInfo.setLoc(Name.StartLocation);
4440 
4441   switch (Name.getKind()) {
4442 
4443   case UnqualifiedId::IK_ImplicitSelfParam:
4444   case UnqualifiedId::IK_Identifier:
4445     NameInfo.setName(Name.Identifier);
4446     NameInfo.setLoc(Name.StartLocation);
4447     return NameInfo;
4448 
4449   case UnqualifiedId::IK_OperatorFunctionId:
4450     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4451                                            Name.OperatorFunctionId.Operator));
4452     NameInfo.setLoc(Name.StartLocation);
4453     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4454       = Name.OperatorFunctionId.SymbolLocations[0];
4455     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4456       = Name.EndLocation.getRawEncoding();
4457     return NameInfo;
4458 
4459   case UnqualifiedId::IK_LiteralOperatorId:
4460     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4461                                                            Name.Identifier));
4462     NameInfo.setLoc(Name.StartLocation);
4463     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4464     return NameInfo;
4465 
4466   case UnqualifiedId::IK_ConversionFunctionId: {
4467     TypeSourceInfo *TInfo;
4468     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4469     if (Ty.isNull())
4470       return DeclarationNameInfo();
4471     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4472                                                Context.getCanonicalType(Ty)));
4473     NameInfo.setLoc(Name.StartLocation);
4474     NameInfo.setNamedTypeInfo(TInfo);
4475     return NameInfo;
4476   }
4477 
4478   case UnqualifiedId::IK_ConstructorName: {
4479     TypeSourceInfo *TInfo;
4480     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4481     if (Ty.isNull())
4482       return DeclarationNameInfo();
4483     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4484                                               Context.getCanonicalType(Ty)));
4485     NameInfo.setLoc(Name.StartLocation);
4486     NameInfo.setNamedTypeInfo(TInfo);
4487     return NameInfo;
4488   }
4489 
4490   case UnqualifiedId::IK_ConstructorTemplateId: {
4491     // In well-formed code, we can only have a constructor
4492     // template-id that refers to the current context, so go there
4493     // to find the actual type being constructed.
4494     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4495     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4496       return DeclarationNameInfo();
4497 
4498     // Determine the type of the class being constructed.
4499     QualType CurClassType = Context.getTypeDeclType(CurClass);
4500 
4501     // FIXME: Check two things: that the template-id names the same type as
4502     // CurClassType, and that the template-id does not occur when the name
4503     // was qualified.
4504 
4505     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4506                                     Context.getCanonicalType(CurClassType)));
4507     NameInfo.setLoc(Name.StartLocation);
4508     // FIXME: should we retrieve TypeSourceInfo?
4509     NameInfo.setNamedTypeInfo(nullptr);
4510     return NameInfo;
4511   }
4512 
4513   case UnqualifiedId::IK_DestructorName: {
4514     TypeSourceInfo *TInfo;
4515     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4516     if (Ty.isNull())
4517       return DeclarationNameInfo();
4518     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4519                                               Context.getCanonicalType(Ty)));
4520     NameInfo.setLoc(Name.StartLocation);
4521     NameInfo.setNamedTypeInfo(TInfo);
4522     return NameInfo;
4523   }
4524 
4525   case UnqualifiedId::IK_TemplateId: {
4526     TemplateName TName = Name.TemplateId->Template.get();
4527     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4528     return Context.getNameForTemplate(TName, TNameLoc);
4529   }
4530 
4531   } // switch (Name.getKind())
4532 
4533   llvm_unreachable("Unknown name kind");
4534 }
4535 
4536 static QualType getCoreType(QualType Ty) {
4537   do {
4538     if (Ty->isPointerType() || Ty->isReferenceType())
4539       Ty = Ty->getPointeeType();
4540     else if (Ty->isArrayType())
4541       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4542     else
4543       return Ty.withoutLocalFastQualifiers();
4544   } while (true);
4545 }
4546 
4547 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4548 /// and Definition have "nearly" matching parameters. This heuristic is
4549 /// used to improve diagnostics in the case where an out-of-line function
4550 /// definition doesn't match any declaration within the class or namespace.
4551 /// Also sets Params to the list of indices to the parameters that differ
4552 /// between the declaration and the definition. If hasSimilarParameters
4553 /// returns true and Params is empty, then all of the parameters match.
4554 static bool hasSimilarParameters(ASTContext &Context,
4555                                      FunctionDecl *Declaration,
4556                                      FunctionDecl *Definition,
4557                                      SmallVectorImpl<unsigned> &Params) {
4558   Params.clear();
4559   if (Declaration->param_size() != Definition->param_size())
4560     return false;
4561   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4562     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4563     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4564 
4565     // The parameter types are identical
4566     if (Context.hasSameType(DefParamTy, DeclParamTy))
4567       continue;
4568 
4569     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4570     QualType DefParamBaseTy = getCoreType(DefParamTy);
4571     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4572     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4573 
4574     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4575         (DeclTyName && DeclTyName == DefTyName))
4576       Params.push_back(Idx);
4577     else  // The two parameters aren't even close
4578       return false;
4579   }
4580 
4581   return true;
4582 }
4583 
4584 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4585 /// declarator needs to be rebuilt in the current instantiation.
4586 /// Any bits of declarator which appear before the name are valid for
4587 /// consideration here.  That's specifically the type in the decl spec
4588 /// and the base type in any member-pointer chunks.
4589 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4590                                                     DeclarationName Name) {
4591   // The types we specifically need to rebuild are:
4592   //   - typenames, typeofs, and decltypes
4593   //   - types which will become injected class names
4594   // Of course, we also need to rebuild any type referencing such a
4595   // type.  It's safest to just say "dependent", but we call out a
4596   // few cases here.
4597 
4598   DeclSpec &DS = D.getMutableDeclSpec();
4599   switch (DS.getTypeSpecType()) {
4600   case DeclSpec::TST_typename:
4601   case DeclSpec::TST_typeofType:
4602   case DeclSpec::TST_underlyingType:
4603   case DeclSpec::TST_atomic: {
4604     // Grab the type from the parser.
4605     TypeSourceInfo *TSI = nullptr;
4606     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4607     if (T.isNull() || !T->isDependentType()) break;
4608 
4609     // Make sure there's a type source info.  This isn't really much
4610     // of a waste; most dependent types should have type source info
4611     // attached already.
4612     if (!TSI)
4613       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4614 
4615     // Rebuild the type in the current instantiation.
4616     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4617     if (!TSI) return true;
4618 
4619     // Store the new type back in the decl spec.
4620     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4621     DS.UpdateTypeRep(LocType);
4622     break;
4623   }
4624 
4625   case DeclSpec::TST_decltype:
4626   case DeclSpec::TST_typeofExpr: {
4627     Expr *E = DS.getRepAsExpr();
4628     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4629     if (Result.isInvalid()) return true;
4630     DS.UpdateExprRep(Result.get());
4631     break;
4632   }
4633 
4634   default:
4635     // Nothing to do for these decl specs.
4636     break;
4637   }
4638 
4639   // It doesn't matter what order we do this in.
4640   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4641     DeclaratorChunk &Chunk = D.getTypeObject(I);
4642 
4643     // The only type information in the declarator which can come
4644     // before the declaration name is the base type of a member
4645     // pointer.
4646     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4647       continue;
4648 
4649     // Rebuild the scope specifier in-place.
4650     CXXScopeSpec &SS = Chunk.Mem.Scope();
4651     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4652       return true;
4653   }
4654 
4655   return false;
4656 }
4657 
4658 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4659   D.setFunctionDefinitionKind(FDK_Declaration);
4660   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4661 
4662   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4663       Dcl && Dcl->getDeclContext()->isFileContext())
4664     Dcl->setTopLevelDeclInObjCContainer();
4665 
4666   return Dcl;
4667 }
4668 
4669 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4670 ///   If T is the name of a class, then each of the following shall have a
4671 ///   name different from T:
4672 ///     - every static data member of class T;
4673 ///     - every member function of class T
4674 ///     - every member of class T that is itself a type;
4675 /// \returns true if the declaration name violates these rules.
4676 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4677                                    DeclarationNameInfo NameInfo) {
4678   DeclarationName Name = NameInfo.getName();
4679 
4680   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4681   while (Record && Record->isAnonymousStructOrUnion())
4682     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4683   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4684     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4685     return true;
4686   }
4687 
4688   return false;
4689 }
4690 
4691 /// \brief Diagnose a declaration whose declarator-id has the given
4692 /// nested-name-specifier.
4693 ///
4694 /// \param SS The nested-name-specifier of the declarator-id.
4695 ///
4696 /// \param DC The declaration context to which the nested-name-specifier
4697 /// resolves.
4698 ///
4699 /// \param Name The name of the entity being declared.
4700 ///
4701 /// \param Loc The location of the name of the entity being declared.
4702 ///
4703 /// \returns true if we cannot safely recover from this error, false otherwise.
4704 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4705                                         DeclarationName Name,
4706                                         SourceLocation Loc) {
4707   DeclContext *Cur = CurContext;
4708   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4709     Cur = Cur->getParent();
4710 
4711   // If the user provided a superfluous scope specifier that refers back to the
4712   // class in which the entity is already declared, diagnose and ignore it.
4713   //
4714   // class X {
4715   //   void X::f();
4716   // };
4717   //
4718   // Note, it was once ill-formed to give redundant qualification in all
4719   // contexts, but that rule was removed by DR482.
4720   if (Cur->Equals(DC)) {
4721     if (Cur->isRecord()) {
4722       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4723                                       : diag::err_member_extra_qualification)
4724         << Name << FixItHint::CreateRemoval(SS.getRange());
4725       SS.clear();
4726     } else {
4727       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4728     }
4729     return false;
4730   }
4731 
4732   // Check whether the qualifying scope encloses the scope of the original
4733   // declaration.
4734   if (!Cur->Encloses(DC)) {
4735     if (Cur->isRecord())
4736       Diag(Loc, diag::err_member_qualification)
4737         << Name << SS.getRange();
4738     else if (isa<TranslationUnitDecl>(DC))
4739       Diag(Loc, diag::err_invalid_declarator_global_scope)
4740         << Name << SS.getRange();
4741     else if (isa<FunctionDecl>(Cur))
4742       Diag(Loc, diag::err_invalid_declarator_in_function)
4743         << Name << SS.getRange();
4744     else if (isa<BlockDecl>(Cur))
4745       Diag(Loc, diag::err_invalid_declarator_in_block)
4746         << Name << SS.getRange();
4747     else
4748       Diag(Loc, diag::err_invalid_declarator_scope)
4749       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4750 
4751     return true;
4752   }
4753 
4754   if (Cur->isRecord()) {
4755     // Cannot qualify members within a class.
4756     Diag(Loc, diag::err_member_qualification)
4757       << Name << SS.getRange();
4758     SS.clear();
4759 
4760     // C++ constructors and destructors with incorrect scopes can break
4761     // our AST invariants by having the wrong underlying types. If
4762     // that's the case, then drop this declaration entirely.
4763     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4764          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4765         !Context.hasSameType(Name.getCXXNameType(),
4766                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4767       return true;
4768 
4769     return false;
4770   }
4771 
4772   // C++11 [dcl.meaning]p1:
4773   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4774   //   not begin with a decltype-specifer"
4775   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4776   while (SpecLoc.getPrefix())
4777     SpecLoc = SpecLoc.getPrefix();
4778   if (dyn_cast_or_null<DecltypeType>(
4779         SpecLoc.getNestedNameSpecifier()->getAsType()))
4780     Diag(Loc, diag::err_decltype_in_declarator)
4781       << SpecLoc.getTypeLoc().getSourceRange();
4782 
4783   return false;
4784 }
4785 
4786 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4787                                   MultiTemplateParamsArg TemplateParamLists) {
4788   // TODO: consider using NameInfo for diagnostic.
4789   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4790   DeclarationName Name = NameInfo.getName();
4791 
4792   // All of these full declarators require an identifier.  If it doesn't have
4793   // one, the ParsedFreeStandingDeclSpec action should be used.
4794   if (!Name) {
4795     if (!D.isInvalidType())  // Reject this if we think it is valid.
4796       Diag(D.getDeclSpec().getLocStart(),
4797            diag::err_declarator_need_ident)
4798         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4799     return nullptr;
4800   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4801     return nullptr;
4802 
4803   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4804   // we find one that is.
4805   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4806          (S->getFlags() & Scope::TemplateParamScope) != 0)
4807     S = S->getParent();
4808 
4809   DeclContext *DC = CurContext;
4810   if (D.getCXXScopeSpec().isInvalid())
4811     D.setInvalidType();
4812   else if (D.getCXXScopeSpec().isSet()) {
4813     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4814                                         UPPC_DeclarationQualifier))
4815       return nullptr;
4816 
4817     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4818     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4819     if (!DC || isa<EnumDecl>(DC)) {
4820       // If we could not compute the declaration context, it's because the
4821       // declaration context is dependent but does not refer to a class,
4822       // class template, or class template partial specialization. Complain
4823       // and return early, to avoid the coming semantic disaster.
4824       Diag(D.getIdentifierLoc(),
4825            diag::err_template_qualified_declarator_no_match)
4826         << D.getCXXScopeSpec().getScopeRep()
4827         << D.getCXXScopeSpec().getRange();
4828       return nullptr;
4829     }
4830     bool IsDependentContext = DC->isDependentContext();
4831 
4832     if (!IsDependentContext &&
4833         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4834       return nullptr;
4835 
4836     // If a class is incomplete, do not parse entities inside it.
4837     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4838       Diag(D.getIdentifierLoc(),
4839            diag::err_member_def_undefined_record)
4840         << Name << DC << D.getCXXScopeSpec().getRange();
4841       return nullptr;
4842     }
4843     if (!D.getDeclSpec().isFriendSpecified()) {
4844       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4845                                       Name, D.getIdentifierLoc())) {
4846         if (DC->isRecord())
4847           return nullptr;
4848 
4849         D.setInvalidType();
4850       }
4851     }
4852 
4853     // Check whether we need to rebuild the type of the given
4854     // declaration in the current instantiation.
4855     if (EnteringContext && IsDependentContext &&
4856         TemplateParamLists.size() != 0) {
4857       ContextRAII SavedContext(*this, DC);
4858       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4859         D.setInvalidType();
4860     }
4861   }
4862 
4863   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4864   QualType R = TInfo->getType();
4865 
4866   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4867     // If this is a typedef, we'll end up spewing multiple diagnostics.
4868     // Just return early; it's safer. If this is a function, let the
4869     // "constructor cannot have a return type" diagnostic handle it.
4870     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4871       return nullptr;
4872 
4873   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4874                                       UPPC_DeclarationType))
4875     D.setInvalidType();
4876 
4877   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4878                         ForRedeclaration);
4879 
4880   // See if this is a redefinition of a variable in the same scope.
4881   if (!D.getCXXScopeSpec().isSet()) {
4882     bool IsLinkageLookup = false;
4883     bool CreateBuiltins = false;
4884 
4885     // If the declaration we're planning to build will be a function
4886     // or object with linkage, then look for another declaration with
4887     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4888     //
4889     // If the declaration we're planning to build will be declared with
4890     // external linkage in the translation unit, create any builtin with
4891     // the same name.
4892     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4893       /* Do nothing*/;
4894     else if (CurContext->isFunctionOrMethod() &&
4895              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4896               R->isFunctionType())) {
4897       IsLinkageLookup = true;
4898       CreateBuiltins =
4899           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4900     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4901                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4902       CreateBuiltins = true;
4903 
4904     if (IsLinkageLookup)
4905       Previous.clear(LookupRedeclarationWithLinkage);
4906 
4907     LookupName(Previous, S, CreateBuiltins);
4908   } else { // Something like "int foo::x;"
4909     LookupQualifiedName(Previous, DC);
4910 
4911     // C++ [dcl.meaning]p1:
4912     //   When the declarator-id is qualified, the declaration shall refer to a
4913     //  previously declared member of the class or namespace to which the
4914     //  qualifier refers (or, in the case of a namespace, of an element of the
4915     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4916     //  thereof; [...]
4917     //
4918     // Note that we already checked the context above, and that we do not have
4919     // enough information to make sure that Previous contains the declaration
4920     // we want to match. For example, given:
4921     //
4922     //   class X {
4923     //     void f();
4924     //     void f(float);
4925     //   };
4926     //
4927     //   void X::f(int) { } // ill-formed
4928     //
4929     // In this case, Previous will point to the overload set
4930     // containing the two f's declared in X, but neither of them
4931     // matches.
4932 
4933     // C++ [dcl.meaning]p1:
4934     //   [...] the member shall not merely have been introduced by a
4935     //   using-declaration in the scope of the class or namespace nominated by
4936     //   the nested-name-specifier of the declarator-id.
4937     RemoveUsingDecls(Previous);
4938   }
4939 
4940   if (Previous.isSingleResult() &&
4941       Previous.getFoundDecl()->isTemplateParameter()) {
4942     // Maybe we will complain about the shadowed template parameter.
4943     if (!D.isInvalidType())
4944       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4945                                       Previous.getFoundDecl());
4946 
4947     // Just pretend that we didn't see the previous declaration.
4948     Previous.clear();
4949   }
4950 
4951   // In C++, the previous declaration we find might be a tag type
4952   // (class or enum). In this case, the new declaration will hide the
4953   // tag type. Note that this does does not apply if we're declaring a
4954   // typedef (C++ [dcl.typedef]p4).
4955   if (Previous.isSingleTagDecl() &&
4956       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4957     Previous.clear();
4958 
4959   // Check that there are no default arguments other than in the parameters
4960   // of a function declaration (C++ only).
4961   if (getLangOpts().CPlusPlus)
4962     CheckExtraCXXDefaultArguments(D);
4963 
4964   if (D.getDeclSpec().isConceptSpecified()) {
4965     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4966     // applied only to the definition of a function template or variable
4967     // template, declared in namespace scope
4968     if (!TemplateParamLists.size()) {
4969       Diag(D.getDeclSpec().getConceptSpecLoc(),
4970            diag:: err_concept_wrong_decl_kind);
4971       return nullptr;
4972     }
4973 
4974     if (!DC->getRedeclContext()->isFileContext()) {
4975       Diag(D.getIdentifierLoc(),
4976            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4977       return nullptr;
4978     }
4979   }
4980 
4981   NamedDecl *New;
4982 
4983   bool AddToScope = true;
4984   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4985     if (TemplateParamLists.size()) {
4986       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4987       return nullptr;
4988     }
4989 
4990     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4991   } else if (R->isFunctionType()) {
4992     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4993                                   TemplateParamLists,
4994                                   AddToScope);
4995   } else {
4996     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4997                                   AddToScope);
4998   }
4999 
5000   if (!New)
5001     return nullptr;
5002 
5003   // If this has an identifier and is not an invalid redeclaration or
5004   // function template specialization, add it to the scope stack.
5005   if (New->getDeclName() && AddToScope &&
5006        !(D.isRedeclaration() && New->isInvalidDecl())) {
5007     // Only make a locally-scoped extern declaration visible if it is the first
5008     // declaration of this entity. Qualified lookup for such an entity should
5009     // only find this declaration if there is no visible declaration of it.
5010     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5011     PushOnScopeChains(New, S, AddToContext);
5012     if (!AddToContext)
5013       CurContext->addHiddenDecl(New);
5014   }
5015 
5016   return New;
5017 }
5018 
5019 /// Helper method to turn variable array types into constant array
5020 /// types in certain situations which would otherwise be errors (for
5021 /// GCC compatibility).
5022 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5023                                                     ASTContext &Context,
5024                                                     bool &SizeIsNegative,
5025                                                     llvm::APSInt &Oversized) {
5026   // This method tries to turn a variable array into a constant
5027   // array even when the size isn't an ICE.  This is necessary
5028   // for compatibility with code that depends on gcc's buggy
5029   // constant expression folding, like struct {char x[(int)(char*)2];}
5030   SizeIsNegative = false;
5031   Oversized = 0;
5032 
5033   if (T->isDependentType())
5034     return QualType();
5035 
5036   QualifierCollector Qs;
5037   const Type *Ty = Qs.strip(T);
5038 
5039   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5040     QualType Pointee = PTy->getPointeeType();
5041     QualType FixedType =
5042         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5043                                             Oversized);
5044     if (FixedType.isNull()) return FixedType;
5045     FixedType = Context.getPointerType(FixedType);
5046     return Qs.apply(Context, FixedType);
5047   }
5048   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5049     QualType Inner = PTy->getInnerType();
5050     QualType FixedType =
5051         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5052                                             Oversized);
5053     if (FixedType.isNull()) return FixedType;
5054     FixedType = Context.getParenType(FixedType);
5055     return Qs.apply(Context, FixedType);
5056   }
5057 
5058   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5059   if (!VLATy)
5060     return QualType();
5061   // FIXME: We should probably handle this case
5062   if (VLATy->getElementType()->isVariablyModifiedType())
5063     return QualType();
5064 
5065   llvm::APSInt Res;
5066   if (!VLATy->getSizeExpr() ||
5067       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5068     return QualType();
5069 
5070   // Check whether the array size is negative.
5071   if (Res.isSigned() && Res.isNegative()) {
5072     SizeIsNegative = true;
5073     return QualType();
5074   }
5075 
5076   // Check whether the array is too large to be addressed.
5077   unsigned ActiveSizeBits
5078     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5079                                               Res);
5080   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5081     Oversized = Res;
5082     return QualType();
5083   }
5084 
5085   return Context.getConstantArrayType(VLATy->getElementType(),
5086                                       Res, ArrayType::Normal, 0);
5087 }
5088 
5089 static void
5090 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5091   SrcTL = SrcTL.getUnqualifiedLoc();
5092   DstTL = DstTL.getUnqualifiedLoc();
5093   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5094     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5095     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5096                                       DstPTL.getPointeeLoc());
5097     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5098     return;
5099   }
5100   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5101     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5102     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5103                                       DstPTL.getInnerLoc());
5104     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5105     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5106     return;
5107   }
5108   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5109   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5110   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5111   TypeLoc DstElemTL = DstATL.getElementLoc();
5112   DstElemTL.initializeFullCopy(SrcElemTL);
5113   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5114   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5115   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5116 }
5117 
5118 /// Helper method to turn variable array types into constant array
5119 /// types in certain situations which would otherwise be errors (for
5120 /// GCC compatibility).
5121 static TypeSourceInfo*
5122 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5123                                               ASTContext &Context,
5124                                               bool &SizeIsNegative,
5125                                               llvm::APSInt &Oversized) {
5126   QualType FixedTy
5127     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5128                                           SizeIsNegative, Oversized);
5129   if (FixedTy.isNull())
5130     return nullptr;
5131   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5132   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5133                                     FixedTInfo->getTypeLoc());
5134   return FixedTInfo;
5135 }
5136 
5137 /// \brief Register the given locally-scoped extern "C" declaration so
5138 /// that it can be found later for redeclarations. We include any extern "C"
5139 /// declaration that is not visible in the translation unit here, not just
5140 /// function-scope declarations.
5141 void
5142 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5143   if (!getLangOpts().CPlusPlus &&
5144       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5145     // Don't need to track declarations in the TU in C.
5146     return;
5147 
5148   // Note that we have a locally-scoped external with this name.
5149   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5150 }
5151 
5152 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5153   // FIXME: We can have multiple results via __attribute__((overloadable)).
5154   auto Result = Context.getExternCContextDecl()->lookup(Name);
5155   return Result.empty() ? nullptr : *Result.begin();
5156 }
5157 
5158 /// \brief Diagnose function specifiers on a declaration of an identifier that
5159 /// does not identify a function.
5160 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5161   // FIXME: We should probably indicate the identifier in question to avoid
5162   // confusion for constructs like "inline int a(), b;"
5163   if (DS.isInlineSpecified())
5164     Diag(DS.getInlineSpecLoc(),
5165          diag::err_inline_non_function);
5166 
5167   if (DS.isVirtualSpecified())
5168     Diag(DS.getVirtualSpecLoc(),
5169          diag::err_virtual_non_function);
5170 
5171   if (DS.isExplicitSpecified())
5172     Diag(DS.getExplicitSpecLoc(),
5173          diag::err_explicit_non_function);
5174 
5175   if (DS.isNoreturnSpecified())
5176     Diag(DS.getNoreturnSpecLoc(),
5177          diag::err_noreturn_non_function);
5178 }
5179 
5180 NamedDecl*
5181 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5182                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5183   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5184   if (D.getCXXScopeSpec().isSet()) {
5185     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5186       << D.getCXXScopeSpec().getRange();
5187     D.setInvalidType();
5188     // Pretend we didn't see the scope specifier.
5189     DC = CurContext;
5190     Previous.clear();
5191   }
5192 
5193   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5194 
5195   if (D.getDeclSpec().isConstexprSpecified())
5196     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5197       << 1;
5198   if (D.getDeclSpec().isConceptSpecified())
5199     Diag(D.getDeclSpec().getConceptSpecLoc(),
5200          diag::err_concept_wrong_decl_kind);
5201 
5202   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5203     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5204       << D.getName().getSourceRange();
5205     return nullptr;
5206   }
5207 
5208   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5209   if (!NewTD) return nullptr;
5210 
5211   // Handle attributes prior to checking for duplicates in MergeVarDecl
5212   ProcessDeclAttributes(S, NewTD, D);
5213 
5214   CheckTypedefForVariablyModifiedType(S, NewTD);
5215 
5216   bool Redeclaration = D.isRedeclaration();
5217   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5218   D.setRedeclaration(Redeclaration);
5219   return ND;
5220 }
5221 
5222 void
5223 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5224   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5225   // then it shall have block scope.
5226   // Note that variably modified types must be fixed before merging the decl so
5227   // that redeclarations will match.
5228   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5229   QualType T = TInfo->getType();
5230   if (T->isVariablyModifiedType()) {
5231     getCurFunction()->setHasBranchProtectedScope();
5232 
5233     if (S->getFnParent() == nullptr) {
5234       bool SizeIsNegative;
5235       llvm::APSInt Oversized;
5236       TypeSourceInfo *FixedTInfo =
5237         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5238                                                       SizeIsNegative,
5239                                                       Oversized);
5240       if (FixedTInfo) {
5241         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5242         NewTD->setTypeSourceInfo(FixedTInfo);
5243       } else {
5244         if (SizeIsNegative)
5245           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5246         else if (T->isVariableArrayType())
5247           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5248         else if (Oversized.getBoolValue())
5249           Diag(NewTD->getLocation(), diag::err_array_too_large)
5250             << Oversized.toString(10);
5251         else
5252           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5253         NewTD->setInvalidDecl();
5254       }
5255     }
5256   }
5257 }
5258 
5259 
5260 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5261 /// declares a typedef-name, either using the 'typedef' type specifier or via
5262 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5263 NamedDecl*
5264 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5265                            LookupResult &Previous, bool &Redeclaration) {
5266   // Merge the decl with the existing one if appropriate. If the decl is
5267   // in an outer scope, it isn't the same thing.
5268   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5269                        /*AllowInlineNamespace*/false);
5270   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5271   if (!Previous.empty()) {
5272     Redeclaration = true;
5273     MergeTypedefNameDecl(S, NewTD, Previous);
5274   }
5275 
5276   // If this is the C FILE type, notify the AST context.
5277   if (IdentifierInfo *II = NewTD->getIdentifier())
5278     if (!NewTD->isInvalidDecl() &&
5279         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5280       if (II->isStr("FILE"))
5281         Context.setFILEDecl(NewTD);
5282       else if (II->isStr("jmp_buf"))
5283         Context.setjmp_bufDecl(NewTD);
5284       else if (II->isStr("sigjmp_buf"))
5285         Context.setsigjmp_bufDecl(NewTD);
5286       else if (II->isStr("ucontext_t"))
5287         Context.setucontext_tDecl(NewTD);
5288     }
5289 
5290   return NewTD;
5291 }
5292 
5293 /// \brief Determines whether the given declaration is an out-of-scope
5294 /// previous declaration.
5295 ///
5296 /// This routine should be invoked when name lookup has found a
5297 /// previous declaration (PrevDecl) that is not in the scope where a
5298 /// new declaration by the same name is being introduced. If the new
5299 /// declaration occurs in a local scope, previous declarations with
5300 /// linkage may still be considered previous declarations (C99
5301 /// 6.2.2p4-5, C++ [basic.link]p6).
5302 ///
5303 /// \param PrevDecl the previous declaration found by name
5304 /// lookup
5305 ///
5306 /// \param DC the context in which the new declaration is being
5307 /// declared.
5308 ///
5309 /// \returns true if PrevDecl is an out-of-scope previous declaration
5310 /// for a new delcaration with the same name.
5311 static bool
5312 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5313                                 ASTContext &Context) {
5314   if (!PrevDecl)
5315     return false;
5316 
5317   if (!PrevDecl->hasLinkage())
5318     return false;
5319 
5320   if (Context.getLangOpts().CPlusPlus) {
5321     // C++ [basic.link]p6:
5322     //   If there is a visible declaration of an entity with linkage
5323     //   having the same name and type, ignoring entities declared
5324     //   outside the innermost enclosing namespace scope, the block
5325     //   scope declaration declares that same entity and receives the
5326     //   linkage of the previous declaration.
5327     DeclContext *OuterContext = DC->getRedeclContext();
5328     if (!OuterContext->isFunctionOrMethod())
5329       // This rule only applies to block-scope declarations.
5330       return false;
5331 
5332     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5333     if (PrevOuterContext->isRecord())
5334       // We found a member function: ignore it.
5335       return false;
5336 
5337     // Find the innermost enclosing namespace for the new and
5338     // previous declarations.
5339     OuterContext = OuterContext->getEnclosingNamespaceContext();
5340     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5341 
5342     // The previous declaration is in a different namespace, so it
5343     // isn't the same function.
5344     if (!OuterContext->Equals(PrevOuterContext))
5345       return false;
5346   }
5347 
5348   return true;
5349 }
5350 
5351 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5352   CXXScopeSpec &SS = D.getCXXScopeSpec();
5353   if (!SS.isSet()) return;
5354   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5355 }
5356 
5357 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5358   QualType type = decl->getType();
5359   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5360   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5361     // Various kinds of declaration aren't allowed to be __autoreleasing.
5362     unsigned kind = -1U;
5363     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5364       if (var->hasAttr<BlocksAttr>())
5365         kind = 0; // __block
5366       else if (!var->hasLocalStorage())
5367         kind = 1; // global
5368     } else if (isa<ObjCIvarDecl>(decl)) {
5369       kind = 3; // ivar
5370     } else if (isa<FieldDecl>(decl)) {
5371       kind = 2; // field
5372     }
5373 
5374     if (kind != -1U) {
5375       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5376         << kind;
5377     }
5378   } else if (lifetime == Qualifiers::OCL_None) {
5379     // Try to infer lifetime.
5380     if (!type->isObjCLifetimeType())
5381       return false;
5382 
5383     lifetime = type->getObjCARCImplicitLifetime();
5384     type = Context.getLifetimeQualifiedType(type, lifetime);
5385     decl->setType(type);
5386   }
5387 
5388   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5389     // Thread-local variables cannot have lifetime.
5390     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5391         var->getTLSKind()) {
5392       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5393         << var->getType();
5394       return true;
5395     }
5396   }
5397 
5398   return false;
5399 }
5400 
5401 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5402   // Ensure that an auto decl is deduced otherwise the checks below might cache
5403   // the wrong linkage.
5404   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5405 
5406   // 'weak' only applies to declarations with external linkage.
5407   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5408     if (!ND.isExternallyVisible()) {
5409       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5410       ND.dropAttr<WeakAttr>();
5411     }
5412   }
5413   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5414     if (ND.isExternallyVisible()) {
5415       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5416       ND.dropAttr<WeakRefAttr>();
5417       ND.dropAttr<AliasAttr>();
5418     }
5419   }
5420 
5421   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5422     if (VD->hasInit()) {
5423       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5424         assert(VD->isThisDeclarationADefinition() &&
5425                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5426         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5427         VD->dropAttr<AliasAttr>();
5428       }
5429     }
5430   }
5431 
5432   // 'selectany' only applies to externally visible variable declarations.
5433   // It does not apply to functions.
5434   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5435     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5436       S.Diag(Attr->getLocation(),
5437              diag::err_attribute_selectany_non_extern_data);
5438       ND.dropAttr<SelectAnyAttr>();
5439     }
5440   }
5441 
5442   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5443     // dll attributes require external linkage. Static locals may have external
5444     // linkage but still cannot be explicitly imported or exported.
5445     auto *VD = dyn_cast<VarDecl>(&ND);
5446     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5447       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5448         << &ND << Attr;
5449       ND.setInvalidDecl();
5450     }
5451   }
5452 
5453   // Virtual functions cannot be marked as 'notail'.
5454   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5455     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5456       if (MD->isVirtual()) {
5457         S.Diag(ND.getLocation(),
5458                diag::err_invalid_attribute_on_virtual_function)
5459             << Attr;
5460         ND.dropAttr<NotTailCalledAttr>();
5461       }
5462 }
5463 
5464 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5465                                            NamedDecl *NewDecl,
5466                                            bool IsSpecialization) {
5467   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5468     OldDecl = OldTD->getTemplatedDecl();
5469   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5470     NewDecl = NewTD->getTemplatedDecl();
5471 
5472   if (!OldDecl || !NewDecl)
5473     return;
5474 
5475   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5476   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5477   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5478   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5479 
5480   // dllimport and dllexport are inheritable attributes so we have to exclude
5481   // inherited attribute instances.
5482   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5483                     (NewExportAttr && !NewExportAttr->isInherited());
5484 
5485   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5486   // the only exception being explicit specializations.
5487   // Implicitly generated declarations are also excluded for now because there
5488   // is no other way to switch these to use dllimport or dllexport.
5489   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5490 
5491   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5492     // Allow with a warning for free functions and global variables.
5493     bool JustWarn = false;
5494     if (!OldDecl->isCXXClassMember()) {
5495       auto *VD = dyn_cast<VarDecl>(OldDecl);
5496       if (VD && !VD->getDescribedVarTemplate())
5497         JustWarn = true;
5498       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5499       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5500         JustWarn = true;
5501     }
5502 
5503     // We cannot change a declaration that's been used because IR has already
5504     // been emitted. Dllimported functions will still work though (modulo
5505     // address equality) as they can use the thunk.
5506     if (OldDecl->isUsed())
5507       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5508         JustWarn = false;
5509 
5510     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5511                                : diag::err_attribute_dll_redeclaration;
5512     S.Diag(NewDecl->getLocation(), DiagID)
5513         << NewDecl
5514         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5515     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5516     if (!JustWarn) {
5517       NewDecl->setInvalidDecl();
5518       return;
5519     }
5520   }
5521 
5522   // A redeclaration is not allowed to drop a dllimport attribute, the only
5523   // exceptions being inline function definitions, local extern declarations,
5524   // and qualified friend declarations.
5525   // NB: MSVC converts such a declaration to dllexport.
5526   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5527   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5528     // Ignore static data because out-of-line definitions are diagnosed
5529     // separately.
5530     IsStaticDataMember = VD->isStaticDataMember();
5531   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5532     IsInline = FD->isInlined();
5533     IsQualifiedFriend = FD->getQualifier() &&
5534                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5535   }
5536 
5537   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5538       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5539     S.Diag(NewDecl->getLocation(),
5540            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5541       << NewDecl << OldImportAttr;
5542     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5543     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5544     OldDecl->dropAttr<DLLImportAttr>();
5545     NewDecl->dropAttr<DLLImportAttr>();
5546   } else if (IsInline && OldImportAttr &&
5547              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5548     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5549     OldDecl->dropAttr<DLLImportAttr>();
5550     NewDecl->dropAttr<DLLImportAttr>();
5551     S.Diag(NewDecl->getLocation(),
5552            diag::warn_dllimport_dropped_from_inline_function)
5553         << NewDecl << OldImportAttr;
5554   }
5555 }
5556 
5557 /// Given that we are within the definition of the given function,
5558 /// will that definition behave like C99's 'inline', where the
5559 /// definition is discarded except for optimization purposes?
5560 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5561   // Try to avoid calling GetGVALinkageForFunction.
5562 
5563   // All cases of this require the 'inline' keyword.
5564   if (!FD->isInlined()) return false;
5565 
5566   // This is only possible in C++ with the gnu_inline attribute.
5567   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5568     return false;
5569 
5570   // Okay, go ahead and call the relatively-more-expensive function.
5571 
5572 #ifndef NDEBUG
5573   // AST quite reasonably asserts that it's working on a function
5574   // definition.  We don't really have a way to tell it that we're
5575   // currently defining the function, so just lie to it in +Asserts
5576   // builds.  This is an awful hack.
5577   FD->setLazyBody(1);
5578 #endif
5579 
5580   bool isC99Inline =
5581       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5582 
5583 #ifndef NDEBUG
5584   FD->setLazyBody(0);
5585 #endif
5586 
5587   return isC99Inline;
5588 }
5589 
5590 /// Determine whether a variable is extern "C" prior to attaching
5591 /// an initializer. We can't just call isExternC() here, because that
5592 /// will also compute and cache whether the declaration is externally
5593 /// visible, which might change when we attach the initializer.
5594 ///
5595 /// This can only be used if the declaration is known to not be a
5596 /// redeclaration of an internal linkage declaration.
5597 ///
5598 /// For instance:
5599 ///
5600 ///   auto x = []{};
5601 ///
5602 /// Attaching the initializer here makes this declaration not externally
5603 /// visible, because its type has internal linkage.
5604 ///
5605 /// FIXME: This is a hack.
5606 template<typename T>
5607 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5608   if (S.getLangOpts().CPlusPlus) {
5609     // In C++, the overloadable attribute negates the effects of extern "C".
5610     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5611       return false;
5612 
5613     // So do CUDA's host/device attributes if overloading is enabled.
5614     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5615         (D->template hasAttr<CUDADeviceAttr>() ||
5616          D->template hasAttr<CUDAHostAttr>()))
5617       return false;
5618   }
5619   return D->isExternC();
5620 }
5621 
5622 static bool shouldConsiderLinkage(const VarDecl *VD) {
5623   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5624   if (DC->isFunctionOrMethod())
5625     return VD->hasExternalStorage();
5626   if (DC->isFileContext())
5627     return true;
5628   if (DC->isRecord())
5629     return false;
5630   llvm_unreachable("Unexpected context");
5631 }
5632 
5633 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5634   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5635   if (DC->isFileContext() || DC->isFunctionOrMethod())
5636     return true;
5637   if (DC->isRecord())
5638     return false;
5639   llvm_unreachable("Unexpected context");
5640 }
5641 
5642 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5643                           AttributeList::Kind Kind) {
5644   for (const AttributeList *L = AttrList; L; L = L->getNext())
5645     if (L->getKind() == Kind)
5646       return true;
5647   return false;
5648 }
5649 
5650 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5651                           AttributeList::Kind Kind) {
5652   // Check decl attributes on the DeclSpec.
5653   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5654     return true;
5655 
5656   // Walk the declarator structure, checking decl attributes that were in a type
5657   // position to the decl itself.
5658   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5659     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5660       return true;
5661   }
5662 
5663   // Finally, check attributes on the decl itself.
5664   return hasParsedAttr(S, PD.getAttributes(), Kind);
5665 }
5666 
5667 /// Adjust the \c DeclContext for a function or variable that might be a
5668 /// function-local external declaration.
5669 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5670   if (!DC->isFunctionOrMethod())
5671     return false;
5672 
5673   // If this is a local extern function or variable declared within a function
5674   // template, don't add it into the enclosing namespace scope until it is
5675   // instantiated; it might have a dependent type right now.
5676   if (DC->isDependentContext())
5677     return true;
5678 
5679   // C++11 [basic.link]p7:
5680   //   When a block scope declaration of an entity with linkage is not found to
5681   //   refer to some other declaration, then that entity is a member of the
5682   //   innermost enclosing namespace.
5683   //
5684   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5685   // semantically-enclosing namespace, not a lexically-enclosing one.
5686   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5687     DC = DC->getParent();
5688   return true;
5689 }
5690 
5691 /// \brief Returns true if given declaration has external C language linkage.
5692 static bool isDeclExternC(const Decl *D) {
5693   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5694     return FD->isExternC();
5695   if (const auto *VD = dyn_cast<VarDecl>(D))
5696     return VD->isExternC();
5697 
5698   llvm_unreachable("Unknown type of decl!");
5699 }
5700 
5701 NamedDecl *
5702 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5703                               TypeSourceInfo *TInfo, LookupResult &Previous,
5704                               MultiTemplateParamsArg TemplateParamLists,
5705                               bool &AddToScope) {
5706   QualType R = TInfo->getType();
5707   DeclarationName Name = GetNameForDeclarator(D).getName();
5708 
5709   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5710   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5711 
5712   // dllimport globals without explicit storage class are treated as extern. We
5713   // have to change the storage class this early to get the right DeclContext.
5714   if (SC == SC_None && !DC->isRecord() &&
5715       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5716       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5717     SC = SC_Extern;
5718 
5719   DeclContext *OriginalDC = DC;
5720   bool IsLocalExternDecl = SC == SC_Extern &&
5721                            adjustContextForLocalExternDecl(DC);
5722 
5723   if (getLangOpts().OpenCL) {
5724     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5725     QualType NR = R;
5726     while (NR->isPointerType()) {
5727       if (NR->isFunctionPointerType()) {
5728         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5729         D.setInvalidType();
5730         break;
5731       }
5732       NR = NR->getPointeeType();
5733     }
5734 
5735     if (!getOpenCLOptions().cl_khr_fp16) {
5736       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5737       // half array type (unless the cl_khr_fp16 extension is enabled).
5738       if (Context.getBaseElementType(R)->isHalfType()) {
5739         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5740         D.setInvalidType();
5741       }
5742     }
5743   }
5744 
5745   if (SCSpec == DeclSpec::SCS_mutable) {
5746     // mutable can only appear on non-static class members, so it's always
5747     // an error here
5748     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5749     D.setInvalidType();
5750     SC = SC_None;
5751   }
5752 
5753   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5754       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5755                               D.getDeclSpec().getStorageClassSpecLoc())) {
5756     // In C++11, the 'register' storage class specifier is deprecated.
5757     // Suppress the warning in system macros, it's used in macros in some
5758     // popular C system headers, such as in glibc's htonl() macro.
5759     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5760          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5761                                    : diag::warn_deprecated_register)
5762       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5763   }
5764 
5765   IdentifierInfo *II = Name.getAsIdentifierInfo();
5766   if (!II) {
5767     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5768       << Name;
5769     return nullptr;
5770   }
5771 
5772   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5773 
5774   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5775     // C99 6.9p2: The storage-class specifiers auto and register shall not
5776     // appear in the declaration specifiers in an external declaration.
5777     // Global Register+Asm is a GNU extension we support.
5778     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5779       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5780       D.setInvalidType();
5781     }
5782   }
5783 
5784   if (getLangOpts().OpenCL) {
5785     // OpenCL v1.2 s6.9.b p4:
5786     // The sampler type cannot be used with the __local and __global address
5787     // space qualifiers.
5788     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5789       R.getAddressSpace() == LangAS::opencl_global)) {
5790       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5791     }
5792 
5793     // OpenCL 1.2 spec, p6.9 r:
5794     // The event type cannot be used to declare a program scope variable.
5795     // The event type cannot be used with the __local, __constant and __global
5796     // address space qualifiers.
5797     if (R->isEventT()) {
5798       if (S->getParent() == nullptr) {
5799         Diag(D.getLocStart(), diag::err_event_t_global_var);
5800         D.setInvalidType();
5801       }
5802 
5803       if (R.getAddressSpace()) {
5804         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5805         D.setInvalidType();
5806       }
5807     }
5808   }
5809 
5810   bool IsExplicitSpecialization = false;
5811   bool IsVariableTemplateSpecialization = false;
5812   bool IsPartialSpecialization = false;
5813   bool IsVariableTemplate = false;
5814   VarDecl *NewVD = nullptr;
5815   VarTemplateDecl *NewTemplate = nullptr;
5816   TemplateParameterList *TemplateParams = nullptr;
5817   if (!getLangOpts().CPlusPlus) {
5818     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5819                             D.getIdentifierLoc(), II,
5820                             R, TInfo, SC);
5821 
5822     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5823       ParsingInitForAutoVars.insert(NewVD);
5824 
5825     if (D.isInvalidType())
5826       NewVD->setInvalidDecl();
5827   } else {
5828     bool Invalid = false;
5829 
5830     if (DC->isRecord() && !CurContext->isRecord()) {
5831       // This is an out-of-line definition of a static data member.
5832       switch (SC) {
5833       case SC_None:
5834         break;
5835       case SC_Static:
5836         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5837              diag::err_static_out_of_line)
5838           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5839         break;
5840       case SC_Auto:
5841       case SC_Register:
5842       case SC_Extern:
5843         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5844         // to names of variables declared in a block or to function parameters.
5845         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5846         // of class members
5847 
5848         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5849              diag::err_storage_class_for_static_member)
5850           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5851         break;
5852       case SC_PrivateExtern:
5853         llvm_unreachable("C storage class in c++!");
5854       }
5855     }
5856 
5857     if (SC == SC_Static && CurContext->isRecord()) {
5858       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5859         if (RD->isLocalClass())
5860           Diag(D.getIdentifierLoc(),
5861                diag::err_static_data_member_not_allowed_in_local_class)
5862             << Name << RD->getDeclName();
5863 
5864         // C++98 [class.union]p1: If a union contains a static data member,
5865         // the program is ill-formed. C++11 drops this restriction.
5866         if (RD->isUnion())
5867           Diag(D.getIdentifierLoc(),
5868                getLangOpts().CPlusPlus11
5869                  ? diag::warn_cxx98_compat_static_data_member_in_union
5870                  : diag::ext_static_data_member_in_union) << Name;
5871         // We conservatively disallow static data members in anonymous structs.
5872         else if (!RD->getDeclName())
5873           Diag(D.getIdentifierLoc(),
5874                diag::err_static_data_member_not_allowed_in_anon_struct)
5875             << Name << RD->isUnion();
5876       }
5877     }
5878 
5879     // Match up the template parameter lists with the scope specifier, then
5880     // determine whether we have a template or a template specialization.
5881     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5882         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5883         D.getCXXScopeSpec(),
5884         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5885             ? D.getName().TemplateId
5886             : nullptr,
5887         TemplateParamLists,
5888         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5889 
5890     if (TemplateParams) {
5891       if (!TemplateParams->size() &&
5892           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5893         // There is an extraneous 'template<>' for this variable. Complain
5894         // about it, but allow the declaration of the variable.
5895         Diag(TemplateParams->getTemplateLoc(),
5896              diag::err_template_variable_noparams)
5897           << II
5898           << SourceRange(TemplateParams->getTemplateLoc(),
5899                          TemplateParams->getRAngleLoc());
5900         TemplateParams = nullptr;
5901       } else {
5902         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5903           // This is an explicit specialization or a partial specialization.
5904           // FIXME: Check that we can declare a specialization here.
5905           IsVariableTemplateSpecialization = true;
5906           IsPartialSpecialization = TemplateParams->size() > 0;
5907         } else { // if (TemplateParams->size() > 0)
5908           // This is a template declaration.
5909           IsVariableTemplate = true;
5910 
5911           // Check that we can declare a template here.
5912           if (CheckTemplateDeclScope(S, TemplateParams))
5913             return nullptr;
5914 
5915           // Only C++1y supports variable templates (N3651).
5916           Diag(D.getIdentifierLoc(),
5917                getLangOpts().CPlusPlus14
5918                    ? diag::warn_cxx11_compat_variable_template
5919                    : diag::ext_variable_template);
5920         }
5921       }
5922     } else {
5923       assert(
5924           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5925           "should have a 'template<>' for this decl");
5926     }
5927 
5928     if (IsVariableTemplateSpecialization) {
5929       SourceLocation TemplateKWLoc =
5930           TemplateParamLists.size() > 0
5931               ? TemplateParamLists[0]->getTemplateLoc()
5932               : SourceLocation();
5933       DeclResult Res = ActOnVarTemplateSpecialization(
5934           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5935           IsPartialSpecialization);
5936       if (Res.isInvalid())
5937         return nullptr;
5938       NewVD = cast<VarDecl>(Res.get());
5939       AddToScope = false;
5940     } else
5941       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5942                               D.getIdentifierLoc(), II, R, TInfo, SC);
5943 
5944     // If this is supposed to be a variable template, create it as such.
5945     if (IsVariableTemplate) {
5946       NewTemplate =
5947           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5948                                   TemplateParams, NewVD);
5949       NewVD->setDescribedVarTemplate(NewTemplate);
5950     }
5951 
5952     // If this decl has an auto type in need of deduction, make a note of the
5953     // Decl so we can diagnose uses of it in its own initializer.
5954     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5955       ParsingInitForAutoVars.insert(NewVD);
5956 
5957     if (D.isInvalidType() || Invalid) {
5958       NewVD->setInvalidDecl();
5959       if (NewTemplate)
5960         NewTemplate->setInvalidDecl();
5961     }
5962 
5963     SetNestedNameSpecifier(NewVD, D);
5964 
5965     // If we have any template parameter lists that don't directly belong to
5966     // the variable (matching the scope specifier), store them.
5967     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5968     if (TemplateParamLists.size() > VDTemplateParamLists)
5969       NewVD->setTemplateParameterListsInfo(
5970           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5971 
5972     if (D.getDeclSpec().isConstexprSpecified())
5973       NewVD->setConstexpr(true);
5974 
5975     if (D.getDeclSpec().isConceptSpecified()) {
5976       NewVD->setConcept(true);
5977 
5978       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5979       // be declared with the thread_local, inline, friend, or constexpr
5980       // specifiers, [...]
5981       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5982         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5983              diag::err_concept_decl_invalid_specifiers)
5984             << 0 << 0;
5985         NewVD->setInvalidDecl(true);
5986       }
5987 
5988       if (D.getDeclSpec().isConstexprSpecified()) {
5989         Diag(D.getDeclSpec().getConstexprSpecLoc(),
5990              diag::err_concept_decl_invalid_specifiers)
5991             << 0 << 3;
5992         NewVD->setInvalidDecl(true);
5993       }
5994     }
5995   }
5996 
5997   // Set the lexical context. If the declarator has a C++ scope specifier, the
5998   // lexical context will be different from the semantic context.
5999   NewVD->setLexicalDeclContext(CurContext);
6000   if (NewTemplate)
6001     NewTemplate->setLexicalDeclContext(CurContext);
6002 
6003   if (IsLocalExternDecl)
6004     NewVD->setLocalExternDecl();
6005 
6006   bool EmitTLSUnsupportedError = false;
6007   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6008     // C++11 [dcl.stc]p4:
6009     //   When thread_local is applied to a variable of block scope the
6010     //   storage-class-specifier static is implied if it does not appear
6011     //   explicitly.
6012     // Core issue: 'static' is not implied if the variable is declared
6013     //   'extern'.
6014     if (NewVD->hasLocalStorage() &&
6015         (SCSpec != DeclSpec::SCS_unspecified ||
6016          TSCS != DeclSpec::TSCS_thread_local ||
6017          !DC->isFunctionOrMethod()))
6018       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6019            diag::err_thread_non_global)
6020         << DeclSpec::getSpecifierName(TSCS);
6021     else if (!Context.getTargetInfo().isTLSSupported()) {
6022       if (getLangOpts().CUDA) {
6023         // Postpone error emission until we've collected attributes required to
6024         // figure out whether it's a host or device variable and whether the
6025         // error should be ignored.
6026         EmitTLSUnsupportedError = true;
6027         // We still need to mark the variable as TLS so it shows up in AST with
6028         // proper storage class for other tools to use even if we're not going
6029         // to emit any code for it.
6030         NewVD->setTSCSpec(TSCS);
6031       } else
6032         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6033              diag::err_thread_unsupported);
6034     } else
6035       NewVD->setTSCSpec(TSCS);
6036   }
6037 
6038   // C99 6.7.4p3
6039   //   An inline definition of a function with external linkage shall
6040   //   not contain a definition of a modifiable object with static or
6041   //   thread storage duration...
6042   // We only apply this when the function is required to be defined
6043   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6044   // that a local variable with thread storage duration still has to
6045   // be marked 'static'.  Also note that it's possible to get these
6046   // semantics in C++ using __attribute__((gnu_inline)).
6047   if (SC == SC_Static && S->getFnParent() != nullptr &&
6048       !NewVD->getType().isConstQualified()) {
6049     FunctionDecl *CurFD = getCurFunctionDecl();
6050     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6051       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6052            diag::warn_static_local_in_extern_inline);
6053       MaybeSuggestAddingStaticToDecl(CurFD);
6054     }
6055   }
6056 
6057   if (D.getDeclSpec().isModulePrivateSpecified()) {
6058     if (IsVariableTemplateSpecialization)
6059       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6060           << (IsPartialSpecialization ? 1 : 0)
6061           << FixItHint::CreateRemoval(
6062                  D.getDeclSpec().getModulePrivateSpecLoc());
6063     else if (IsExplicitSpecialization)
6064       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6065         << 2
6066         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6067     else if (NewVD->hasLocalStorage())
6068       Diag(NewVD->getLocation(), diag::err_module_private_local)
6069         << 0 << NewVD->getDeclName()
6070         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6071         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6072     else {
6073       NewVD->setModulePrivate();
6074       if (NewTemplate)
6075         NewTemplate->setModulePrivate();
6076     }
6077   }
6078 
6079   // Handle attributes prior to checking for duplicates in MergeVarDecl
6080   ProcessDeclAttributes(S, NewVD, D);
6081 
6082   if (getLangOpts().CUDA) {
6083     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6084       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6085            diag::err_thread_unsupported);
6086     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6087     // storage [duration]."
6088     if (SC == SC_None && S->getFnParent() != nullptr &&
6089         (NewVD->hasAttr<CUDASharedAttr>() ||
6090          NewVD->hasAttr<CUDAConstantAttr>())) {
6091       NewVD->setStorageClass(SC_Static);
6092     }
6093   }
6094 
6095   // Ensure that dllimport globals without explicit storage class are treated as
6096   // extern. The storage class is set above using parsed attributes. Now we can
6097   // check the VarDecl itself.
6098   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6099          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6100          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6101 
6102   // In auto-retain/release, infer strong retension for variables of
6103   // retainable type.
6104   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6105     NewVD->setInvalidDecl();
6106 
6107   // Handle GNU asm-label extension (encoded as an attribute).
6108   if (Expr *E = (Expr*)D.getAsmLabel()) {
6109     // The parser guarantees this is a string.
6110     StringLiteral *SE = cast<StringLiteral>(E);
6111     StringRef Label = SE->getString();
6112     if (S->getFnParent() != nullptr) {
6113       switch (SC) {
6114       case SC_None:
6115       case SC_Auto:
6116         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6117         break;
6118       case SC_Register:
6119         // Local Named register
6120         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6121             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6122           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6123         break;
6124       case SC_Static:
6125       case SC_Extern:
6126       case SC_PrivateExtern:
6127         break;
6128       }
6129     } else if (SC == SC_Register) {
6130       // Global Named register
6131       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6132         const auto &TI = Context.getTargetInfo();
6133         bool HasSizeMismatch;
6134 
6135         if (!TI.isValidGCCRegisterName(Label))
6136           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6137         else if (!TI.validateGlobalRegisterVariable(Label,
6138                                                     Context.getTypeSize(R),
6139                                                     HasSizeMismatch))
6140           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6141         else if (HasSizeMismatch)
6142           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6143       }
6144 
6145       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6146         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6147         NewVD->setInvalidDecl(true);
6148       }
6149     }
6150 
6151     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6152                                                 Context, Label, 0));
6153   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6154     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6155       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6156     if (I != ExtnameUndeclaredIdentifiers.end()) {
6157       if (isDeclExternC(NewVD)) {
6158         NewVD->addAttr(I->second);
6159         ExtnameUndeclaredIdentifiers.erase(I);
6160       } else
6161         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6162             << /*Variable*/1 << NewVD;
6163     }
6164   }
6165 
6166   // Diagnose shadowed variables before filtering for scope.
6167   if (D.getCXXScopeSpec().isEmpty())
6168     CheckShadow(S, NewVD, Previous);
6169 
6170   // Don't consider existing declarations that are in a different
6171   // scope and are out-of-semantic-context declarations (if the new
6172   // declaration has linkage).
6173   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6174                        D.getCXXScopeSpec().isNotEmpty() ||
6175                        IsExplicitSpecialization ||
6176                        IsVariableTemplateSpecialization);
6177 
6178   // Check whether the previous declaration is in the same block scope. This
6179   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6180   if (getLangOpts().CPlusPlus &&
6181       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6182     NewVD->setPreviousDeclInSameBlockScope(
6183         Previous.isSingleResult() && !Previous.isShadowed() &&
6184         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6185 
6186   if (!getLangOpts().CPlusPlus) {
6187     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6188   } else {
6189     // If this is an explicit specialization of a static data member, check it.
6190     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6191         CheckMemberSpecialization(NewVD, Previous))
6192       NewVD->setInvalidDecl();
6193 
6194     // Merge the decl with the existing one if appropriate.
6195     if (!Previous.empty()) {
6196       if (Previous.isSingleResult() &&
6197           isa<FieldDecl>(Previous.getFoundDecl()) &&
6198           D.getCXXScopeSpec().isSet()) {
6199         // The user tried to define a non-static data member
6200         // out-of-line (C++ [dcl.meaning]p1).
6201         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6202           << D.getCXXScopeSpec().getRange();
6203         Previous.clear();
6204         NewVD->setInvalidDecl();
6205       }
6206     } else if (D.getCXXScopeSpec().isSet()) {
6207       // No previous declaration in the qualifying scope.
6208       Diag(D.getIdentifierLoc(), diag::err_no_member)
6209         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6210         << D.getCXXScopeSpec().getRange();
6211       NewVD->setInvalidDecl();
6212     }
6213 
6214     if (!IsVariableTemplateSpecialization)
6215       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6216 
6217     if (NewTemplate) {
6218       VarTemplateDecl *PrevVarTemplate =
6219           NewVD->getPreviousDecl()
6220               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6221               : nullptr;
6222 
6223       // Check the template parameter list of this declaration, possibly
6224       // merging in the template parameter list from the previous variable
6225       // template declaration.
6226       if (CheckTemplateParameterList(
6227               TemplateParams,
6228               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6229                               : nullptr,
6230               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6231                DC->isDependentContext())
6232                   ? TPC_ClassTemplateMember
6233                   : TPC_VarTemplate))
6234         NewVD->setInvalidDecl();
6235 
6236       // If we are providing an explicit specialization of a static variable
6237       // template, make a note of that.
6238       if (PrevVarTemplate &&
6239           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6240         PrevVarTemplate->setMemberSpecialization();
6241     }
6242   }
6243 
6244   ProcessPragmaWeak(S, NewVD);
6245 
6246   // If this is the first declaration of an extern C variable, update
6247   // the map of such variables.
6248   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6249       isIncompleteDeclExternC(*this, NewVD))
6250     RegisterLocallyScopedExternCDecl(NewVD, S);
6251 
6252   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6253     Decl *ManglingContextDecl;
6254     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6255             NewVD->getDeclContext(), ManglingContextDecl)) {
6256       Context.setManglingNumber(
6257           NewVD, MCtx->getManglingNumber(
6258                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6259       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6260     }
6261   }
6262 
6263   // Special handling of variable named 'main'.
6264   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6265       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6266       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6267 
6268     // C++ [basic.start.main]p3
6269     // A program that declares a variable main at global scope is ill-formed.
6270     if (getLangOpts().CPlusPlus)
6271       Diag(D.getLocStart(), diag::err_main_global_variable);
6272 
6273     // In C, and external-linkage variable named main results in undefined
6274     // behavior.
6275     else if (NewVD->hasExternalFormalLinkage())
6276       Diag(D.getLocStart(), diag::warn_main_redefined);
6277   }
6278 
6279   if (D.isRedeclaration() && !Previous.empty()) {
6280     checkDLLAttributeRedeclaration(
6281         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6282         IsExplicitSpecialization);
6283   }
6284 
6285   if (NewTemplate) {
6286     if (NewVD->isInvalidDecl())
6287       NewTemplate->setInvalidDecl();
6288     ActOnDocumentableDecl(NewTemplate);
6289     return NewTemplate;
6290   }
6291 
6292   return NewVD;
6293 }
6294 
6295 /// \brief Diagnose variable or built-in function shadowing.  Implements
6296 /// -Wshadow.
6297 ///
6298 /// This method is called whenever a VarDecl is added to a "useful"
6299 /// scope.
6300 ///
6301 /// \param S the scope in which the shadowing name is being declared
6302 /// \param R the lookup of the name
6303 ///
6304 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6305   // Return if warning is ignored.
6306   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6307     return;
6308 
6309   // Don't diagnose declarations at file scope.
6310   if (D->hasGlobalStorage())
6311     return;
6312 
6313   DeclContext *NewDC = D->getDeclContext();
6314 
6315   // Only diagnose if we're shadowing an unambiguous field or variable.
6316   if (R.getResultKind() != LookupResult::Found)
6317     return;
6318 
6319   NamedDecl* ShadowedDecl = R.getFoundDecl();
6320   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6321     return;
6322 
6323   // Fields are not shadowed by variables in C++ static methods.
6324   if (isa<FieldDecl>(ShadowedDecl))
6325     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6326       if (MD->isStatic())
6327         return;
6328 
6329   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6330     if (shadowedVar->isExternC()) {
6331       // For shadowing external vars, make sure that we point to the global
6332       // declaration, not a locally scoped extern declaration.
6333       for (auto I : shadowedVar->redecls())
6334         if (I->isFileVarDecl()) {
6335           ShadowedDecl = I;
6336           break;
6337         }
6338     }
6339 
6340   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6341 
6342   // Only warn about certain kinds of shadowing for class members.
6343   if (NewDC && NewDC->isRecord()) {
6344     // In particular, don't warn about shadowing non-class members.
6345     if (!OldDC->isRecord())
6346       return;
6347 
6348     // TODO: should we warn about static data members shadowing
6349     // static data members from base classes?
6350 
6351     // TODO: don't diagnose for inaccessible shadowed members.
6352     // This is hard to do perfectly because we might friend the
6353     // shadowing context, but that's just a false negative.
6354   }
6355 
6356   // Determine what kind of declaration we're shadowing.
6357   unsigned Kind;
6358   if (isa<RecordDecl>(OldDC)) {
6359     if (isa<FieldDecl>(ShadowedDecl))
6360       Kind = 3; // field
6361     else
6362       Kind = 2; // static data member
6363   } else if (OldDC->isFileContext())
6364     Kind = 1; // global
6365   else
6366     Kind = 0; // local
6367 
6368   DeclarationName Name = R.getLookupName();
6369 
6370   // Emit warning and note.
6371   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6372     return;
6373   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6374   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6375 }
6376 
6377 /// \brief Check -Wshadow without the advantage of a previous lookup.
6378 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6379   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6380     return;
6381 
6382   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6383                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6384   LookupName(R, S);
6385   CheckShadow(S, D, R);
6386 }
6387 
6388 /// Check for conflict between this global or extern "C" declaration and
6389 /// previous global or extern "C" declarations. This is only used in C++.
6390 template<typename T>
6391 static bool checkGlobalOrExternCConflict(
6392     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6393   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6394   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6395 
6396   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6397     // The common case: this global doesn't conflict with any extern "C"
6398     // declaration.
6399     return false;
6400   }
6401 
6402   if (Prev) {
6403     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6404       // Both the old and new declarations have C language linkage. This is a
6405       // redeclaration.
6406       Previous.clear();
6407       Previous.addDecl(Prev);
6408       return true;
6409     }
6410 
6411     // This is a global, non-extern "C" declaration, and there is a previous
6412     // non-global extern "C" declaration. Diagnose if this is a variable
6413     // declaration.
6414     if (!isa<VarDecl>(ND))
6415       return false;
6416   } else {
6417     // The declaration is extern "C". Check for any declaration in the
6418     // translation unit which might conflict.
6419     if (IsGlobal) {
6420       // We have already performed the lookup into the translation unit.
6421       IsGlobal = false;
6422       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6423            I != E; ++I) {
6424         if (isa<VarDecl>(*I)) {
6425           Prev = *I;
6426           break;
6427         }
6428       }
6429     } else {
6430       DeclContext::lookup_result R =
6431           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6432       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6433            I != E; ++I) {
6434         if (isa<VarDecl>(*I)) {
6435           Prev = *I;
6436           break;
6437         }
6438         // FIXME: If we have any other entity with this name in global scope,
6439         // the declaration is ill-formed, but that is a defect: it breaks the
6440         // 'stat' hack, for instance. Only variables can have mangled name
6441         // clashes with extern "C" declarations, so only they deserve a
6442         // diagnostic.
6443       }
6444     }
6445 
6446     if (!Prev)
6447       return false;
6448   }
6449 
6450   // Use the first declaration's location to ensure we point at something which
6451   // is lexically inside an extern "C" linkage-spec.
6452   assert(Prev && "should have found a previous declaration to diagnose");
6453   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6454     Prev = FD->getFirstDecl();
6455   else
6456     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6457 
6458   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6459     << IsGlobal << ND;
6460   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6461     << IsGlobal;
6462   return false;
6463 }
6464 
6465 /// Apply special rules for handling extern "C" declarations. Returns \c true
6466 /// if we have found that this is a redeclaration of some prior entity.
6467 ///
6468 /// Per C++ [dcl.link]p6:
6469 ///   Two declarations [for a function or variable] with C language linkage
6470 ///   with the same name that appear in different scopes refer to the same
6471 ///   [entity]. An entity with C language linkage shall not be declared with
6472 ///   the same name as an entity in global scope.
6473 template<typename T>
6474 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6475                                                   LookupResult &Previous) {
6476   if (!S.getLangOpts().CPlusPlus) {
6477     // In C, when declaring a global variable, look for a corresponding 'extern'
6478     // variable declared in function scope. We don't need this in C++, because
6479     // we find local extern decls in the surrounding file-scope DeclContext.
6480     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6481       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6482         Previous.clear();
6483         Previous.addDecl(Prev);
6484         return true;
6485       }
6486     }
6487     return false;
6488   }
6489 
6490   // A declaration in the translation unit can conflict with an extern "C"
6491   // declaration.
6492   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6493     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6494 
6495   // An extern "C" declaration can conflict with a declaration in the
6496   // translation unit or can be a redeclaration of an extern "C" declaration
6497   // in another scope.
6498   if (isIncompleteDeclExternC(S,ND))
6499     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6500 
6501   // Neither global nor extern "C": nothing to do.
6502   return false;
6503 }
6504 
6505 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6506   // If the decl is already known invalid, don't check it.
6507   if (NewVD->isInvalidDecl())
6508     return;
6509 
6510   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6511   QualType T = TInfo->getType();
6512 
6513   // Defer checking an 'auto' type until its initializer is attached.
6514   if (T->isUndeducedType())
6515     return;
6516 
6517   if (NewVD->hasAttrs())
6518     CheckAlignasUnderalignment(NewVD);
6519 
6520   if (T->isObjCObjectType()) {
6521     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6522       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6523     T = Context.getObjCObjectPointerType(T);
6524     NewVD->setType(T);
6525   }
6526 
6527   // Emit an error if an address space was applied to decl with local storage.
6528   // This includes arrays of objects with address space qualifiers, but not
6529   // automatic variables that point to other address spaces.
6530   // ISO/IEC TR 18037 S5.1.2
6531   if (!getLangOpts().OpenCL
6532       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6533     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6534     NewVD->setInvalidDecl();
6535     return;
6536   }
6537 
6538   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6539   // scope.
6540   if (getLangOpts().OpenCLVersion == 120 &&
6541       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6542       NewVD->isStaticLocal()) {
6543     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6544     NewVD->setInvalidDecl();
6545     return;
6546   }
6547 
6548   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6549   // __constant address space.
6550   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6551   // variables inside a function can also be declared in the global
6552   // address space.
6553   if (getLangOpts().OpenCL) {
6554     if (NewVD->isFileVarDecl()) {
6555       if (!T->isSamplerT() &&
6556           !(T.getAddressSpace() == LangAS::opencl_constant ||
6557             (T.getAddressSpace() == LangAS::opencl_global &&
6558              getLangOpts().OpenCLVersion == 200))) {
6559         if (getLangOpts().OpenCLVersion == 200)
6560           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6561               << "global or constant";
6562         else
6563           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6564               << "constant";
6565         NewVD->setInvalidDecl();
6566         return;
6567       }
6568     } else {
6569       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6570       // variables inside a function can also be declared in the global
6571       // address space.
6572       if (NewVD->isStaticLocal() &&
6573           !(T.getAddressSpace() == LangAS::opencl_constant ||
6574             (T.getAddressSpace() == LangAS::opencl_global &&
6575              getLangOpts().OpenCLVersion == 200))) {
6576         if (getLangOpts().OpenCLVersion == 200)
6577           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6578               << "global or constant";
6579         else
6580           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6581               << "constant";
6582         NewVD->setInvalidDecl();
6583         return;
6584       }
6585       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6586       // in functions.
6587       if (T.getAddressSpace() == LangAS::opencl_constant ||
6588           T.getAddressSpace() == LangAS::opencl_local) {
6589         FunctionDecl *FD = getCurFunctionDecl();
6590         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6591           if (T.getAddressSpace() == LangAS::opencl_constant)
6592             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6593                 << "constant";
6594           else
6595             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6596                 << "local";
6597           NewVD->setInvalidDecl();
6598           return;
6599         }
6600       }
6601     }
6602   }
6603 
6604   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6605       && !NewVD->hasAttr<BlocksAttr>()) {
6606     if (getLangOpts().getGC() != LangOptions::NonGC)
6607       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6608     else {
6609       assert(!getLangOpts().ObjCAutoRefCount);
6610       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6611     }
6612   }
6613 
6614   bool isVM = T->isVariablyModifiedType();
6615   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6616       NewVD->hasAttr<BlocksAttr>())
6617     getCurFunction()->setHasBranchProtectedScope();
6618 
6619   if ((isVM && NewVD->hasLinkage()) ||
6620       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6621     bool SizeIsNegative;
6622     llvm::APSInt Oversized;
6623     TypeSourceInfo *FixedTInfo =
6624       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6625                                                     SizeIsNegative, Oversized);
6626     if (!FixedTInfo && T->isVariableArrayType()) {
6627       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6628       // FIXME: This won't give the correct result for
6629       // int a[10][n];
6630       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6631 
6632       if (NewVD->isFileVarDecl())
6633         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6634         << SizeRange;
6635       else if (NewVD->isStaticLocal())
6636         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6637         << SizeRange;
6638       else
6639         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6640         << SizeRange;
6641       NewVD->setInvalidDecl();
6642       return;
6643     }
6644 
6645     if (!FixedTInfo) {
6646       if (NewVD->isFileVarDecl())
6647         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6648       else
6649         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6650       NewVD->setInvalidDecl();
6651       return;
6652     }
6653 
6654     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6655     NewVD->setType(FixedTInfo->getType());
6656     NewVD->setTypeSourceInfo(FixedTInfo);
6657   }
6658 
6659   if (T->isVoidType()) {
6660     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6661     //                    of objects and functions.
6662     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6663       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6664         << T;
6665       NewVD->setInvalidDecl();
6666       return;
6667     }
6668   }
6669 
6670   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6671     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6672     NewVD->setInvalidDecl();
6673     return;
6674   }
6675 
6676   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6677     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6678     NewVD->setInvalidDecl();
6679     return;
6680   }
6681 
6682   if (NewVD->isConstexpr() && !T->isDependentType() &&
6683       RequireLiteralType(NewVD->getLocation(), T,
6684                          diag::err_constexpr_var_non_literal)) {
6685     NewVD->setInvalidDecl();
6686     return;
6687   }
6688 }
6689 
6690 /// \brief Perform semantic checking on a newly-created variable
6691 /// declaration.
6692 ///
6693 /// This routine performs all of the type-checking required for a
6694 /// variable declaration once it has been built. It is used both to
6695 /// check variables after they have been parsed and their declarators
6696 /// have been translated into a declaration, and to check variables
6697 /// that have been instantiated from a template.
6698 ///
6699 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6700 ///
6701 /// Returns true if the variable declaration is a redeclaration.
6702 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6703   CheckVariableDeclarationType(NewVD);
6704 
6705   // If the decl is already known invalid, don't check it.
6706   if (NewVD->isInvalidDecl())
6707     return false;
6708 
6709   // If we did not find anything by this name, look for a non-visible
6710   // extern "C" declaration with the same name.
6711   if (Previous.empty() &&
6712       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6713     Previous.setShadowed();
6714 
6715   if (!Previous.empty()) {
6716     MergeVarDecl(NewVD, Previous);
6717     return true;
6718   }
6719   return false;
6720 }
6721 
6722 namespace {
6723 struct FindOverriddenMethod {
6724   Sema *S;
6725   CXXMethodDecl *Method;
6726 
6727   /// Member lookup function that determines whether a given C++
6728   /// method overrides a method in a base class, to be used with
6729   /// CXXRecordDecl::lookupInBases().
6730   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6731     RecordDecl *BaseRecord =
6732         Specifier->getType()->getAs<RecordType>()->getDecl();
6733 
6734     DeclarationName Name = Method->getDeclName();
6735 
6736     // FIXME: Do we care about other names here too?
6737     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6738       // We really want to find the base class destructor here.
6739       QualType T = S->Context.getTypeDeclType(BaseRecord);
6740       CanQualType CT = S->Context.getCanonicalType(T);
6741 
6742       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6743     }
6744 
6745     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6746          Path.Decls = Path.Decls.slice(1)) {
6747       NamedDecl *D = Path.Decls.front();
6748       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6749         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6750           return true;
6751       }
6752     }
6753 
6754     return false;
6755   }
6756 };
6757 
6758 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6759 } // end anonymous namespace
6760 
6761 /// \brief Report an error regarding overriding, along with any relevant
6762 /// overriden methods.
6763 ///
6764 /// \param DiagID the primary error to report.
6765 /// \param MD the overriding method.
6766 /// \param OEK which overrides to include as notes.
6767 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6768                             OverrideErrorKind OEK = OEK_All) {
6769   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6770   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6771                                       E = MD->end_overridden_methods();
6772        I != E; ++I) {
6773     // This check (& the OEK parameter) could be replaced by a predicate, but
6774     // without lambdas that would be overkill. This is still nicer than writing
6775     // out the diag loop 3 times.
6776     if ((OEK == OEK_All) ||
6777         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6778         (OEK == OEK_Deleted && (*I)->isDeleted()))
6779       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6780   }
6781 }
6782 
6783 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6784 /// and if so, check that it's a valid override and remember it.
6785 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6786   // Look for methods in base classes that this method might override.
6787   CXXBasePaths Paths;
6788   FindOverriddenMethod FOM;
6789   FOM.Method = MD;
6790   FOM.S = this;
6791   bool hasDeletedOverridenMethods = false;
6792   bool hasNonDeletedOverridenMethods = false;
6793   bool AddedAny = false;
6794   if (DC->lookupInBases(FOM, Paths)) {
6795     for (auto *I : Paths.found_decls()) {
6796       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6797         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6798         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6799             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6800             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6801             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6802           hasDeletedOverridenMethods |= OldMD->isDeleted();
6803           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6804           AddedAny = true;
6805         }
6806       }
6807     }
6808   }
6809 
6810   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6811     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6812   }
6813   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6814     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6815   }
6816 
6817   return AddedAny;
6818 }
6819 
6820 namespace {
6821   // Struct for holding all of the extra arguments needed by
6822   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6823   struct ActOnFDArgs {
6824     Scope *S;
6825     Declarator &D;
6826     MultiTemplateParamsArg TemplateParamLists;
6827     bool AddToScope;
6828   };
6829 }
6830 
6831 namespace {
6832 
6833 // Callback to only accept typo corrections that have a non-zero edit distance.
6834 // Also only accept corrections that have the same parent decl.
6835 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6836  public:
6837   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6838                             CXXRecordDecl *Parent)
6839       : Context(Context), OriginalFD(TypoFD),
6840         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6841 
6842   bool ValidateCandidate(const TypoCorrection &candidate) override {
6843     if (candidate.getEditDistance() == 0)
6844       return false;
6845 
6846     SmallVector<unsigned, 1> MismatchedParams;
6847     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6848                                           CDeclEnd = candidate.end();
6849          CDecl != CDeclEnd; ++CDecl) {
6850       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6851 
6852       if (FD && !FD->hasBody() &&
6853           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6854         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6855           CXXRecordDecl *Parent = MD->getParent();
6856           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6857             return true;
6858         } else if (!ExpectedParent) {
6859           return true;
6860         }
6861       }
6862     }
6863 
6864     return false;
6865   }
6866 
6867  private:
6868   ASTContext &Context;
6869   FunctionDecl *OriginalFD;
6870   CXXRecordDecl *ExpectedParent;
6871 };
6872 
6873 }
6874 
6875 /// \brief Generate diagnostics for an invalid function redeclaration.
6876 ///
6877 /// This routine handles generating the diagnostic messages for an invalid
6878 /// function redeclaration, including finding possible similar declarations
6879 /// or performing typo correction if there are no previous declarations with
6880 /// the same name.
6881 ///
6882 /// Returns a NamedDecl iff typo correction was performed and substituting in
6883 /// the new declaration name does not cause new errors.
6884 static NamedDecl *DiagnoseInvalidRedeclaration(
6885     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6886     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6887   DeclarationName Name = NewFD->getDeclName();
6888   DeclContext *NewDC = NewFD->getDeclContext();
6889   SmallVector<unsigned, 1> MismatchedParams;
6890   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6891   TypoCorrection Correction;
6892   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6893   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6894                                    : diag::err_member_decl_does_not_match;
6895   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6896                     IsLocalFriend ? Sema::LookupLocalFriendName
6897                                   : Sema::LookupOrdinaryName,
6898                     Sema::ForRedeclaration);
6899 
6900   NewFD->setInvalidDecl();
6901   if (IsLocalFriend)
6902     SemaRef.LookupName(Prev, S);
6903   else
6904     SemaRef.LookupQualifiedName(Prev, NewDC);
6905   assert(!Prev.isAmbiguous() &&
6906          "Cannot have an ambiguity in previous-declaration lookup");
6907   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6908   if (!Prev.empty()) {
6909     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6910          Func != FuncEnd; ++Func) {
6911       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6912       if (FD &&
6913           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6914         // Add 1 to the index so that 0 can mean the mismatch didn't
6915         // involve a parameter
6916         unsigned ParamNum =
6917             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6918         NearMatches.push_back(std::make_pair(FD, ParamNum));
6919       }
6920     }
6921   // If the qualified name lookup yielded nothing, try typo correction
6922   } else if ((Correction = SemaRef.CorrectTypo(
6923                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6924                   &ExtraArgs.D.getCXXScopeSpec(),
6925                   llvm::make_unique<DifferentNameValidatorCCC>(
6926                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6927                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6928     // Set up everything for the call to ActOnFunctionDeclarator
6929     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6930                               ExtraArgs.D.getIdentifierLoc());
6931     Previous.clear();
6932     Previous.setLookupName(Correction.getCorrection());
6933     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6934                                     CDeclEnd = Correction.end();
6935          CDecl != CDeclEnd; ++CDecl) {
6936       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6937       if (FD && !FD->hasBody() &&
6938           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6939         Previous.addDecl(FD);
6940       }
6941     }
6942     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6943 
6944     NamedDecl *Result;
6945     // Retry building the function declaration with the new previous
6946     // declarations, and with errors suppressed.
6947     {
6948       // Trap errors.
6949       Sema::SFINAETrap Trap(SemaRef);
6950 
6951       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6952       // pieces need to verify the typo-corrected C++ declaration and hopefully
6953       // eliminate the need for the parameter pack ExtraArgs.
6954       Result = SemaRef.ActOnFunctionDeclarator(
6955           ExtraArgs.S, ExtraArgs.D,
6956           Correction.getCorrectionDecl()->getDeclContext(),
6957           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6958           ExtraArgs.AddToScope);
6959 
6960       if (Trap.hasErrorOccurred())
6961         Result = nullptr;
6962     }
6963 
6964     if (Result) {
6965       // Determine which correction we picked.
6966       Decl *Canonical = Result->getCanonicalDecl();
6967       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6968            I != E; ++I)
6969         if ((*I)->getCanonicalDecl() == Canonical)
6970           Correction.setCorrectionDecl(*I);
6971 
6972       SemaRef.diagnoseTypo(
6973           Correction,
6974           SemaRef.PDiag(IsLocalFriend
6975                           ? diag::err_no_matching_local_friend_suggest
6976                           : diag::err_member_decl_does_not_match_suggest)
6977             << Name << NewDC << IsDefinition);
6978       return Result;
6979     }
6980 
6981     // Pretend the typo correction never occurred
6982     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6983                               ExtraArgs.D.getIdentifierLoc());
6984     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6985     Previous.clear();
6986     Previous.setLookupName(Name);
6987   }
6988 
6989   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6990       << Name << NewDC << IsDefinition << NewFD->getLocation();
6991 
6992   bool NewFDisConst = false;
6993   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6994     NewFDisConst = NewMD->isConst();
6995 
6996   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6997        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6998        NearMatch != NearMatchEnd; ++NearMatch) {
6999     FunctionDecl *FD = NearMatch->first;
7000     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7001     bool FDisConst = MD && MD->isConst();
7002     bool IsMember = MD || !IsLocalFriend;
7003 
7004     // FIXME: These notes are poorly worded for the local friend case.
7005     if (unsigned Idx = NearMatch->second) {
7006       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7007       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7008       if (Loc.isInvalid()) Loc = FD->getLocation();
7009       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7010                                  : diag::note_local_decl_close_param_match)
7011         << Idx << FDParam->getType()
7012         << NewFD->getParamDecl(Idx - 1)->getType();
7013     } else if (FDisConst != NewFDisConst) {
7014       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7015           << NewFDisConst << FD->getSourceRange().getEnd();
7016     } else
7017       SemaRef.Diag(FD->getLocation(),
7018                    IsMember ? diag::note_member_def_close_match
7019                             : diag::note_local_decl_close_match);
7020   }
7021   return nullptr;
7022 }
7023 
7024 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7025   switch (D.getDeclSpec().getStorageClassSpec()) {
7026   default: llvm_unreachable("Unknown storage class!");
7027   case DeclSpec::SCS_auto:
7028   case DeclSpec::SCS_register:
7029   case DeclSpec::SCS_mutable:
7030     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7031                  diag::err_typecheck_sclass_func);
7032     D.setInvalidType();
7033     break;
7034   case DeclSpec::SCS_unspecified: break;
7035   case DeclSpec::SCS_extern:
7036     if (D.getDeclSpec().isExternInLinkageSpec())
7037       return SC_None;
7038     return SC_Extern;
7039   case DeclSpec::SCS_static: {
7040     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7041       // C99 6.7.1p5:
7042       //   The declaration of an identifier for a function that has
7043       //   block scope shall have no explicit storage-class specifier
7044       //   other than extern
7045       // See also (C++ [dcl.stc]p4).
7046       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7047                    diag::err_static_block_func);
7048       break;
7049     } else
7050       return SC_Static;
7051   }
7052   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7053   }
7054 
7055   // No explicit storage class has already been returned
7056   return SC_None;
7057 }
7058 
7059 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7060                                            DeclContext *DC, QualType &R,
7061                                            TypeSourceInfo *TInfo,
7062                                            StorageClass SC,
7063                                            bool &IsVirtualOkay) {
7064   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7065   DeclarationName Name = NameInfo.getName();
7066 
7067   FunctionDecl *NewFD = nullptr;
7068   bool isInline = D.getDeclSpec().isInlineSpecified();
7069 
7070   if (!SemaRef.getLangOpts().CPlusPlus) {
7071     // Determine whether the function was written with a
7072     // prototype. This true when:
7073     //   - there is a prototype in the declarator, or
7074     //   - the type R of the function is some kind of typedef or other reference
7075     //     to a type name (which eventually refers to a function type).
7076     bool HasPrototype =
7077       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7078       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7079 
7080     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7081                                  D.getLocStart(), NameInfo, R,
7082                                  TInfo, SC, isInline,
7083                                  HasPrototype, false);
7084     if (D.isInvalidType())
7085       NewFD->setInvalidDecl();
7086 
7087     return NewFD;
7088   }
7089 
7090   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7091   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7092 
7093   // Check that the return type is not an abstract class type.
7094   // For record types, this is done by the AbstractClassUsageDiagnoser once
7095   // the class has been completely parsed.
7096   if (!DC->isRecord() &&
7097       SemaRef.RequireNonAbstractType(
7098           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7099           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7100     D.setInvalidType();
7101 
7102   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7103     // This is a C++ constructor declaration.
7104     assert(DC->isRecord() &&
7105            "Constructors can only be declared in a member context");
7106 
7107     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7108     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7109                                       D.getLocStart(), NameInfo,
7110                                       R, TInfo, isExplicit, isInline,
7111                                       /*isImplicitlyDeclared=*/false,
7112                                       isConstexpr);
7113 
7114   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7115     // This is a C++ destructor declaration.
7116     if (DC->isRecord()) {
7117       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7118       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7119       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7120                                         SemaRef.Context, Record,
7121                                         D.getLocStart(),
7122                                         NameInfo, R, TInfo, isInline,
7123                                         /*isImplicitlyDeclared=*/false);
7124 
7125       // If the class is complete, then we now create the implicit exception
7126       // specification. If the class is incomplete or dependent, we can't do
7127       // it yet.
7128       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7129           Record->getDefinition() && !Record->isBeingDefined() &&
7130           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7131         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7132       }
7133 
7134       IsVirtualOkay = true;
7135       return NewDD;
7136 
7137     } else {
7138       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7139       D.setInvalidType();
7140 
7141       // Create a FunctionDecl to satisfy the function definition parsing
7142       // code path.
7143       return FunctionDecl::Create(SemaRef.Context, DC,
7144                                   D.getLocStart(),
7145                                   D.getIdentifierLoc(), Name, R, TInfo,
7146                                   SC, isInline,
7147                                   /*hasPrototype=*/true, isConstexpr);
7148     }
7149 
7150   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7151     if (!DC->isRecord()) {
7152       SemaRef.Diag(D.getIdentifierLoc(),
7153            diag::err_conv_function_not_member);
7154       return nullptr;
7155     }
7156 
7157     SemaRef.CheckConversionDeclarator(D, R, SC);
7158     IsVirtualOkay = true;
7159     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7160                                      D.getLocStart(), NameInfo,
7161                                      R, TInfo, isInline, isExplicit,
7162                                      isConstexpr, SourceLocation());
7163 
7164   } else if (DC->isRecord()) {
7165     // If the name of the function is the same as the name of the record,
7166     // then this must be an invalid constructor that has a return type.
7167     // (The parser checks for a return type and makes the declarator a
7168     // constructor if it has no return type).
7169     if (Name.getAsIdentifierInfo() &&
7170         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7171       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7172         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7173         << SourceRange(D.getIdentifierLoc());
7174       return nullptr;
7175     }
7176 
7177     // This is a C++ method declaration.
7178     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7179                                                cast<CXXRecordDecl>(DC),
7180                                                D.getLocStart(), NameInfo, R,
7181                                                TInfo, SC, isInline,
7182                                                isConstexpr, SourceLocation());
7183     IsVirtualOkay = !Ret->isStatic();
7184     return Ret;
7185   } else {
7186     bool isFriend =
7187         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7188     if (!isFriend && SemaRef.CurContext->isRecord())
7189       return nullptr;
7190 
7191     // Determine whether the function was written with a
7192     // prototype. This true when:
7193     //   - we're in C++ (where every function has a prototype),
7194     return FunctionDecl::Create(SemaRef.Context, DC,
7195                                 D.getLocStart(),
7196                                 NameInfo, R, TInfo, SC, isInline,
7197                                 true/*HasPrototype*/, isConstexpr);
7198   }
7199 }
7200 
7201 enum OpenCLParamType {
7202   ValidKernelParam,
7203   PtrPtrKernelParam,
7204   PtrKernelParam,
7205   PrivatePtrKernelParam,
7206   InvalidKernelParam,
7207   RecordKernelParam
7208 };
7209 
7210 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7211   if (PT->isPointerType()) {
7212     QualType PointeeType = PT->getPointeeType();
7213     if (PointeeType->isPointerType())
7214       return PtrPtrKernelParam;
7215     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7216                                               : PtrKernelParam;
7217   }
7218 
7219   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7220   // be used as builtin types.
7221 
7222   if (PT->isImageType())
7223     return PtrKernelParam;
7224 
7225   if (PT->isBooleanType())
7226     return InvalidKernelParam;
7227 
7228   if (PT->isEventT())
7229     return InvalidKernelParam;
7230 
7231   if (PT->isHalfType())
7232     return InvalidKernelParam;
7233 
7234   if (PT->isRecordType())
7235     return RecordKernelParam;
7236 
7237   return ValidKernelParam;
7238 }
7239 
7240 static void checkIsValidOpenCLKernelParameter(
7241   Sema &S,
7242   Declarator &D,
7243   ParmVarDecl *Param,
7244   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7245   QualType PT = Param->getType();
7246 
7247   // Cache the valid types we encounter to avoid rechecking structs that are
7248   // used again
7249   if (ValidTypes.count(PT.getTypePtr()))
7250     return;
7251 
7252   switch (getOpenCLKernelParameterType(PT)) {
7253   case PtrPtrKernelParam:
7254     // OpenCL v1.2 s6.9.a:
7255     // A kernel function argument cannot be declared as a
7256     // pointer to a pointer type.
7257     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7258     D.setInvalidType();
7259     return;
7260 
7261   case PrivatePtrKernelParam:
7262     // OpenCL v1.2 s6.9.a:
7263     // A kernel function argument cannot be declared as a
7264     // pointer to the private address space.
7265     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7266     D.setInvalidType();
7267     return;
7268 
7269     // OpenCL v1.2 s6.9.k:
7270     // Arguments to kernel functions in a program cannot be declared with the
7271     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7272     // uintptr_t or a struct and/or union that contain fields declared to be
7273     // one of these built-in scalar types.
7274 
7275   case InvalidKernelParam:
7276     // OpenCL v1.2 s6.8 n:
7277     // A kernel function argument cannot be declared
7278     // of event_t type.
7279     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7280     D.setInvalidType();
7281     return;
7282 
7283   case PtrKernelParam:
7284   case ValidKernelParam:
7285     ValidTypes.insert(PT.getTypePtr());
7286     return;
7287 
7288   case RecordKernelParam:
7289     break;
7290   }
7291 
7292   // Track nested structs we will inspect
7293   SmallVector<const Decl *, 4> VisitStack;
7294 
7295   // Track where we are in the nested structs. Items will migrate from
7296   // VisitStack to HistoryStack as we do the DFS for bad field.
7297   SmallVector<const FieldDecl *, 4> HistoryStack;
7298   HistoryStack.push_back(nullptr);
7299 
7300   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7301   VisitStack.push_back(PD);
7302 
7303   assert(VisitStack.back() && "First decl null?");
7304 
7305   do {
7306     const Decl *Next = VisitStack.pop_back_val();
7307     if (!Next) {
7308       assert(!HistoryStack.empty());
7309       // Found a marker, we have gone up a level
7310       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7311         ValidTypes.insert(Hist->getType().getTypePtr());
7312 
7313       continue;
7314     }
7315 
7316     // Adds everything except the original parameter declaration (which is not a
7317     // field itself) to the history stack.
7318     const RecordDecl *RD;
7319     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7320       HistoryStack.push_back(Field);
7321       RD = Field->getType()->castAs<RecordType>()->getDecl();
7322     } else {
7323       RD = cast<RecordDecl>(Next);
7324     }
7325 
7326     // Add a null marker so we know when we've gone back up a level
7327     VisitStack.push_back(nullptr);
7328 
7329     for (const auto *FD : RD->fields()) {
7330       QualType QT = FD->getType();
7331 
7332       if (ValidTypes.count(QT.getTypePtr()))
7333         continue;
7334 
7335       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7336       if (ParamType == ValidKernelParam)
7337         continue;
7338 
7339       if (ParamType == RecordKernelParam) {
7340         VisitStack.push_back(FD);
7341         continue;
7342       }
7343 
7344       // OpenCL v1.2 s6.9.p:
7345       // Arguments to kernel functions that are declared to be a struct or union
7346       // do not allow OpenCL objects to be passed as elements of the struct or
7347       // union.
7348       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7349           ParamType == PrivatePtrKernelParam) {
7350         S.Diag(Param->getLocation(),
7351                diag::err_record_with_pointers_kernel_param)
7352           << PT->isUnionType()
7353           << PT;
7354       } else {
7355         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7356       }
7357 
7358       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7359         << PD->getDeclName();
7360 
7361       // We have an error, now let's go back up through history and show where
7362       // the offending field came from
7363       for (ArrayRef<const FieldDecl *>::const_iterator
7364                I = HistoryStack.begin() + 1,
7365                E = HistoryStack.end();
7366            I != E; ++I) {
7367         const FieldDecl *OuterField = *I;
7368         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7369           << OuterField->getType();
7370       }
7371 
7372       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7373         << QT->isPointerType()
7374         << QT;
7375       D.setInvalidType();
7376       return;
7377     }
7378   } while (!VisitStack.empty());
7379 }
7380 
7381 NamedDecl*
7382 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7383                               TypeSourceInfo *TInfo, LookupResult &Previous,
7384                               MultiTemplateParamsArg TemplateParamLists,
7385                               bool &AddToScope) {
7386   QualType R = TInfo->getType();
7387 
7388   assert(R.getTypePtr()->isFunctionType());
7389 
7390   // TODO: consider using NameInfo for diagnostic.
7391   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7392   DeclarationName Name = NameInfo.getName();
7393   StorageClass SC = getFunctionStorageClass(*this, D);
7394 
7395   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7396     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7397          diag::err_invalid_thread)
7398       << DeclSpec::getSpecifierName(TSCS);
7399 
7400   if (D.isFirstDeclarationOfMember())
7401     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7402                            D.getIdentifierLoc());
7403 
7404   bool isFriend = false;
7405   FunctionTemplateDecl *FunctionTemplate = nullptr;
7406   bool isExplicitSpecialization = false;
7407   bool isFunctionTemplateSpecialization = false;
7408 
7409   bool isDependentClassScopeExplicitSpecialization = false;
7410   bool HasExplicitTemplateArgs = false;
7411   TemplateArgumentListInfo TemplateArgs;
7412 
7413   bool isVirtualOkay = false;
7414 
7415   DeclContext *OriginalDC = DC;
7416   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7417 
7418   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7419                                               isVirtualOkay);
7420   if (!NewFD) return nullptr;
7421 
7422   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7423     NewFD->setTopLevelDeclInObjCContainer();
7424 
7425   // Set the lexical context. If this is a function-scope declaration, or has a
7426   // C++ scope specifier, or is the object of a friend declaration, the lexical
7427   // context will be different from the semantic context.
7428   NewFD->setLexicalDeclContext(CurContext);
7429 
7430   if (IsLocalExternDecl)
7431     NewFD->setLocalExternDecl();
7432 
7433   if (getLangOpts().CPlusPlus) {
7434     bool isInline = D.getDeclSpec().isInlineSpecified();
7435     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7436     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7437     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7438     bool isConcept = D.getDeclSpec().isConceptSpecified();
7439     isFriend = D.getDeclSpec().isFriendSpecified();
7440     if (isFriend && !isInline && D.isFunctionDefinition()) {
7441       // C++ [class.friend]p5
7442       //   A function can be defined in a friend declaration of a
7443       //   class . . . . Such a function is implicitly inline.
7444       NewFD->setImplicitlyInline();
7445     }
7446 
7447     // If this is a method defined in an __interface, and is not a constructor
7448     // or an overloaded operator, then set the pure flag (isVirtual will already
7449     // return true).
7450     if (const CXXRecordDecl *Parent =
7451           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7452       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7453         NewFD->setPure(true);
7454 
7455       // C++ [class.union]p2
7456       //   A union can have member functions, but not virtual functions.
7457       if (isVirtual && Parent->isUnion())
7458         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7459     }
7460 
7461     SetNestedNameSpecifier(NewFD, D);
7462     isExplicitSpecialization = false;
7463     isFunctionTemplateSpecialization = false;
7464     if (D.isInvalidType())
7465       NewFD->setInvalidDecl();
7466 
7467     // Match up the template parameter lists with the scope specifier, then
7468     // determine whether we have a template or a template specialization.
7469     bool Invalid = false;
7470     if (TemplateParameterList *TemplateParams =
7471             MatchTemplateParametersToScopeSpecifier(
7472                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7473                 D.getCXXScopeSpec(),
7474                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7475                     ? D.getName().TemplateId
7476                     : nullptr,
7477                 TemplateParamLists, isFriend, isExplicitSpecialization,
7478                 Invalid)) {
7479       if (TemplateParams->size() > 0) {
7480         // This is a function template
7481 
7482         // Check that we can declare a template here.
7483         if (CheckTemplateDeclScope(S, TemplateParams))
7484           NewFD->setInvalidDecl();
7485 
7486         // A destructor cannot be a template.
7487         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7488           Diag(NewFD->getLocation(), diag::err_destructor_template);
7489           NewFD->setInvalidDecl();
7490         }
7491 
7492         // If we're adding a template to a dependent context, we may need to
7493         // rebuilding some of the types used within the template parameter list,
7494         // now that we know what the current instantiation is.
7495         if (DC->isDependentContext()) {
7496           ContextRAII SavedContext(*this, DC);
7497           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7498             Invalid = true;
7499         }
7500 
7501 
7502         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7503                                                         NewFD->getLocation(),
7504                                                         Name, TemplateParams,
7505                                                         NewFD);
7506         FunctionTemplate->setLexicalDeclContext(CurContext);
7507         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7508 
7509         // For source fidelity, store the other template param lists.
7510         if (TemplateParamLists.size() > 1) {
7511           NewFD->setTemplateParameterListsInfo(Context,
7512                                                TemplateParamLists.drop_back(1));
7513         }
7514       } else {
7515         // This is a function template specialization.
7516         isFunctionTemplateSpecialization = true;
7517         // For source fidelity, store all the template param lists.
7518         if (TemplateParamLists.size() > 0)
7519           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7520 
7521         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7522         if (isFriend) {
7523           // We want to remove the "template<>", found here.
7524           SourceRange RemoveRange = TemplateParams->getSourceRange();
7525 
7526           // If we remove the template<> and the name is not a
7527           // template-id, we're actually silently creating a problem:
7528           // the friend declaration will refer to an untemplated decl,
7529           // and clearly the user wants a template specialization.  So
7530           // we need to insert '<>' after the name.
7531           SourceLocation InsertLoc;
7532           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7533             InsertLoc = D.getName().getSourceRange().getEnd();
7534             InsertLoc = getLocForEndOfToken(InsertLoc);
7535           }
7536 
7537           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7538             << Name << RemoveRange
7539             << FixItHint::CreateRemoval(RemoveRange)
7540             << FixItHint::CreateInsertion(InsertLoc, "<>");
7541         }
7542       }
7543     }
7544     else {
7545       // All template param lists were matched against the scope specifier:
7546       // this is NOT (an explicit specialization of) a template.
7547       if (TemplateParamLists.size() > 0)
7548         // For source fidelity, store all the template param lists.
7549         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7550     }
7551 
7552     if (Invalid) {
7553       NewFD->setInvalidDecl();
7554       if (FunctionTemplate)
7555         FunctionTemplate->setInvalidDecl();
7556     }
7557 
7558     // C++ [dcl.fct.spec]p5:
7559     //   The virtual specifier shall only be used in declarations of
7560     //   nonstatic class member functions that appear within a
7561     //   member-specification of a class declaration; see 10.3.
7562     //
7563     if (isVirtual && !NewFD->isInvalidDecl()) {
7564       if (!isVirtualOkay) {
7565         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7566              diag::err_virtual_non_function);
7567       } else if (!CurContext->isRecord()) {
7568         // 'virtual' was specified outside of the class.
7569         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7570              diag::err_virtual_out_of_class)
7571           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7572       } else if (NewFD->getDescribedFunctionTemplate()) {
7573         // C++ [temp.mem]p3:
7574         //  A member function template shall not be virtual.
7575         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7576              diag::err_virtual_member_function_template)
7577           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7578       } else {
7579         // Okay: Add virtual to the method.
7580         NewFD->setVirtualAsWritten(true);
7581       }
7582 
7583       if (getLangOpts().CPlusPlus14 &&
7584           NewFD->getReturnType()->isUndeducedType())
7585         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7586     }
7587 
7588     if (getLangOpts().CPlusPlus14 &&
7589         (NewFD->isDependentContext() ||
7590          (isFriend && CurContext->isDependentContext())) &&
7591         NewFD->getReturnType()->isUndeducedType()) {
7592       // If the function template is referenced directly (for instance, as a
7593       // member of the current instantiation), pretend it has a dependent type.
7594       // This is not really justified by the standard, but is the only sane
7595       // thing to do.
7596       // FIXME: For a friend function, we have not marked the function as being
7597       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7598       const FunctionProtoType *FPT =
7599           NewFD->getType()->castAs<FunctionProtoType>();
7600       QualType Result =
7601           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7602       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7603                                              FPT->getExtProtoInfo()));
7604     }
7605 
7606     // C++ [dcl.fct.spec]p3:
7607     //  The inline specifier shall not appear on a block scope function
7608     //  declaration.
7609     if (isInline && !NewFD->isInvalidDecl()) {
7610       if (CurContext->isFunctionOrMethod()) {
7611         // 'inline' is not allowed on block scope function declaration.
7612         Diag(D.getDeclSpec().getInlineSpecLoc(),
7613              diag::err_inline_declaration_block_scope) << Name
7614           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7615       }
7616     }
7617 
7618     // C++ [dcl.fct.spec]p6:
7619     //  The explicit specifier shall be used only in the declaration of a
7620     //  constructor or conversion function within its class definition;
7621     //  see 12.3.1 and 12.3.2.
7622     if (isExplicit && !NewFD->isInvalidDecl()) {
7623       if (!CurContext->isRecord()) {
7624         // 'explicit' was specified outside of the class.
7625         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7626              diag::err_explicit_out_of_class)
7627           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7628       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7629                  !isa<CXXConversionDecl>(NewFD)) {
7630         // 'explicit' was specified on a function that wasn't a constructor
7631         // or conversion function.
7632         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7633              diag::err_explicit_non_ctor_or_conv_function)
7634           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7635       }
7636     }
7637 
7638     if (isConstexpr) {
7639       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7640       // are implicitly inline.
7641       NewFD->setImplicitlyInline();
7642 
7643       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7644       // be either constructors or to return a literal type. Therefore,
7645       // destructors cannot be declared constexpr.
7646       if (isa<CXXDestructorDecl>(NewFD))
7647         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7648     }
7649 
7650     if (isConcept) {
7651       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7652       // applied only to the definition of a function template [...]
7653       if (!D.isFunctionDefinition()) {
7654         Diag(D.getDeclSpec().getConceptSpecLoc(),
7655              diag::err_function_concept_not_defined);
7656         NewFD->setInvalidDecl();
7657       }
7658 
7659       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7660       // have no exception-specification and is treated as if it were specified
7661       // with noexcept(true) (15.4). [...]
7662       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7663         if (FPT->hasExceptionSpec()) {
7664           SourceRange Range;
7665           if (D.isFunctionDeclarator())
7666             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7667           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7668               << FixItHint::CreateRemoval(Range);
7669           NewFD->setInvalidDecl();
7670         } else {
7671           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7672         }
7673 
7674         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7675         // following restrictions:
7676         // - The declaration's parameter list shall be equivalent to an empty
7677         //   parameter list.
7678         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7679           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7680       }
7681 
7682       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7683       // implicity defined to be a constexpr declaration (implicitly inline)
7684       NewFD->setImplicitlyInline();
7685 
7686       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7687       // be declared with the thread_local, inline, friend, or constexpr
7688       // specifiers, [...]
7689       if (isInline) {
7690         Diag(D.getDeclSpec().getInlineSpecLoc(),
7691              diag::err_concept_decl_invalid_specifiers)
7692             << 1 << 1;
7693         NewFD->setInvalidDecl(true);
7694       }
7695 
7696       if (isFriend) {
7697         Diag(D.getDeclSpec().getFriendSpecLoc(),
7698              diag::err_concept_decl_invalid_specifiers)
7699             << 1 << 2;
7700         NewFD->setInvalidDecl(true);
7701       }
7702 
7703       if (isConstexpr) {
7704         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7705              diag::err_concept_decl_invalid_specifiers)
7706             << 1 << 3;
7707         NewFD->setInvalidDecl(true);
7708       }
7709     }
7710 
7711     // If __module_private__ was specified, mark the function accordingly.
7712     if (D.getDeclSpec().isModulePrivateSpecified()) {
7713       if (isFunctionTemplateSpecialization) {
7714         SourceLocation ModulePrivateLoc
7715           = D.getDeclSpec().getModulePrivateSpecLoc();
7716         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7717           << 0
7718           << FixItHint::CreateRemoval(ModulePrivateLoc);
7719       } else {
7720         NewFD->setModulePrivate();
7721         if (FunctionTemplate)
7722           FunctionTemplate->setModulePrivate();
7723       }
7724     }
7725 
7726     if (isFriend) {
7727       if (FunctionTemplate) {
7728         FunctionTemplate->setObjectOfFriendDecl();
7729         FunctionTemplate->setAccess(AS_public);
7730       }
7731       NewFD->setObjectOfFriendDecl();
7732       NewFD->setAccess(AS_public);
7733     }
7734 
7735     // If a function is defined as defaulted or deleted, mark it as such now.
7736     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7737     // definition kind to FDK_Definition.
7738     switch (D.getFunctionDefinitionKind()) {
7739       case FDK_Declaration:
7740       case FDK_Definition:
7741         break;
7742 
7743       case FDK_Defaulted:
7744         NewFD->setDefaulted();
7745         break;
7746 
7747       case FDK_Deleted:
7748         NewFD->setDeletedAsWritten();
7749         break;
7750     }
7751 
7752     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7753         D.isFunctionDefinition()) {
7754       // C++ [class.mfct]p2:
7755       //   A member function may be defined (8.4) in its class definition, in
7756       //   which case it is an inline member function (7.1.2)
7757       NewFD->setImplicitlyInline();
7758     }
7759 
7760     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7761         !CurContext->isRecord()) {
7762       // C++ [class.static]p1:
7763       //   A data or function member of a class may be declared static
7764       //   in a class definition, in which case it is a static member of
7765       //   the class.
7766 
7767       // Complain about the 'static' specifier if it's on an out-of-line
7768       // member function definition.
7769       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7770            diag::err_static_out_of_line)
7771         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7772     }
7773 
7774     // C++11 [except.spec]p15:
7775     //   A deallocation function with no exception-specification is treated
7776     //   as if it were specified with noexcept(true).
7777     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7778     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7779          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7780         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7781       NewFD->setType(Context.getFunctionType(
7782           FPT->getReturnType(), FPT->getParamTypes(),
7783           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7784   }
7785 
7786   // Filter out previous declarations that don't match the scope.
7787   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7788                        D.getCXXScopeSpec().isNotEmpty() ||
7789                        isExplicitSpecialization ||
7790                        isFunctionTemplateSpecialization);
7791 
7792   // Handle GNU asm-label extension (encoded as an attribute).
7793   if (Expr *E = (Expr*) D.getAsmLabel()) {
7794     // The parser guarantees this is a string.
7795     StringLiteral *SE = cast<StringLiteral>(E);
7796     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7797                                                 SE->getString(), 0));
7798   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7799     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7800       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7801     if (I != ExtnameUndeclaredIdentifiers.end()) {
7802       if (isDeclExternC(NewFD)) {
7803         NewFD->addAttr(I->second);
7804         ExtnameUndeclaredIdentifiers.erase(I);
7805       } else
7806         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7807             << /*Variable*/0 << NewFD;
7808     }
7809   }
7810 
7811   // Copy the parameter declarations from the declarator D to the function
7812   // declaration NewFD, if they are available.  First scavenge them into Params.
7813   SmallVector<ParmVarDecl*, 16> Params;
7814   if (D.isFunctionDeclarator()) {
7815     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7816 
7817     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7818     // function that takes no arguments, not a function that takes a
7819     // single void argument.
7820     // We let through "const void" here because Sema::GetTypeForDeclarator
7821     // already checks for that case.
7822     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7823       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7824         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7825         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7826         Param->setDeclContext(NewFD);
7827         Params.push_back(Param);
7828 
7829         if (Param->isInvalidDecl())
7830           NewFD->setInvalidDecl();
7831       }
7832     }
7833 
7834   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7835     // When we're declaring a function with a typedef, typeof, etc as in the
7836     // following example, we'll need to synthesize (unnamed)
7837     // parameters for use in the declaration.
7838     //
7839     // @code
7840     // typedef void fn(int);
7841     // fn f;
7842     // @endcode
7843 
7844     // Synthesize a parameter for each argument type.
7845     for (const auto &AI : FT->param_types()) {
7846       ParmVarDecl *Param =
7847           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7848       Param->setScopeInfo(0, Params.size());
7849       Params.push_back(Param);
7850     }
7851   } else {
7852     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7853            "Should not need args for typedef of non-prototype fn");
7854   }
7855 
7856   // Finally, we know we have the right number of parameters, install them.
7857   NewFD->setParams(Params);
7858 
7859   // Find all anonymous symbols defined during the declaration of this function
7860   // and add to NewFD. This lets us track decls such 'enum Y' in:
7861   //
7862   //   void f(enum Y {AA} x) {}
7863   //
7864   // which would otherwise incorrectly end up in the translation unit scope.
7865   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7866   DeclsInPrototypeScope.clear();
7867 
7868   if (D.getDeclSpec().isNoreturnSpecified())
7869     NewFD->addAttr(
7870         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7871                                        Context, 0));
7872 
7873   // Functions returning a variably modified type violate C99 6.7.5.2p2
7874   // because all functions have linkage.
7875   if (!NewFD->isInvalidDecl() &&
7876       NewFD->getReturnType()->isVariablyModifiedType()) {
7877     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7878     NewFD->setInvalidDecl();
7879   }
7880 
7881   // Apply an implicit SectionAttr if #pragma code_seg is active.
7882   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7883       !NewFD->hasAttr<SectionAttr>()) {
7884     NewFD->addAttr(
7885         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7886                                     CodeSegStack.CurrentValue->getString(),
7887                                     CodeSegStack.CurrentPragmaLocation));
7888     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7889                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7890                          ASTContext::PSF_Read,
7891                      NewFD))
7892       NewFD->dropAttr<SectionAttr>();
7893   }
7894 
7895   // Handle attributes.
7896   ProcessDeclAttributes(S, NewFD, D);
7897 
7898   if (getLangOpts().OpenCL) {
7899     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7900     // type declaration will generate a compilation error.
7901     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7902     if (AddressSpace == LangAS::opencl_local ||
7903         AddressSpace == LangAS::opencl_global ||
7904         AddressSpace == LangAS::opencl_constant) {
7905       Diag(NewFD->getLocation(),
7906            diag::err_opencl_return_value_with_address_space);
7907       NewFD->setInvalidDecl();
7908     }
7909   }
7910 
7911   if (!getLangOpts().CPlusPlus) {
7912     // Perform semantic checking on the function declaration.
7913     bool isExplicitSpecialization=false;
7914     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7915       CheckMain(NewFD, D.getDeclSpec());
7916 
7917     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7918       CheckMSVCRTEntryPoint(NewFD);
7919 
7920     if (!NewFD->isInvalidDecl())
7921       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7922                                                   isExplicitSpecialization));
7923     else if (!Previous.empty())
7924       // Recover gracefully from an invalid redeclaration.
7925       D.setRedeclaration(true);
7926     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7927             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7928            "previous declaration set still overloaded");
7929 
7930     // Diagnose no-prototype function declarations with calling conventions that
7931     // don't support variadic calls. Only do this in C and do it after merging
7932     // possibly prototyped redeclarations.
7933     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7934     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7935       CallingConv CC = FT->getExtInfo().getCC();
7936       if (!supportsVariadicCall(CC)) {
7937         // Windows system headers sometimes accidentally use stdcall without
7938         // (void) parameters, so we relax this to a warning.
7939         int DiagID =
7940             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7941         Diag(NewFD->getLocation(), DiagID)
7942             << FunctionType::getNameForCallConv(CC);
7943       }
7944     }
7945   } else {
7946     // C++11 [replacement.functions]p3:
7947     //  The program's definitions shall not be specified as inline.
7948     //
7949     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7950     //
7951     // Suppress the diagnostic if the function is __attribute__((used)), since
7952     // that forces an external definition to be emitted.
7953     if (D.getDeclSpec().isInlineSpecified() &&
7954         NewFD->isReplaceableGlobalAllocationFunction() &&
7955         !NewFD->hasAttr<UsedAttr>())
7956       Diag(D.getDeclSpec().getInlineSpecLoc(),
7957            diag::ext_operator_new_delete_declared_inline)
7958         << NewFD->getDeclName();
7959 
7960     // If the declarator is a template-id, translate the parser's template
7961     // argument list into our AST format.
7962     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7963       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7964       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7965       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7966       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7967                                          TemplateId->NumArgs);
7968       translateTemplateArguments(TemplateArgsPtr,
7969                                  TemplateArgs);
7970 
7971       HasExplicitTemplateArgs = true;
7972 
7973       if (NewFD->isInvalidDecl()) {
7974         HasExplicitTemplateArgs = false;
7975       } else if (FunctionTemplate) {
7976         // Function template with explicit template arguments.
7977         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7978           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7979 
7980         HasExplicitTemplateArgs = false;
7981       } else {
7982         assert((isFunctionTemplateSpecialization ||
7983                 D.getDeclSpec().isFriendSpecified()) &&
7984                "should have a 'template<>' for this decl");
7985         // "friend void foo<>(int);" is an implicit specialization decl.
7986         isFunctionTemplateSpecialization = true;
7987       }
7988     } else if (isFriend && isFunctionTemplateSpecialization) {
7989       // This combination is only possible in a recovery case;  the user
7990       // wrote something like:
7991       //   template <> friend void foo(int);
7992       // which we're recovering from as if the user had written:
7993       //   friend void foo<>(int);
7994       // Go ahead and fake up a template id.
7995       HasExplicitTemplateArgs = true;
7996       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7997       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7998     }
7999 
8000     // If it's a friend (and only if it's a friend), it's possible
8001     // that either the specialized function type or the specialized
8002     // template is dependent, and therefore matching will fail.  In
8003     // this case, don't check the specialization yet.
8004     bool InstantiationDependent = false;
8005     if (isFunctionTemplateSpecialization && isFriend &&
8006         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8007          TemplateSpecializationType::anyDependentTemplateArguments(
8008             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8009             InstantiationDependent))) {
8010       assert(HasExplicitTemplateArgs &&
8011              "friend function specialization without template args");
8012       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8013                                                        Previous))
8014         NewFD->setInvalidDecl();
8015     } else if (isFunctionTemplateSpecialization) {
8016       if (CurContext->isDependentContext() && CurContext->isRecord()
8017           && !isFriend) {
8018         isDependentClassScopeExplicitSpecialization = true;
8019         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8020           diag::ext_function_specialization_in_class :
8021           diag::err_function_specialization_in_class)
8022           << NewFD->getDeclName();
8023       } else if (CheckFunctionTemplateSpecialization(NewFD,
8024                                   (HasExplicitTemplateArgs ? &TemplateArgs
8025                                                            : nullptr),
8026                                                      Previous))
8027         NewFD->setInvalidDecl();
8028 
8029       // C++ [dcl.stc]p1:
8030       //   A storage-class-specifier shall not be specified in an explicit
8031       //   specialization (14.7.3)
8032       FunctionTemplateSpecializationInfo *Info =
8033           NewFD->getTemplateSpecializationInfo();
8034       if (Info && SC != SC_None) {
8035         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8036           Diag(NewFD->getLocation(),
8037                diag::err_explicit_specialization_inconsistent_storage_class)
8038             << SC
8039             << FixItHint::CreateRemoval(
8040                                       D.getDeclSpec().getStorageClassSpecLoc());
8041 
8042         else
8043           Diag(NewFD->getLocation(),
8044                diag::ext_explicit_specialization_storage_class)
8045             << FixItHint::CreateRemoval(
8046                                       D.getDeclSpec().getStorageClassSpecLoc());
8047       }
8048 
8049     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8050       if (CheckMemberSpecialization(NewFD, Previous))
8051           NewFD->setInvalidDecl();
8052     }
8053 
8054     // Perform semantic checking on the function declaration.
8055     if (!isDependentClassScopeExplicitSpecialization) {
8056       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8057         CheckMain(NewFD, D.getDeclSpec());
8058 
8059       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8060         CheckMSVCRTEntryPoint(NewFD);
8061 
8062       if (!NewFD->isInvalidDecl())
8063         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8064                                                     isExplicitSpecialization));
8065       else if (!Previous.empty())
8066         // Recover gracefully from an invalid redeclaration.
8067         D.setRedeclaration(true);
8068     }
8069 
8070     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8071             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8072            "previous declaration set still overloaded");
8073 
8074     NamedDecl *PrincipalDecl = (FunctionTemplate
8075                                 ? cast<NamedDecl>(FunctionTemplate)
8076                                 : NewFD);
8077 
8078     if (isFriend && D.isRedeclaration()) {
8079       AccessSpecifier Access = AS_public;
8080       if (!NewFD->isInvalidDecl())
8081         Access = NewFD->getPreviousDecl()->getAccess();
8082 
8083       NewFD->setAccess(Access);
8084       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8085     }
8086 
8087     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8088         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8089       PrincipalDecl->setNonMemberOperator();
8090 
8091     // If we have a function template, check the template parameter
8092     // list. This will check and merge default template arguments.
8093     if (FunctionTemplate) {
8094       FunctionTemplateDecl *PrevTemplate =
8095                                      FunctionTemplate->getPreviousDecl();
8096       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8097                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8098                                     : nullptr,
8099                             D.getDeclSpec().isFriendSpecified()
8100                               ? (D.isFunctionDefinition()
8101                                    ? TPC_FriendFunctionTemplateDefinition
8102                                    : TPC_FriendFunctionTemplate)
8103                               : (D.getCXXScopeSpec().isSet() &&
8104                                  DC && DC->isRecord() &&
8105                                  DC->isDependentContext())
8106                                   ? TPC_ClassTemplateMember
8107                                   : TPC_FunctionTemplate);
8108     }
8109 
8110     if (NewFD->isInvalidDecl()) {
8111       // Ignore all the rest of this.
8112     } else if (!D.isRedeclaration()) {
8113       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8114                                        AddToScope };
8115       // Fake up an access specifier if it's supposed to be a class member.
8116       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8117         NewFD->setAccess(AS_public);
8118 
8119       // Qualified decls generally require a previous declaration.
8120       if (D.getCXXScopeSpec().isSet()) {
8121         // ...with the major exception of templated-scope or
8122         // dependent-scope friend declarations.
8123 
8124         // TODO: we currently also suppress this check in dependent
8125         // contexts because (1) the parameter depth will be off when
8126         // matching friend templates and (2) we might actually be
8127         // selecting a friend based on a dependent factor.  But there
8128         // are situations where these conditions don't apply and we
8129         // can actually do this check immediately.
8130         if (isFriend &&
8131             (TemplateParamLists.size() ||
8132              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8133              CurContext->isDependentContext())) {
8134           // ignore these
8135         } else {
8136           // The user tried to provide an out-of-line definition for a
8137           // function that is a member of a class or namespace, but there
8138           // was no such member function declared (C++ [class.mfct]p2,
8139           // C++ [namespace.memdef]p2). For example:
8140           //
8141           // class X {
8142           //   void f() const;
8143           // };
8144           //
8145           // void X::f() { } // ill-formed
8146           //
8147           // Complain about this problem, and attempt to suggest close
8148           // matches (e.g., those that differ only in cv-qualifiers and
8149           // whether the parameter types are references).
8150 
8151           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8152                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8153             AddToScope = ExtraArgs.AddToScope;
8154             return Result;
8155           }
8156         }
8157 
8158         // Unqualified local friend declarations are required to resolve
8159         // to something.
8160       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8161         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8162                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8163           AddToScope = ExtraArgs.AddToScope;
8164           return Result;
8165         }
8166       }
8167 
8168     } else if (!D.isFunctionDefinition() &&
8169                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8170                !isFriend && !isFunctionTemplateSpecialization &&
8171                !isExplicitSpecialization) {
8172       // An out-of-line member function declaration must also be a
8173       // definition (C++ [class.mfct]p2).
8174       // Note that this is not the case for explicit specializations of
8175       // function templates or member functions of class templates, per
8176       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8177       // extension for compatibility with old SWIG code which likes to
8178       // generate them.
8179       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8180         << D.getCXXScopeSpec().getRange();
8181     }
8182   }
8183 
8184   ProcessPragmaWeak(S, NewFD);
8185   checkAttributesAfterMerging(*this, *NewFD);
8186 
8187   AddKnownFunctionAttributes(NewFD);
8188 
8189   if (NewFD->hasAttr<OverloadableAttr>() &&
8190       !NewFD->getType()->getAs<FunctionProtoType>()) {
8191     Diag(NewFD->getLocation(),
8192          diag::err_attribute_overloadable_no_prototype)
8193       << NewFD;
8194 
8195     // Turn this into a variadic function with no parameters.
8196     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8197     FunctionProtoType::ExtProtoInfo EPI(
8198         Context.getDefaultCallingConvention(true, false));
8199     EPI.Variadic = true;
8200     EPI.ExtInfo = FT->getExtInfo();
8201 
8202     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8203     NewFD->setType(R);
8204   }
8205 
8206   // If there's a #pragma GCC visibility in scope, and this isn't a class
8207   // member, set the visibility of this function.
8208   if (!DC->isRecord() && NewFD->isExternallyVisible())
8209     AddPushedVisibilityAttribute(NewFD);
8210 
8211   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8212   // marking the function.
8213   AddCFAuditedAttribute(NewFD);
8214 
8215   // If this is a function definition, check if we have to apply optnone due to
8216   // a pragma.
8217   if(D.isFunctionDefinition())
8218     AddRangeBasedOptnone(NewFD);
8219 
8220   // If this is the first declaration of an extern C variable, update
8221   // the map of such variables.
8222   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8223       isIncompleteDeclExternC(*this, NewFD))
8224     RegisterLocallyScopedExternCDecl(NewFD, S);
8225 
8226   // Set this FunctionDecl's range up to the right paren.
8227   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8228 
8229   if (D.isRedeclaration() && !Previous.empty()) {
8230     checkDLLAttributeRedeclaration(
8231         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8232         isExplicitSpecialization || isFunctionTemplateSpecialization);
8233   }
8234 
8235   if (getLangOpts().CPlusPlus) {
8236     if (FunctionTemplate) {
8237       if (NewFD->isInvalidDecl())
8238         FunctionTemplate->setInvalidDecl();
8239       return FunctionTemplate;
8240     }
8241   }
8242 
8243   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8244     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8245     if ((getLangOpts().OpenCLVersion >= 120)
8246         && (SC == SC_Static)) {
8247       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8248       D.setInvalidType();
8249     }
8250 
8251     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8252     if (!NewFD->getReturnType()->isVoidType()) {
8253       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8254       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8255           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8256                                 : FixItHint());
8257       D.setInvalidType();
8258     }
8259 
8260     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8261     for (auto Param : NewFD->params())
8262       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8263   }
8264   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8265        PE = NewFD->param_end(); PI != PE; ++PI) {
8266     ParmVarDecl *Param = *PI;
8267     QualType PT = Param->getType();
8268 
8269     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8270     // types.
8271     if (getLangOpts().OpenCLVersion >= 200) {
8272       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8273         QualType ElemTy = PipeTy->getElementType();
8274           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8275             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8276             D.setInvalidType();
8277           }
8278       }
8279     }
8280   }
8281 
8282   MarkUnusedFileScopedDecl(NewFD);
8283 
8284   if (getLangOpts().CUDA) {
8285     IdentifierInfo *II = NewFD->getIdentifier();
8286     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8287         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8288       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8289         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8290 
8291       Context.setcudaConfigureCallDecl(NewFD);
8292     }
8293 
8294     // Variadic functions, other than a *declaration* of printf, are not allowed
8295     // in device-side CUDA code, unless someone passed
8296     // -fcuda-allow-variadic-functions.
8297     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8298         (NewFD->hasAttr<CUDADeviceAttr>() ||
8299          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8300         !(II && II->isStr("printf") && NewFD->isExternC() &&
8301           !D.isFunctionDefinition())) {
8302       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8303     }
8304   }
8305 
8306   // Here we have an function template explicit specialization at class scope.
8307   // The actually specialization will be postponed to template instatiation
8308   // time via the ClassScopeFunctionSpecializationDecl node.
8309   if (isDependentClassScopeExplicitSpecialization) {
8310     ClassScopeFunctionSpecializationDecl *NewSpec =
8311                          ClassScopeFunctionSpecializationDecl::Create(
8312                                 Context, CurContext, SourceLocation(),
8313                                 cast<CXXMethodDecl>(NewFD),
8314                                 HasExplicitTemplateArgs, TemplateArgs);
8315     CurContext->addDecl(NewSpec);
8316     AddToScope = false;
8317   }
8318 
8319   return NewFD;
8320 }
8321 
8322 /// \brief Perform semantic checking of a new function declaration.
8323 ///
8324 /// Performs semantic analysis of the new function declaration
8325 /// NewFD. This routine performs all semantic checking that does not
8326 /// require the actual declarator involved in the declaration, and is
8327 /// used both for the declaration of functions as they are parsed
8328 /// (called via ActOnDeclarator) and for the declaration of functions
8329 /// that have been instantiated via C++ template instantiation (called
8330 /// via InstantiateDecl).
8331 ///
8332 /// \param IsExplicitSpecialization whether this new function declaration is
8333 /// an explicit specialization of the previous declaration.
8334 ///
8335 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8336 ///
8337 /// \returns true if the function declaration is a redeclaration.
8338 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8339                                     LookupResult &Previous,
8340                                     bool IsExplicitSpecialization) {
8341   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8342          "Variably modified return types are not handled here");
8343 
8344   // Determine whether the type of this function should be merged with
8345   // a previous visible declaration. This never happens for functions in C++,
8346   // and always happens in C if the previous declaration was visible.
8347   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8348                                !Previous.isShadowed();
8349 
8350   bool Redeclaration = false;
8351   NamedDecl *OldDecl = nullptr;
8352 
8353   // Merge or overload the declaration with an existing declaration of
8354   // the same name, if appropriate.
8355   if (!Previous.empty()) {
8356     // Determine whether NewFD is an overload of PrevDecl or
8357     // a declaration that requires merging. If it's an overload,
8358     // there's no more work to do here; we'll just add the new
8359     // function to the scope.
8360     if (!AllowOverloadingOfFunction(Previous, Context)) {
8361       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8362       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8363         Redeclaration = true;
8364         OldDecl = Candidate;
8365       }
8366     } else {
8367       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8368                             /*NewIsUsingDecl*/ false)) {
8369       case Ovl_Match:
8370         Redeclaration = true;
8371         break;
8372 
8373       case Ovl_NonFunction:
8374         Redeclaration = true;
8375         break;
8376 
8377       case Ovl_Overload:
8378         Redeclaration = false;
8379         break;
8380       }
8381 
8382       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8383         // If a function name is overloadable in C, then every function
8384         // with that name must be marked "overloadable".
8385         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8386           << Redeclaration << NewFD;
8387         NamedDecl *OverloadedDecl = nullptr;
8388         if (Redeclaration)
8389           OverloadedDecl = OldDecl;
8390         else if (!Previous.empty())
8391           OverloadedDecl = Previous.getRepresentativeDecl();
8392         if (OverloadedDecl)
8393           Diag(OverloadedDecl->getLocation(),
8394                diag::note_attribute_overloadable_prev_overload);
8395         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8396       }
8397     }
8398   }
8399 
8400   // Check for a previous extern "C" declaration with this name.
8401   if (!Redeclaration &&
8402       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8403     if (!Previous.empty()) {
8404       // This is an extern "C" declaration with the same name as a previous
8405       // declaration, and thus redeclares that entity...
8406       Redeclaration = true;
8407       OldDecl = Previous.getFoundDecl();
8408       MergeTypeWithPrevious = false;
8409 
8410       // ... except in the presence of __attribute__((overloadable)).
8411       if (OldDecl->hasAttr<OverloadableAttr>()) {
8412         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8413           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8414             << Redeclaration << NewFD;
8415           Diag(Previous.getFoundDecl()->getLocation(),
8416                diag::note_attribute_overloadable_prev_overload);
8417           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8418         }
8419         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8420           Redeclaration = false;
8421           OldDecl = nullptr;
8422         }
8423       }
8424     }
8425   }
8426 
8427   // C++11 [dcl.constexpr]p8:
8428   //   A constexpr specifier for a non-static member function that is not
8429   //   a constructor declares that member function to be const.
8430   //
8431   // This needs to be delayed until we know whether this is an out-of-line
8432   // definition of a static member function.
8433   //
8434   // This rule is not present in C++1y, so we produce a backwards
8435   // compatibility warning whenever it happens in C++11.
8436   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8437   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8438       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8439       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8440     CXXMethodDecl *OldMD = nullptr;
8441     if (OldDecl)
8442       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8443     if (!OldMD || !OldMD->isStatic()) {
8444       const FunctionProtoType *FPT =
8445         MD->getType()->castAs<FunctionProtoType>();
8446       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8447       EPI.TypeQuals |= Qualifiers::Const;
8448       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8449                                           FPT->getParamTypes(), EPI));
8450 
8451       // Warn that we did this, if we're not performing template instantiation.
8452       // In that case, we'll have warned already when the template was defined.
8453       if (ActiveTemplateInstantiations.empty()) {
8454         SourceLocation AddConstLoc;
8455         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8456                 .IgnoreParens().getAs<FunctionTypeLoc>())
8457           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8458 
8459         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8460           << FixItHint::CreateInsertion(AddConstLoc, " const");
8461       }
8462     }
8463   }
8464 
8465   if (Redeclaration) {
8466     // NewFD and OldDecl represent declarations that need to be
8467     // merged.
8468     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8469       NewFD->setInvalidDecl();
8470       return Redeclaration;
8471     }
8472 
8473     Previous.clear();
8474     Previous.addDecl(OldDecl);
8475 
8476     if (FunctionTemplateDecl *OldTemplateDecl
8477                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8478       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8479       FunctionTemplateDecl *NewTemplateDecl
8480         = NewFD->getDescribedFunctionTemplate();
8481       assert(NewTemplateDecl && "Template/non-template mismatch");
8482       if (CXXMethodDecl *Method
8483             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8484         Method->setAccess(OldTemplateDecl->getAccess());
8485         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8486       }
8487 
8488       // If this is an explicit specialization of a member that is a function
8489       // template, mark it as a member specialization.
8490       if (IsExplicitSpecialization &&
8491           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8492         NewTemplateDecl->setMemberSpecialization();
8493         assert(OldTemplateDecl->isMemberSpecialization());
8494       }
8495 
8496     } else {
8497       // This needs to happen first so that 'inline' propagates.
8498       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8499 
8500       if (isa<CXXMethodDecl>(NewFD))
8501         NewFD->setAccess(OldDecl->getAccess());
8502     }
8503   }
8504 
8505   // Semantic checking for this function declaration (in isolation).
8506 
8507   if (getLangOpts().CPlusPlus) {
8508     // C++-specific checks.
8509     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8510       CheckConstructor(Constructor);
8511     } else if (CXXDestructorDecl *Destructor =
8512                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8513       CXXRecordDecl *Record = Destructor->getParent();
8514       QualType ClassType = Context.getTypeDeclType(Record);
8515 
8516       // FIXME: Shouldn't we be able to perform this check even when the class
8517       // type is dependent? Both gcc and edg can handle that.
8518       if (!ClassType->isDependentType()) {
8519         DeclarationName Name
8520           = Context.DeclarationNames.getCXXDestructorName(
8521                                         Context.getCanonicalType(ClassType));
8522         if (NewFD->getDeclName() != Name) {
8523           Diag(NewFD->getLocation(), diag::err_destructor_name);
8524           NewFD->setInvalidDecl();
8525           return Redeclaration;
8526         }
8527       }
8528     } else if (CXXConversionDecl *Conversion
8529                = dyn_cast<CXXConversionDecl>(NewFD)) {
8530       ActOnConversionDeclarator(Conversion);
8531     }
8532 
8533     // Find any virtual functions that this function overrides.
8534     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8535       if (!Method->isFunctionTemplateSpecialization() &&
8536           !Method->getDescribedFunctionTemplate() &&
8537           Method->isCanonicalDecl()) {
8538         if (AddOverriddenMethods(Method->getParent(), Method)) {
8539           // If the function was marked as "static", we have a problem.
8540           if (NewFD->getStorageClass() == SC_Static) {
8541             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8542           }
8543         }
8544       }
8545 
8546       if (Method->isStatic())
8547         checkThisInStaticMemberFunctionType(Method);
8548     }
8549 
8550     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8551     if (NewFD->isOverloadedOperator() &&
8552         CheckOverloadedOperatorDeclaration(NewFD)) {
8553       NewFD->setInvalidDecl();
8554       return Redeclaration;
8555     }
8556 
8557     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8558     if (NewFD->getLiteralIdentifier() &&
8559         CheckLiteralOperatorDeclaration(NewFD)) {
8560       NewFD->setInvalidDecl();
8561       return Redeclaration;
8562     }
8563 
8564     // In C++, check default arguments now that we have merged decls. Unless
8565     // the lexical context is the class, because in this case this is done
8566     // during delayed parsing anyway.
8567     if (!CurContext->isRecord())
8568       CheckCXXDefaultArguments(NewFD);
8569 
8570     // If this function declares a builtin function, check the type of this
8571     // declaration against the expected type for the builtin.
8572     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8573       ASTContext::GetBuiltinTypeError Error;
8574       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8575       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8576       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8577         // The type of this function differs from the type of the builtin,
8578         // so forget about the builtin entirely.
8579         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8580       }
8581     }
8582 
8583     // If this function is declared as being extern "C", then check to see if
8584     // the function returns a UDT (class, struct, or union type) that is not C
8585     // compatible, and if it does, warn the user.
8586     // But, issue any diagnostic on the first declaration only.
8587     if (Previous.empty() && NewFD->isExternC()) {
8588       QualType R = NewFD->getReturnType();
8589       if (R->isIncompleteType() && !R->isVoidType())
8590         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8591             << NewFD << R;
8592       else if (!R.isPODType(Context) && !R->isVoidType() &&
8593                !R->isObjCObjectPointerType())
8594         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8595     }
8596   }
8597   return Redeclaration;
8598 }
8599 
8600 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8601   // C++11 [basic.start.main]p3:
8602   //   A program that [...] declares main to be inline, static or
8603   //   constexpr is ill-formed.
8604   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8605   //   appear in a declaration of main.
8606   // static main is not an error under C99, but we should warn about it.
8607   // We accept _Noreturn main as an extension.
8608   if (FD->getStorageClass() == SC_Static)
8609     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8610          ? diag::err_static_main : diag::warn_static_main)
8611       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8612   if (FD->isInlineSpecified())
8613     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8614       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8615   if (DS.isNoreturnSpecified()) {
8616     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8617     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8618     Diag(NoreturnLoc, diag::ext_noreturn_main);
8619     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8620       << FixItHint::CreateRemoval(NoreturnRange);
8621   }
8622   if (FD->isConstexpr()) {
8623     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8624       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8625     FD->setConstexpr(false);
8626   }
8627 
8628   if (getLangOpts().OpenCL) {
8629     Diag(FD->getLocation(), diag::err_opencl_no_main)
8630         << FD->hasAttr<OpenCLKernelAttr>();
8631     FD->setInvalidDecl();
8632     return;
8633   }
8634 
8635   QualType T = FD->getType();
8636   assert(T->isFunctionType() && "function decl is not of function type");
8637   const FunctionType* FT = T->castAs<FunctionType>();
8638 
8639   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8640     // In C with GNU extensions we allow main() to have non-integer return
8641     // type, but we should warn about the extension, and we disable the
8642     // implicit-return-zero rule.
8643 
8644     // GCC in C mode accepts qualified 'int'.
8645     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8646       FD->setHasImplicitReturnZero(true);
8647     else {
8648       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8649       SourceRange RTRange = FD->getReturnTypeSourceRange();
8650       if (RTRange.isValid())
8651         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8652             << FixItHint::CreateReplacement(RTRange, "int");
8653     }
8654   } else {
8655     // In C and C++, main magically returns 0 if you fall off the end;
8656     // set the flag which tells us that.
8657     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8658 
8659     // All the standards say that main() should return 'int'.
8660     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8661       FD->setHasImplicitReturnZero(true);
8662     else {
8663       // Otherwise, this is just a flat-out error.
8664       SourceRange RTRange = FD->getReturnTypeSourceRange();
8665       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8666           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8667                                 : FixItHint());
8668       FD->setInvalidDecl(true);
8669     }
8670   }
8671 
8672   // Treat protoless main() as nullary.
8673   if (isa<FunctionNoProtoType>(FT)) return;
8674 
8675   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8676   unsigned nparams = FTP->getNumParams();
8677   assert(FD->getNumParams() == nparams);
8678 
8679   bool HasExtraParameters = (nparams > 3);
8680 
8681   if (FTP->isVariadic()) {
8682     Diag(FD->getLocation(), diag::ext_variadic_main);
8683     // FIXME: if we had information about the location of the ellipsis, we
8684     // could add a FixIt hint to remove it as a parameter.
8685   }
8686 
8687   // Darwin passes an undocumented fourth argument of type char**.  If
8688   // other platforms start sprouting these, the logic below will start
8689   // getting shifty.
8690   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8691     HasExtraParameters = false;
8692 
8693   if (HasExtraParameters) {
8694     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8695     FD->setInvalidDecl(true);
8696     nparams = 3;
8697   }
8698 
8699   // FIXME: a lot of the following diagnostics would be improved
8700   // if we had some location information about types.
8701 
8702   QualType CharPP =
8703     Context.getPointerType(Context.getPointerType(Context.CharTy));
8704   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8705 
8706   for (unsigned i = 0; i < nparams; ++i) {
8707     QualType AT = FTP->getParamType(i);
8708 
8709     bool mismatch = true;
8710 
8711     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8712       mismatch = false;
8713     else if (Expected[i] == CharPP) {
8714       // As an extension, the following forms are okay:
8715       //   char const **
8716       //   char const * const *
8717       //   char * const *
8718 
8719       QualifierCollector qs;
8720       const PointerType* PT;
8721       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8722           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8723           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8724                               Context.CharTy)) {
8725         qs.removeConst();
8726         mismatch = !qs.empty();
8727       }
8728     }
8729 
8730     if (mismatch) {
8731       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8732       // TODO: suggest replacing given type with expected type
8733       FD->setInvalidDecl(true);
8734     }
8735   }
8736 
8737   if (nparams == 1 && !FD->isInvalidDecl()) {
8738     Diag(FD->getLocation(), diag::warn_main_one_arg);
8739   }
8740 
8741   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8742     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8743     FD->setInvalidDecl();
8744   }
8745 }
8746 
8747 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8748   QualType T = FD->getType();
8749   assert(T->isFunctionType() && "function decl is not of function type");
8750   const FunctionType *FT = T->castAs<FunctionType>();
8751 
8752   // Set an implicit return of 'zero' if the function can return some integral,
8753   // enumeration, pointer or nullptr type.
8754   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8755       FT->getReturnType()->isAnyPointerType() ||
8756       FT->getReturnType()->isNullPtrType())
8757     // DllMain is exempt because a return value of zero means it failed.
8758     if (FD->getName() != "DllMain")
8759       FD->setHasImplicitReturnZero(true);
8760 
8761   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8762     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8763     FD->setInvalidDecl();
8764   }
8765 }
8766 
8767 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8768   // FIXME: Need strict checking.  In C89, we need to check for
8769   // any assignment, increment, decrement, function-calls, or
8770   // commas outside of a sizeof.  In C99, it's the same list,
8771   // except that the aforementioned are allowed in unevaluated
8772   // expressions.  Everything else falls under the
8773   // "may accept other forms of constant expressions" exception.
8774   // (We never end up here for C++, so the constant expression
8775   // rules there don't matter.)
8776   const Expr *Culprit;
8777   if (Init->isConstantInitializer(Context, false, &Culprit))
8778     return false;
8779   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8780     << Culprit->getSourceRange();
8781   return true;
8782 }
8783 
8784 namespace {
8785   // Visits an initialization expression to see if OrigDecl is evaluated in
8786   // its own initialization and throws a warning if it does.
8787   class SelfReferenceChecker
8788       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8789     Sema &S;
8790     Decl *OrigDecl;
8791     bool isRecordType;
8792     bool isPODType;
8793     bool isReferenceType;
8794 
8795     bool isInitList;
8796     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8797   public:
8798     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8799 
8800     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8801                                                     S(S), OrigDecl(OrigDecl) {
8802       isPODType = false;
8803       isRecordType = false;
8804       isReferenceType = false;
8805       isInitList = false;
8806       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8807         isPODType = VD->getType().isPODType(S.Context);
8808         isRecordType = VD->getType()->isRecordType();
8809         isReferenceType = VD->getType()->isReferenceType();
8810       }
8811     }
8812 
8813     // For most expressions, just call the visitor.  For initializer lists,
8814     // track the index of the field being initialized since fields are
8815     // initialized in order allowing use of previously initialized fields.
8816     void CheckExpr(Expr *E) {
8817       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8818       if (!InitList) {
8819         Visit(E);
8820         return;
8821       }
8822 
8823       // Track and increment the index here.
8824       isInitList = true;
8825       InitFieldIndex.push_back(0);
8826       for (auto Child : InitList->children()) {
8827         CheckExpr(cast<Expr>(Child));
8828         ++InitFieldIndex.back();
8829       }
8830       InitFieldIndex.pop_back();
8831     }
8832 
8833     // Returns true if MemberExpr is checked and no futher checking is needed.
8834     // Returns false if additional checking is required.
8835     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8836       llvm::SmallVector<FieldDecl*, 4> Fields;
8837       Expr *Base = E;
8838       bool ReferenceField = false;
8839 
8840       // Get the field memebers used.
8841       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8842         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8843         if (!FD)
8844           return false;
8845         Fields.push_back(FD);
8846         if (FD->getType()->isReferenceType())
8847           ReferenceField = true;
8848         Base = ME->getBase()->IgnoreParenImpCasts();
8849       }
8850 
8851       // Keep checking only if the base Decl is the same.
8852       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8853       if (!DRE || DRE->getDecl() != OrigDecl)
8854         return false;
8855 
8856       // A reference field can be bound to an unininitialized field.
8857       if (CheckReference && !ReferenceField)
8858         return true;
8859 
8860       // Convert FieldDecls to their index number.
8861       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8862       for (const FieldDecl *I : llvm::reverse(Fields))
8863         UsedFieldIndex.push_back(I->getFieldIndex());
8864 
8865       // See if a warning is needed by checking the first difference in index
8866       // numbers.  If field being used has index less than the field being
8867       // initialized, then the use is safe.
8868       for (auto UsedIter = UsedFieldIndex.begin(),
8869                 UsedEnd = UsedFieldIndex.end(),
8870                 OrigIter = InitFieldIndex.begin(),
8871                 OrigEnd = InitFieldIndex.end();
8872            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8873         if (*UsedIter < *OrigIter)
8874           return true;
8875         if (*UsedIter > *OrigIter)
8876           break;
8877       }
8878 
8879       // TODO: Add a different warning which will print the field names.
8880       HandleDeclRefExpr(DRE);
8881       return true;
8882     }
8883 
8884     // For most expressions, the cast is directly above the DeclRefExpr.
8885     // For conditional operators, the cast can be outside the conditional
8886     // operator if both expressions are DeclRefExpr's.
8887     void HandleValue(Expr *E) {
8888       E = E->IgnoreParens();
8889       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8890         HandleDeclRefExpr(DRE);
8891         return;
8892       }
8893 
8894       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8895         Visit(CO->getCond());
8896         HandleValue(CO->getTrueExpr());
8897         HandleValue(CO->getFalseExpr());
8898         return;
8899       }
8900 
8901       if (BinaryConditionalOperator *BCO =
8902               dyn_cast<BinaryConditionalOperator>(E)) {
8903         Visit(BCO->getCond());
8904         HandleValue(BCO->getFalseExpr());
8905         return;
8906       }
8907 
8908       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8909         HandleValue(OVE->getSourceExpr());
8910         return;
8911       }
8912 
8913       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8914         if (BO->getOpcode() == BO_Comma) {
8915           Visit(BO->getLHS());
8916           HandleValue(BO->getRHS());
8917           return;
8918         }
8919       }
8920 
8921       if (isa<MemberExpr>(E)) {
8922         if (isInitList) {
8923           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8924                                       false /*CheckReference*/))
8925             return;
8926         }
8927 
8928         Expr *Base = E->IgnoreParenImpCasts();
8929         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8930           // Check for static member variables and don't warn on them.
8931           if (!isa<FieldDecl>(ME->getMemberDecl()))
8932             return;
8933           Base = ME->getBase()->IgnoreParenImpCasts();
8934         }
8935         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8936           HandleDeclRefExpr(DRE);
8937         return;
8938       }
8939 
8940       Visit(E);
8941     }
8942 
8943     // Reference types not handled in HandleValue are handled here since all
8944     // uses of references are bad, not just r-value uses.
8945     void VisitDeclRefExpr(DeclRefExpr *E) {
8946       if (isReferenceType)
8947         HandleDeclRefExpr(E);
8948     }
8949 
8950     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8951       if (E->getCastKind() == CK_LValueToRValue) {
8952         HandleValue(E->getSubExpr());
8953         return;
8954       }
8955 
8956       Inherited::VisitImplicitCastExpr(E);
8957     }
8958 
8959     void VisitMemberExpr(MemberExpr *E) {
8960       if (isInitList) {
8961         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8962           return;
8963       }
8964 
8965       // Don't warn on arrays since they can be treated as pointers.
8966       if (E->getType()->canDecayToPointerType()) return;
8967 
8968       // Warn when a non-static method call is followed by non-static member
8969       // field accesses, which is followed by a DeclRefExpr.
8970       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8971       bool Warn = (MD && !MD->isStatic());
8972       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8973       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8974         if (!isa<FieldDecl>(ME->getMemberDecl()))
8975           Warn = false;
8976         Base = ME->getBase()->IgnoreParenImpCasts();
8977       }
8978 
8979       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8980         if (Warn)
8981           HandleDeclRefExpr(DRE);
8982         return;
8983       }
8984 
8985       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8986       // Visit that expression.
8987       Visit(Base);
8988     }
8989 
8990     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8991       Expr *Callee = E->getCallee();
8992 
8993       if (isa<UnresolvedLookupExpr>(Callee))
8994         return Inherited::VisitCXXOperatorCallExpr(E);
8995 
8996       Visit(Callee);
8997       for (auto Arg: E->arguments())
8998         HandleValue(Arg->IgnoreParenImpCasts());
8999     }
9000 
9001     void VisitUnaryOperator(UnaryOperator *E) {
9002       // For POD record types, addresses of its own members are well-defined.
9003       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9004           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9005         if (!isPODType)
9006           HandleValue(E->getSubExpr());
9007         return;
9008       }
9009 
9010       if (E->isIncrementDecrementOp()) {
9011         HandleValue(E->getSubExpr());
9012         return;
9013       }
9014 
9015       Inherited::VisitUnaryOperator(E);
9016     }
9017 
9018     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
9019 
9020     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9021       if (E->getConstructor()->isCopyConstructor()) {
9022         Expr *ArgExpr = E->getArg(0);
9023         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9024           if (ILE->getNumInits() == 1)
9025             ArgExpr = ILE->getInit(0);
9026         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9027           if (ICE->getCastKind() == CK_NoOp)
9028             ArgExpr = ICE->getSubExpr();
9029         HandleValue(ArgExpr);
9030         return;
9031       }
9032       Inherited::VisitCXXConstructExpr(E);
9033     }
9034 
9035     void VisitCallExpr(CallExpr *E) {
9036       // Treat std::move as a use.
9037       if (E->getNumArgs() == 1) {
9038         if (FunctionDecl *FD = E->getDirectCallee()) {
9039           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9040               FD->getIdentifier()->isStr("move")) {
9041             HandleValue(E->getArg(0));
9042             return;
9043           }
9044         }
9045       }
9046 
9047       Inherited::VisitCallExpr(E);
9048     }
9049 
9050     void VisitBinaryOperator(BinaryOperator *E) {
9051       if (E->isCompoundAssignmentOp()) {
9052         HandleValue(E->getLHS());
9053         Visit(E->getRHS());
9054         return;
9055       }
9056 
9057       Inherited::VisitBinaryOperator(E);
9058     }
9059 
9060     // A custom visitor for BinaryConditionalOperator is needed because the
9061     // regular visitor would check the condition and true expression separately
9062     // but both point to the same place giving duplicate diagnostics.
9063     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9064       Visit(E->getCond());
9065       Visit(E->getFalseExpr());
9066     }
9067 
9068     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9069       Decl* ReferenceDecl = DRE->getDecl();
9070       if (OrigDecl != ReferenceDecl) return;
9071       unsigned diag;
9072       if (isReferenceType) {
9073         diag = diag::warn_uninit_self_reference_in_reference_init;
9074       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9075         diag = diag::warn_static_self_reference_in_init;
9076       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9077                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9078                  DRE->getDecl()->getType()->isRecordType()) {
9079         diag = diag::warn_uninit_self_reference_in_init;
9080       } else {
9081         // Local variables will be handled by the CFG analysis.
9082         return;
9083       }
9084 
9085       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9086                             S.PDiag(diag)
9087                               << DRE->getNameInfo().getName()
9088                               << OrigDecl->getLocation()
9089                               << DRE->getSourceRange());
9090     }
9091   };
9092 
9093   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9094   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9095                                  bool DirectInit) {
9096     // Parameters arguments are occassionially constructed with itself,
9097     // for instance, in recursive functions.  Skip them.
9098     if (isa<ParmVarDecl>(OrigDecl))
9099       return;
9100 
9101     E = E->IgnoreParens();
9102 
9103     // Skip checking T a = a where T is not a record or reference type.
9104     // Doing so is a way to silence uninitialized warnings.
9105     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9106       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9107         if (ICE->getCastKind() == CK_LValueToRValue)
9108           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9109             if (DRE->getDecl() == OrigDecl)
9110               return;
9111 
9112     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9113   }
9114 }
9115 
9116 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9117                                             DeclarationName Name, QualType Type,
9118                                             TypeSourceInfo *TSI,
9119                                             SourceRange Range, bool DirectInit,
9120                                             Expr *Init) {
9121   bool IsInitCapture = !VDecl;
9122   assert((!VDecl || !VDecl->isInitCapture()) &&
9123          "init captures are expected to be deduced prior to initialization");
9124 
9125   ArrayRef<Expr *> DeduceInits = Init;
9126   if (DirectInit) {
9127     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9128       DeduceInits = PL->exprs();
9129     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9130       DeduceInits = IL->inits();
9131   }
9132 
9133   // Deduction only works if we have exactly one source expression.
9134   if (DeduceInits.empty()) {
9135     // It isn't possible to write this directly, but it is possible to
9136     // end up in this situation with "auto x(some_pack...);"
9137     Diag(Init->getLocStart(), IsInitCapture
9138                                   ? diag::err_init_capture_no_expression
9139                                   : diag::err_auto_var_init_no_expression)
9140         << Name << Type << Range;
9141     return QualType();
9142   }
9143 
9144   if (DeduceInits.size() > 1) {
9145     Diag(DeduceInits[1]->getLocStart(),
9146          IsInitCapture ? diag::err_init_capture_multiple_expressions
9147                        : diag::err_auto_var_init_multiple_expressions)
9148         << Name << Type << Range;
9149     return QualType();
9150   }
9151 
9152   Expr *DeduceInit = DeduceInits[0];
9153   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9154     Diag(Init->getLocStart(), IsInitCapture
9155                                   ? diag::err_init_capture_paren_braces
9156                                   : diag::err_auto_var_init_paren_braces)
9157         << isa<InitListExpr>(Init) << Name << Type << Range;
9158     return QualType();
9159   }
9160 
9161   // Expressions default to 'id' when we're in a debugger.
9162   bool DefaultedAnyToId = false;
9163   if (getLangOpts().DebuggerCastResultToId &&
9164       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9165     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9166     if (Result.isInvalid()) {
9167       return QualType();
9168     }
9169     Init = Result.get();
9170     DefaultedAnyToId = true;
9171   }
9172 
9173   QualType DeducedType;
9174   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9175     if (!IsInitCapture)
9176       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9177     else if (isa<InitListExpr>(Init))
9178       Diag(Range.getBegin(),
9179            diag::err_init_capture_deduction_failure_from_init_list)
9180           << Name
9181           << (DeduceInit->getType().isNull() ? TSI->getType()
9182                                              : DeduceInit->getType())
9183           << DeduceInit->getSourceRange();
9184     else
9185       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9186           << Name << TSI->getType()
9187           << (DeduceInit->getType().isNull() ? TSI->getType()
9188                                              : DeduceInit->getType())
9189           << DeduceInit->getSourceRange();
9190   }
9191 
9192   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9193   // 'id' instead of a specific object type prevents most of our usual
9194   // checks.
9195   // We only want to warn outside of template instantiations, though:
9196   // inside a template, the 'id' could have come from a parameter.
9197   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9198       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9199     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9200     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9201   }
9202 
9203   return DeducedType;
9204 }
9205 
9206 /// AddInitializerToDecl - Adds the initializer Init to the
9207 /// declaration dcl. If DirectInit is true, this is C++ direct
9208 /// initialization rather than copy initialization.
9209 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9210                                 bool DirectInit, bool TypeMayContainAuto) {
9211   // If there is no declaration, there was an error parsing it.  Just ignore
9212   // the initializer.
9213   if (!RealDecl || RealDecl->isInvalidDecl()) {
9214     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9215     return;
9216   }
9217 
9218   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9219     // Pure-specifiers are handled in ActOnPureSpecifier.
9220     Diag(Method->getLocation(), diag::err_member_function_initialization)
9221       << Method->getDeclName() << Init->getSourceRange();
9222     Method->setInvalidDecl();
9223     return;
9224   }
9225 
9226   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9227   if (!VDecl) {
9228     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9229     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9230     RealDecl->setInvalidDecl();
9231     return;
9232   }
9233 
9234   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9235   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9236     // Attempt typo correction early so that the type of the init expression can
9237     // be deduced based on the chosen correction if the original init contains a
9238     // TypoExpr.
9239     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9240     if (!Res.isUsable()) {
9241       RealDecl->setInvalidDecl();
9242       return;
9243     }
9244     Init = Res.get();
9245 
9246     QualType DeducedType = deduceVarTypeFromInitializer(
9247         VDecl, VDecl->getDeclName(), VDecl->getType(),
9248         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9249     if (DeducedType.isNull()) {
9250       RealDecl->setInvalidDecl();
9251       return;
9252     }
9253 
9254     VDecl->setType(DeducedType);
9255     assert(VDecl->isLinkageValid());
9256 
9257     // In ARC, infer lifetime.
9258     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9259       VDecl->setInvalidDecl();
9260 
9261     // If this is a redeclaration, check that the type we just deduced matches
9262     // the previously declared type.
9263     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9264       // We never need to merge the type, because we cannot form an incomplete
9265       // array of auto, nor deduce such a type.
9266       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9267     }
9268 
9269     // Check the deduced type is valid for a variable declaration.
9270     CheckVariableDeclarationType(VDecl);
9271     if (VDecl->isInvalidDecl())
9272       return;
9273   }
9274 
9275   // dllimport cannot be used on variable definitions.
9276   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9277     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9278     VDecl->setInvalidDecl();
9279     return;
9280   }
9281 
9282   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9283     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9284     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9285     VDecl->setInvalidDecl();
9286     return;
9287   }
9288 
9289   if (!VDecl->getType()->isDependentType()) {
9290     // A definition must end up with a complete type, which means it must be
9291     // complete with the restriction that an array type might be completed by
9292     // the initializer; note that later code assumes this restriction.
9293     QualType BaseDeclType = VDecl->getType();
9294     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9295       BaseDeclType = Array->getElementType();
9296     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9297                             diag::err_typecheck_decl_incomplete_type)) {
9298       RealDecl->setInvalidDecl();
9299       return;
9300     }
9301 
9302     // The variable can not have an abstract class type.
9303     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9304                                diag::err_abstract_type_in_decl,
9305                                AbstractVariableType))
9306       VDecl->setInvalidDecl();
9307   }
9308 
9309   VarDecl *Def;
9310   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9311     NamedDecl *Hidden = nullptr;
9312     if (!hasVisibleDefinition(Def, &Hidden) &&
9313         (VDecl->getFormalLinkage() == InternalLinkage ||
9314          VDecl->getDescribedVarTemplate() ||
9315          VDecl->getNumTemplateParameterLists() ||
9316          VDecl->getDeclContext()->isDependentContext())) {
9317       // The previous definition is hidden, and multiple definitions are
9318       // permitted (in separate TUs). Form another definition of it.
9319     } else {
9320       Diag(VDecl->getLocation(), diag::err_redefinition)
9321         << VDecl->getDeclName();
9322       Diag(Def->getLocation(), diag::note_previous_definition);
9323       VDecl->setInvalidDecl();
9324       return;
9325     }
9326   }
9327 
9328   if (getLangOpts().CPlusPlus) {
9329     // C++ [class.static.data]p4
9330     //   If a static data member is of const integral or const
9331     //   enumeration type, its declaration in the class definition can
9332     //   specify a constant-initializer which shall be an integral
9333     //   constant expression (5.19). In that case, the member can appear
9334     //   in integral constant expressions. The member shall still be
9335     //   defined in a namespace scope if it is used in the program and the
9336     //   namespace scope definition shall not contain an initializer.
9337     //
9338     // We already performed a redefinition check above, but for static
9339     // data members we also need to check whether there was an in-class
9340     // declaration with an initializer.
9341     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9342       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9343           << VDecl->getDeclName();
9344       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9345            diag::note_previous_initializer)
9346           << 0;
9347       return;
9348     }
9349 
9350     if (VDecl->hasLocalStorage())
9351       getCurFunction()->setHasBranchProtectedScope();
9352 
9353     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9354       VDecl->setInvalidDecl();
9355       return;
9356     }
9357   }
9358 
9359   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9360   // a kernel function cannot be initialized."
9361   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9362     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9363     VDecl->setInvalidDecl();
9364     return;
9365   }
9366 
9367   // Get the decls type and save a reference for later, since
9368   // CheckInitializerTypes may change it.
9369   QualType DclT = VDecl->getType(), SavT = DclT;
9370 
9371   // Expressions default to 'id' when we're in a debugger
9372   // and we are assigning it to a variable of Objective-C pointer type.
9373   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9374       Init->getType() == Context.UnknownAnyTy) {
9375     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9376     if (Result.isInvalid()) {
9377       VDecl->setInvalidDecl();
9378       return;
9379     }
9380     Init = Result.get();
9381   }
9382 
9383   // Perform the initialization.
9384   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9385   if (!VDecl->isInvalidDecl()) {
9386     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9387     InitializationKind Kind =
9388         DirectInit
9389             ? CXXDirectInit
9390                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9391                                                      Init->getLocStart(),
9392                                                      Init->getLocEnd())
9393                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9394             : InitializationKind::CreateCopy(VDecl->getLocation(),
9395                                              Init->getLocStart());
9396 
9397     MultiExprArg Args = Init;
9398     if (CXXDirectInit)
9399       Args = MultiExprArg(CXXDirectInit->getExprs(),
9400                           CXXDirectInit->getNumExprs());
9401 
9402     // Try to correct any TypoExprs in the initialization arguments.
9403     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9404       ExprResult Res = CorrectDelayedTyposInExpr(
9405           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9406             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9407             return Init.Failed() ? ExprError() : E;
9408           });
9409       if (Res.isInvalid()) {
9410         VDecl->setInvalidDecl();
9411       } else if (Res.get() != Args[Idx]) {
9412         Args[Idx] = Res.get();
9413       }
9414     }
9415     if (VDecl->isInvalidDecl())
9416       return;
9417 
9418     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9419     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9420     if (Result.isInvalid()) {
9421       VDecl->setInvalidDecl();
9422       return;
9423     }
9424 
9425     Init = Result.getAs<Expr>();
9426   }
9427 
9428   // Check for self-references within variable initializers.
9429   // Variables declared within a function/method body (except for references)
9430   // are handled by a dataflow analysis.
9431   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9432       VDecl->getType()->isReferenceType()) {
9433     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9434   }
9435 
9436   // If the type changed, it means we had an incomplete type that was
9437   // completed by the initializer. For example:
9438   //   int ary[] = { 1, 3, 5 };
9439   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9440   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9441     VDecl->setType(DclT);
9442 
9443   if (!VDecl->isInvalidDecl()) {
9444     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9445 
9446     if (VDecl->hasAttr<BlocksAttr>())
9447       checkRetainCycles(VDecl, Init);
9448 
9449     // It is safe to assign a weak reference into a strong variable.
9450     // Although this code can still have problems:
9451     //   id x = self.weakProp;
9452     //   id y = self.weakProp;
9453     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9454     // paths through the function. This should be revisited if
9455     // -Wrepeated-use-of-weak is made flow-sensitive.
9456     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9457         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9458                          Init->getLocStart()))
9459       getCurFunction()->markSafeWeakUse(Init);
9460   }
9461 
9462   // The initialization is usually a full-expression.
9463   //
9464   // FIXME: If this is a braced initialization of an aggregate, it is not
9465   // an expression, and each individual field initializer is a separate
9466   // full-expression. For instance, in:
9467   //
9468   //   struct Temp { ~Temp(); };
9469   //   struct S { S(Temp); };
9470   //   struct T { S a, b; } t = { Temp(), Temp() }
9471   //
9472   // we should destroy the first Temp before constructing the second.
9473   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9474                                           false,
9475                                           VDecl->isConstexpr());
9476   if (Result.isInvalid()) {
9477     VDecl->setInvalidDecl();
9478     return;
9479   }
9480   Init = Result.get();
9481 
9482   // Attach the initializer to the decl.
9483   VDecl->setInit(Init);
9484 
9485   if (VDecl->isLocalVarDecl()) {
9486     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9487     // static storage duration shall be constant expressions or string literals.
9488     // C++ does not have this restriction.
9489     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9490       const Expr *Culprit;
9491       if (VDecl->getStorageClass() == SC_Static)
9492         CheckForConstantInitializer(Init, DclT);
9493       // C89 is stricter than C99 for non-static aggregate types.
9494       // C89 6.5.7p3: All the expressions [...] in an initializer list
9495       // for an object that has aggregate or union type shall be
9496       // constant expressions.
9497       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9498                isa<InitListExpr>(Init) &&
9499                !Init->isConstantInitializer(Context, false, &Culprit))
9500         Diag(Culprit->getExprLoc(),
9501              diag::ext_aggregate_init_not_constant)
9502           << Culprit->getSourceRange();
9503     }
9504   } else if (VDecl->isStaticDataMember() &&
9505              VDecl->getLexicalDeclContext()->isRecord()) {
9506     // This is an in-class initialization for a static data member, e.g.,
9507     //
9508     // struct S {
9509     //   static const int value = 17;
9510     // };
9511 
9512     // C++ [class.mem]p4:
9513     //   A member-declarator can contain a constant-initializer only
9514     //   if it declares a static member (9.4) of const integral or
9515     //   const enumeration type, see 9.4.2.
9516     //
9517     // C++11 [class.static.data]p3:
9518     //   If a non-volatile const static data member is of integral or
9519     //   enumeration type, its declaration in the class definition can
9520     //   specify a brace-or-equal-initializer in which every initalizer-clause
9521     //   that is an assignment-expression is a constant expression. A static
9522     //   data member of literal type can be declared in the class definition
9523     //   with the constexpr specifier; if so, its declaration shall specify a
9524     //   brace-or-equal-initializer in which every initializer-clause that is
9525     //   an assignment-expression is a constant expression.
9526 
9527     // Do nothing on dependent types.
9528     if (DclT->isDependentType()) {
9529 
9530     // Allow any 'static constexpr' members, whether or not they are of literal
9531     // type. We separately check that every constexpr variable is of literal
9532     // type.
9533     } else if (VDecl->isConstexpr()) {
9534 
9535     // Require constness.
9536     } else if (!DclT.isConstQualified()) {
9537       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9538         << Init->getSourceRange();
9539       VDecl->setInvalidDecl();
9540 
9541     // We allow integer constant expressions in all cases.
9542     } else if (DclT->isIntegralOrEnumerationType()) {
9543       // Check whether the expression is a constant expression.
9544       SourceLocation Loc;
9545       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9546         // In C++11, a non-constexpr const static data member with an
9547         // in-class initializer cannot be volatile.
9548         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9549       else if (Init->isValueDependent())
9550         ; // Nothing to check.
9551       else if (Init->isIntegerConstantExpr(Context, &Loc))
9552         ; // Ok, it's an ICE!
9553       else if (Init->isEvaluatable(Context)) {
9554         // If we can constant fold the initializer through heroics, accept it,
9555         // but report this as a use of an extension for -pedantic.
9556         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9557           << Init->getSourceRange();
9558       } else {
9559         // Otherwise, this is some crazy unknown case.  Report the issue at the
9560         // location provided by the isIntegerConstantExpr failed check.
9561         Diag(Loc, diag::err_in_class_initializer_non_constant)
9562           << Init->getSourceRange();
9563         VDecl->setInvalidDecl();
9564       }
9565 
9566     // We allow foldable floating-point constants as an extension.
9567     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9568       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9569       // it anyway and provide a fixit to add the 'constexpr'.
9570       if (getLangOpts().CPlusPlus11) {
9571         Diag(VDecl->getLocation(),
9572              diag::ext_in_class_initializer_float_type_cxx11)
9573             << DclT << Init->getSourceRange();
9574         Diag(VDecl->getLocStart(),
9575              diag::note_in_class_initializer_float_type_cxx11)
9576             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9577       } else {
9578         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9579           << DclT << Init->getSourceRange();
9580 
9581         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9582           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9583             << Init->getSourceRange();
9584           VDecl->setInvalidDecl();
9585         }
9586       }
9587 
9588     // Suggest adding 'constexpr' in C++11 for literal types.
9589     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9590       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9591         << DclT << Init->getSourceRange()
9592         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9593       VDecl->setConstexpr(true);
9594 
9595     } else {
9596       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9597         << DclT << Init->getSourceRange();
9598       VDecl->setInvalidDecl();
9599     }
9600   } else if (VDecl->isFileVarDecl()) {
9601     if (VDecl->getStorageClass() == SC_Extern &&
9602         (!getLangOpts().CPlusPlus ||
9603          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9604            VDecl->isExternC())) &&
9605         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9606       Diag(VDecl->getLocation(), diag::warn_extern_init);
9607 
9608     // C99 6.7.8p4. All file scoped initializers need to be constant.
9609     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9610       CheckForConstantInitializer(Init, DclT);
9611   }
9612 
9613   // We will represent direct-initialization similarly to copy-initialization:
9614   //    int x(1);  -as-> int x = 1;
9615   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9616   //
9617   // Clients that want to distinguish between the two forms, can check for
9618   // direct initializer using VarDecl::getInitStyle().
9619   // A major benefit is that clients that don't particularly care about which
9620   // exactly form was it (like the CodeGen) can handle both cases without
9621   // special case code.
9622 
9623   // C++ 8.5p11:
9624   // The form of initialization (using parentheses or '=') is generally
9625   // insignificant, but does matter when the entity being initialized has a
9626   // class type.
9627   if (CXXDirectInit) {
9628     assert(DirectInit && "Call-style initializer must be direct init.");
9629     VDecl->setInitStyle(VarDecl::CallInit);
9630   } else if (DirectInit) {
9631     // This must be list-initialization. No other way is direct-initialization.
9632     VDecl->setInitStyle(VarDecl::ListInit);
9633   }
9634 
9635   CheckCompleteVariableDeclaration(VDecl);
9636 }
9637 
9638 /// ActOnInitializerError - Given that there was an error parsing an
9639 /// initializer for the given declaration, try to return to some form
9640 /// of sanity.
9641 void Sema::ActOnInitializerError(Decl *D) {
9642   // Our main concern here is re-establishing invariants like "a
9643   // variable's type is either dependent or complete".
9644   if (!D || D->isInvalidDecl()) return;
9645 
9646   VarDecl *VD = dyn_cast<VarDecl>(D);
9647   if (!VD) return;
9648 
9649   // Auto types are meaningless if we can't make sense of the initializer.
9650   if (ParsingInitForAutoVars.count(D)) {
9651     D->setInvalidDecl();
9652     return;
9653   }
9654 
9655   QualType Ty = VD->getType();
9656   if (Ty->isDependentType()) return;
9657 
9658   // Require a complete type.
9659   if (RequireCompleteType(VD->getLocation(),
9660                           Context.getBaseElementType(Ty),
9661                           diag::err_typecheck_decl_incomplete_type)) {
9662     VD->setInvalidDecl();
9663     return;
9664   }
9665 
9666   // Require a non-abstract type.
9667   if (RequireNonAbstractType(VD->getLocation(), Ty,
9668                              diag::err_abstract_type_in_decl,
9669                              AbstractVariableType)) {
9670     VD->setInvalidDecl();
9671     return;
9672   }
9673 
9674   // Don't bother complaining about constructors or destructors,
9675   // though.
9676 }
9677 
9678 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9679                                   bool TypeMayContainAuto) {
9680   // If there is no declaration, there was an error parsing it. Just ignore it.
9681   if (!RealDecl)
9682     return;
9683 
9684   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9685     QualType Type = Var->getType();
9686 
9687     // C++11 [dcl.spec.auto]p3
9688     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9689       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9690         << Var->getDeclName() << Type;
9691       Var->setInvalidDecl();
9692       return;
9693     }
9694 
9695     // C++11 [class.static.data]p3: A static data member can be declared with
9696     // the constexpr specifier; if so, its declaration shall specify
9697     // a brace-or-equal-initializer.
9698     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9699     // the definition of a variable [...] or the declaration of a static data
9700     // member.
9701     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9702       if (Var->isStaticDataMember())
9703         Diag(Var->getLocation(),
9704              diag::err_constexpr_static_mem_var_requires_init)
9705           << Var->getDeclName();
9706       else
9707         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9708       Var->setInvalidDecl();
9709       return;
9710     }
9711 
9712     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9713     // definition having the concept specifier is called a variable concept. A
9714     // concept definition refers to [...] a variable concept and its initializer.
9715     if (Var->isConcept()) {
9716       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9717       Var->setInvalidDecl();
9718       return;
9719     }
9720 
9721     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9722     // be initialized.
9723     if (!Var->isInvalidDecl() &&
9724         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9725         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9726       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9727       Var->setInvalidDecl();
9728       return;
9729     }
9730 
9731     switch (Var->isThisDeclarationADefinition()) {
9732     case VarDecl::Definition:
9733       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9734         break;
9735 
9736       // We have an out-of-line definition of a static data member
9737       // that has an in-class initializer, so we type-check this like
9738       // a declaration.
9739       //
9740       // Fall through
9741 
9742     case VarDecl::DeclarationOnly:
9743       // It's only a declaration.
9744 
9745       // Block scope. C99 6.7p7: If an identifier for an object is
9746       // declared with no linkage (C99 6.2.2p6), the type for the
9747       // object shall be complete.
9748       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9749           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9750           RequireCompleteType(Var->getLocation(), Type,
9751                               diag::err_typecheck_decl_incomplete_type))
9752         Var->setInvalidDecl();
9753 
9754       // Make sure that the type is not abstract.
9755       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9756           RequireNonAbstractType(Var->getLocation(), Type,
9757                                  diag::err_abstract_type_in_decl,
9758                                  AbstractVariableType))
9759         Var->setInvalidDecl();
9760       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9761           Var->getStorageClass() == SC_PrivateExtern) {
9762         Diag(Var->getLocation(), diag::warn_private_extern);
9763         Diag(Var->getLocation(), diag::note_private_extern);
9764       }
9765 
9766       return;
9767 
9768     case VarDecl::TentativeDefinition:
9769       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9770       // object that has file scope without an initializer, and without a
9771       // storage-class specifier or with the storage-class specifier "static",
9772       // constitutes a tentative definition. Note: A tentative definition with
9773       // external linkage is valid (C99 6.2.2p5).
9774       if (!Var->isInvalidDecl()) {
9775         if (const IncompleteArrayType *ArrayT
9776                                     = Context.getAsIncompleteArrayType(Type)) {
9777           if (RequireCompleteType(Var->getLocation(),
9778                                   ArrayT->getElementType(),
9779                                   diag::err_illegal_decl_array_incomplete_type))
9780             Var->setInvalidDecl();
9781         } else if (Var->getStorageClass() == SC_Static) {
9782           // C99 6.9.2p3: If the declaration of an identifier for an object is
9783           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9784           // declared type shall not be an incomplete type.
9785           // NOTE: code such as the following
9786           //     static struct s;
9787           //     struct s { int a; };
9788           // is accepted by gcc. Hence here we issue a warning instead of
9789           // an error and we do not invalidate the static declaration.
9790           // NOTE: to avoid multiple warnings, only check the first declaration.
9791           if (Var->isFirstDecl())
9792             RequireCompleteType(Var->getLocation(), Type,
9793                                 diag::ext_typecheck_decl_incomplete_type);
9794         }
9795       }
9796 
9797       // Record the tentative definition; we're done.
9798       if (!Var->isInvalidDecl())
9799         TentativeDefinitions.push_back(Var);
9800       return;
9801     }
9802 
9803     // Provide a specific diagnostic for uninitialized variable
9804     // definitions with incomplete array type.
9805     if (Type->isIncompleteArrayType()) {
9806       Diag(Var->getLocation(),
9807            diag::err_typecheck_incomplete_array_needs_initializer);
9808       Var->setInvalidDecl();
9809       return;
9810     }
9811 
9812     // Provide a specific diagnostic for uninitialized variable
9813     // definitions with reference type.
9814     if (Type->isReferenceType()) {
9815       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9816         << Var->getDeclName()
9817         << SourceRange(Var->getLocation(), Var->getLocation());
9818       Var->setInvalidDecl();
9819       return;
9820     }
9821 
9822     // Do not attempt to type-check the default initializer for a
9823     // variable with dependent type.
9824     if (Type->isDependentType())
9825       return;
9826 
9827     if (Var->isInvalidDecl())
9828       return;
9829 
9830     if (!Var->hasAttr<AliasAttr>()) {
9831       if (RequireCompleteType(Var->getLocation(),
9832                               Context.getBaseElementType(Type),
9833                               diag::err_typecheck_decl_incomplete_type)) {
9834         Var->setInvalidDecl();
9835         return;
9836       }
9837     } else {
9838       return;
9839     }
9840 
9841     // The variable can not have an abstract class type.
9842     if (RequireNonAbstractType(Var->getLocation(), Type,
9843                                diag::err_abstract_type_in_decl,
9844                                AbstractVariableType)) {
9845       Var->setInvalidDecl();
9846       return;
9847     }
9848 
9849     // Check for jumps past the implicit initializer.  C++0x
9850     // clarifies that this applies to a "variable with automatic
9851     // storage duration", not a "local variable".
9852     // C++11 [stmt.dcl]p3
9853     //   A program that jumps from a point where a variable with automatic
9854     //   storage duration is not in scope to a point where it is in scope is
9855     //   ill-formed unless the variable has scalar type, class type with a
9856     //   trivial default constructor and a trivial destructor, a cv-qualified
9857     //   version of one of these types, or an array of one of the preceding
9858     //   types and is declared without an initializer.
9859     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9860       if (const RecordType *Record
9861             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9862         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9863         // Mark the function for further checking even if the looser rules of
9864         // C++11 do not require such checks, so that we can diagnose
9865         // incompatibilities with C++98.
9866         if (!CXXRecord->isPOD())
9867           getCurFunction()->setHasBranchProtectedScope();
9868       }
9869     }
9870 
9871     // C++03 [dcl.init]p9:
9872     //   If no initializer is specified for an object, and the
9873     //   object is of (possibly cv-qualified) non-POD class type (or
9874     //   array thereof), the object shall be default-initialized; if
9875     //   the object is of const-qualified type, the underlying class
9876     //   type shall have a user-declared default
9877     //   constructor. Otherwise, if no initializer is specified for
9878     //   a non- static object, the object and its subobjects, if
9879     //   any, have an indeterminate initial value); if the object
9880     //   or any of its subobjects are of const-qualified type, the
9881     //   program is ill-formed.
9882     // C++0x [dcl.init]p11:
9883     //   If no initializer is specified for an object, the object is
9884     //   default-initialized; [...].
9885     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9886     InitializationKind Kind
9887       = InitializationKind::CreateDefault(Var->getLocation());
9888 
9889     InitializationSequence InitSeq(*this, Entity, Kind, None);
9890     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9891     if (Init.isInvalid())
9892       Var->setInvalidDecl();
9893     else if (Init.get()) {
9894       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9895       // This is important for template substitution.
9896       Var->setInitStyle(VarDecl::CallInit);
9897     }
9898 
9899     CheckCompleteVariableDeclaration(Var);
9900   }
9901 }
9902 
9903 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9904   VarDecl *VD = dyn_cast<VarDecl>(D);
9905   if (!VD) {
9906     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9907     D->setInvalidDecl();
9908     return;
9909   }
9910 
9911   VD->setCXXForRangeDecl(true);
9912 
9913   // for-range-declaration cannot be given a storage class specifier.
9914   int Error = -1;
9915   switch (VD->getStorageClass()) {
9916   case SC_None:
9917     break;
9918   case SC_Extern:
9919     Error = 0;
9920     break;
9921   case SC_Static:
9922     Error = 1;
9923     break;
9924   case SC_PrivateExtern:
9925     Error = 2;
9926     break;
9927   case SC_Auto:
9928     Error = 3;
9929     break;
9930   case SC_Register:
9931     Error = 4;
9932     break;
9933   }
9934   if (Error != -1) {
9935     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9936       << VD->getDeclName() << Error;
9937     D->setInvalidDecl();
9938   }
9939 }
9940 
9941 StmtResult
9942 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9943                                  IdentifierInfo *Ident,
9944                                  ParsedAttributes &Attrs,
9945                                  SourceLocation AttrEnd) {
9946   // C++1y [stmt.iter]p1:
9947   //   A range-based for statement of the form
9948   //      for ( for-range-identifier : for-range-initializer ) statement
9949   //   is equivalent to
9950   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9951   DeclSpec DS(Attrs.getPool().getFactory());
9952 
9953   const char *PrevSpec;
9954   unsigned DiagID;
9955   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9956                      getPrintingPolicy());
9957 
9958   Declarator D(DS, Declarator::ForContext);
9959   D.SetIdentifier(Ident, IdentLoc);
9960   D.takeAttributes(Attrs, AttrEnd);
9961 
9962   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9963   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9964                 EmptyAttrs, IdentLoc);
9965   Decl *Var = ActOnDeclarator(S, D);
9966   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9967   FinalizeDeclaration(Var);
9968   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9969                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9970 }
9971 
9972 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9973   if (var->isInvalidDecl()) return;
9974 
9975   // In Objective-C, don't allow jumps past the implicit initialization of a
9976   // local retaining variable.
9977   if (getLangOpts().ObjC1 &&
9978       var->hasLocalStorage()) {
9979     switch (var->getType().getObjCLifetime()) {
9980     case Qualifiers::OCL_None:
9981     case Qualifiers::OCL_ExplicitNone:
9982     case Qualifiers::OCL_Autoreleasing:
9983       break;
9984 
9985     case Qualifiers::OCL_Weak:
9986     case Qualifiers::OCL_Strong:
9987       getCurFunction()->setHasBranchProtectedScope();
9988       break;
9989     }
9990   }
9991 
9992   // Warn about externally-visible variables being defined without a
9993   // prior declaration.  We only want to do this for global
9994   // declarations, but we also specifically need to avoid doing it for
9995   // class members because the linkage of an anonymous class can
9996   // change if it's later given a typedef name.
9997   if (var->isThisDeclarationADefinition() &&
9998       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9999       var->isExternallyVisible() && var->hasLinkage() &&
10000       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10001                                   var->getLocation())) {
10002     // Find a previous declaration that's not a definition.
10003     VarDecl *prev = var->getPreviousDecl();
10004     while (prev && prev->isThisDeclarationADefinition())
10005       prev = prev->getPreviousDecl();
10006 
10007     if (!prev)
10008       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10009   }
10010 
10011   if (var->getTLSKind() == VarDecl::TLS_Static) {
10012     const Expr *Culprit;
10013     if (var->getType().isDestructedType()) {
10014       // GNU C++98 edits for __thread, [basic.start.term]p3:
10015       //   The type of an object with thread storage duration shall not
10016       //   have a non-trivial destructor.
10017       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10018       if (getLangOpts().CPlusPlus11)
10019         Diag(var->getLocation(), diag::note_use_thread_local);
10020     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10021                !var->getInit()->isConstantInitializer(
10022                    Context, var->getType()->isReferenceType(), &Culprit)) {
10023       // GNU C++98 edits for __thread, [basic.start.init]p4:
10024       //   An object of thread storage duration shall not require dynamic
10025       //   initialization.
10026       // FIXME: Need strict checking here.
10027       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10028         << Culprit->getSourceRange();
10029       if (getLangOpts().CPlusPlus11)
10030         Diag(var->getLocation(), diag::note_use_thread_local);
10031     }
10032 
10033   }
10034 
10035   // Apply section attributes and pragmas to global variables.
10036   bool GlobalStorage = var->hasGlobalStorage();
10037   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10038       ActiveTemplateInstantiations.empty()) {
10039     PragmaStack<StringLiteral *> *Stack = nullptr;
10040     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10041     if (var->getType().isConstQualified())
10042       Stack = &ConstSegStack;
10043     else if (!var->getInit()) {
10044       Stack = &BSSSegStack;
10045       SectionFlags |= ASTContext::PSF_Write;
10046     } else {
10047       Stack = &DataSegStack;
10048       SectionFlags |= ASTContext::PSF_Write;
10049     }
10050     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10051       var->addAttr(SectionAttr::CreateImplicit(
10052           Context, SectionAttr::Declspec_allocate,
10053           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10054     }
10055     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10056       if (UnifySection(SA->getName(), SectionFlags, var))
10057         var->dropAttr<SectionAttr>();
10058 
10059     // Apply the init_seg attribute if this has an initializer.  If the
10060     // initializer turns out to not be dynamic, we'll end up ignoring this
10061     // attribute.
10062     if (CurInitSeg && var->getInit())
10063       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10064                                                CurInitSegLoc));
10065   }
10066 
10067   // All the following checks are C++ only.
10068   if (!getLangOpts().CPlusPlus) return;
10069 
10070   QualType type = var->getType();
10071   if (type->isDependentType()) return;
10072 
10073   // __block variables might require us to capture a copy-initializer.
10074   if (var->hasAttr<BlocksAttr>()) {
10075     // It's currently invalid to ever have a __block variable with an
10076     // array type; should we diagnose that here?
10077 
10078     // Regardless, we don't want to ignore array nesting when
10079     // constructing this copy.
10080     if (type->isStructureOrClassType()) {
10081       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10082       SourceLocation poi = var->getLocation();
10083       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10084       ExprResult result
10085         = PerformMoveOrCopyInitialization(
10086             InitializedEntity::InitializeBlock(poi, type, false),
10087             var, var->getType(), varRef, /*AllowNRVO=*/true);
10088       if (!result.isInvalid()) {
10089         result = MaybeCreateExprWithCleanups(result);
10090         Expr *init = result.getAs<Expr>();
10091         Context.setBlockVarCopyInits(var, init);
10092       }
10093     }
10094   }
10095 
10096   Expr *Init = var->getInit();
10097   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10098   QualType baseType = Context.getBaseElementType(type);
10099 
10100   if (!var->getDeclContext()->isDependentContext() &&
10101       Init && !Init->isValueDependent()) {
10102     if (IsGlobal && !var->isConstexpr() &&
10103         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10104                                     var->getLocation())) {
10105       // Warn about globals which don't have a constant initializer.  Don't
10106       // warn about globals with a non-trivial destructor because we already
10107       // warned about them.
10108       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10109       if (!(RD && !RD->hasTrivialDestructor()) &&
10110           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10111         Diag(var->getLocation(), diag::warn_global_constructor)
10112           << Init->getSourceRange();
10113     }
10114 
10115     if (var->isConstexpr()) {
10116       SmallVector<PartialDiagnosticAt, 8> Notes;
10117       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10118         SourceLocation DiagLoc = var->getLocation();
10119         // If the note doesn't add any useful information other than a source
10120         // location, fold it into the primary diagnostic.
10121         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10122               diag::note_invalid_subexpr_in_const_expr) {
10123           DiagLoc = Notes[0].first;
10124           Notes.clear();
10125         }
10126         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10127           << var << Init->getSourceRange();
10128         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10129           Diag(Notes[I].first, Notes[I].second);
10130       }
10131     } else if (var->isUsableInConstantExpressions(Context)) {
10132       // Check whether the initializer of a const variable of integral or
10133       // enumeration type is an ICE now, since we can't tell whether it was
10134       // initialized by a constant expression if we check later.
10135       var->checkInitIsICE();
10136     }
10137   }
10138 
10139   // Require the destructor.
10140   if (const RecordType *recordType = baseType->getAs<RecordType>())
10141     FinalizeVarWithDestructor(var, recordType);
10142 }
10143 
10144 /// \brief Determines if a variable's alignment is dependent.
10145 static bool hasDependentAlignment(VarDecl *VD) {
10146   if (VD->getType()->isDependentType())
10147     return true;
10148   for (auto *I : VD->specific_attrs<AlignedAttr>())
10149     if (I->isAlignmentDependent())
10150       return true;
10151   return false;
10152 }
10153 
10154 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10155 /// any semantic actions necessary after any initializer has been attached.
10156 void
10157 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10158   // Note that we are no longer parsing the initializer for this declaration.
10159   ParsingInitForAutoVars.erase(ThisDecl);
10160 
10161   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10162   if (!VD)
10163     return;
10164 
10165   checkAttributesAfterMerging(*this, *VD);
10166 
10167   // Perform TLS alignment check here after attributes attached to the variable
10168   // which may affect the alignment have been processed. Only perform the check
10169   // if the target has a maximum TLS alignment (zero means no constraints).
10170   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10171     // Protect the check so that it's not performed on dependent types and
10172     // dependent alignments (we can't determine the alignment in that case).
10173     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10174       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10175       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10176         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10177           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10178           << (unsigned)MaxAlignChars.getQuantity();
10179       }
10180     }
10181   }
10182 
10183   // Static locals inherit dll attributes from their function.
10184   if (VD->isStaticLocal()) {
10185     if (FunctionDecl *FD =
10186             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10187       if (Attr *A = getDLLAttr(FD)) {
10188         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10189         NewAttr->setInherited(true);
10190         VD->addAttr(NewAttr);
10191       }
10192     }
10193   }
10194 
10195   // Grab the dllimport or dllexport attribute off of the VarDecl.
10196   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10197 
10198   // Imported static data members cannot be defined out-of-line.
10199   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10200     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10201         VD->isThisDeclarationADefinition()) {
10202       // We allow definitions of dllimport class template static data members
10203       // with a warning.
10204       CXXRecordDecl *Context =
10205         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10206       bool IsClassTemplateMember =
10207           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10208           Context->getDescribedClassTemplate();
10209 
10210       Diag(VD->getLocation(),
10211            IsClassTemplateMember
10212                ? diag::warn_attribute_dllimport_static_field_definition
10213                : diag::err_attribute_dllimport_static_field_definition);
10214       Diag(IA->getLocation(), diag::note_attribute);
10215       if (!IsClassTemplateMember)
10216         VD->setInvalidDecl();
10217     }
10218   }
10219 
10220   // dllimport/dllexport variables cannot be thread local, their TLS index
10221   // isn't exported with the variable.
10222   if (DLLAttr && VD->getTLSKind()) {
10223     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10224     if (F && getDLLAttr(F)) {
10225       assert(VD->isStaticLocal());
10226       // But if this is a static local in a dlimport/dllexport function, the
10227       // function will never be inlined, which means the var would never be
10228       // imported, so having it marked import/export is safe.
10229     } else {
10230       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10231                                                                     << DLLAttr;
10232       VD->setInvalidDecl();
10233     }
10234   }
10235 
10236   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10237     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10238       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10239       VD->dropAttr<UsedAttr>();
10240     }
10241   }
10242 
10243   const DeclContext *DC = VD->getDeclContext();
10244   // If there's a #pragma GCC visibility in scope, and this isn't a class
10245   // member, set the visibility of this variable.
10246   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10247     AddPushedVisibilityAttribute(VD);
10248 
10249   // FIXME: Warn on unused templates.
10250   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10251       !isa<VarTemplatePartialSpecializationDecl>(VD))
10252     MarkUnusedFileScopedDecl(VD);
10253 
10254   // Now we have parsed the initializer and can update the table of magic
10255   // tag values.
10256   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10257       !VD->getType()->isIntegralOrEnumerationType())
10258     return;
10259 
10260   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10261     const Expr *MagicValueExpr = VD->getInit();
10262     if (!MagicValueExpr) {
10263       continue;
10264     }
10265     llvm::APSInt MagicValueInt;
10266     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10267       Diag(I->getRange().getBegin(),
10268            diag::err_type_tag_for_datatype_not_ice)
10269         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10270       continue;
10271     }
10272     if (MagicValueInt.getActiveBits() > 64) {
10273       Diag(I->getRange().getBegin(),
10274            diag::err_type_tag_for_datatype_too_large)
10275         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10276       continue;
10277     }
10278     uint64_t MagicValue = MagicValueInt.getZExtValue();
10279     RegisterTypeTagForDatatype(I->getArgumentKind(),
10280                                MagicValue,
10281                                I->getMatchingCType(),
10282                                I->getLayoutCompatible(),
10283                                I->getMustBeNull());
10284   }
10285 }
10286 
10287 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10288                                                    ArrayRef<Decl *> Group) {
10289   SmallVector<Decl*, 8> Decls;
10290 
10291   if (DS.isTypeSpecOwned())
10292     Decls.push_back(DS.getRepAsDecl());
10293 
10294   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10295   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10296     if (Decl *D = Group[i]) {
10297       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10298         if (!FirstDeclaratorInGroup)
10299           FirstDeclaratorInGroup = DD;
10300       Decls.push_back(D);
10301     }
10302 
10303   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10304     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10305       handleTagNumbering(Tag, S);
10306       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10307           getLangOpts().CPlusPlus)
10308         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10309     }
10310   }
10311 
10312   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10313 }
10314 
10315 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10316 /// group, performing any necessary semantic checking.
10317 Sema::DeclGroupPtrTy
10318 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10319                            bool TypeMayContainAuto) {
10320   // C++0x [dcl.spec.auto]p7:
10321   //   If the type deduced for the template parameter U is not the same in each
10322   //   deduction, the program is ill-formed.
10323   // FIXME: When initializer-list support is added, a distinction is needed
10324   // between the deduced type U and the deduced type which 'auto' stands for.
10325   //   auto a = 0, b = { 1, 2, 3 };
10326   // is legal because the deduced type U is 'int' in both cases.
10327   if (TypeMayContainAuto && Group.size() > 1) {
10328     QualType Deduced;
10329     CanQualType DeducedCanon;
10330     VarDecl *DeducedDecl = nullptr;
10331     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10332       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10333         AutoType *AT = D->getType()->getContainedAutoType();
10334         // Don't reissue diagnostics when instantiating a template.
10335         if (AT && D->isInvalidDecl())
10336           break;
10337         QualType U = AT ? AT->getDeducedType() : QualType();
10338         if (!U.isNull()) {
10339           CanQualType UCanon = Context.getCanonicalType(U);
10340           if (Deduced.isNull()) {
10341             Deduced = U;
10342             DeducedCanon = UCanon;
10343             DeducedDecl = D;
10344           } else if (DeducedCanon != UCanon) {
10345             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10346                  diag::err_auto_different_deductions)
10347               << (unsigned)AT->getKeyword()
10348               << Deduced << DeducedDecl->getDeclName()
10349               << U << D->getDeclName()
10350               << DeducedDecl->getInit()->getSourceRange()
10351               << D->getInit()->getSourceRange();
10352             D->setInvalidDecl();
10353             break;
10354           }
10355         }
10356       }
10357     }
10358   }
10359 
10360   ActOnDocumentableDecls(Group);
10361 
10362   return DeclGroupPtrTy::make(
10363       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10364 }
10365 
10366 void Sema::ActOnDocumentableDecl(Decl *D) {
10367   ActOnDocumentableDecls(D);
10368 }
10369 
10370 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10371   // Don't parse the comment if Doxygen diagnostics are ignored.
10372   if (Group.empty() || !Group[0])
10373     return;
10374 
10375   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10376                       Group[0]->getLocation()) &&
10377       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10378                       Group[0]->getLocation()))
10379     return;
10380 
10381   if (Group.size() >= 2) {
10382     // This is a decl group.  Normally it will contain only declarations
10383     // produced from declarator list.  But in case we have any definitions or
10384     // additional declaration references:
10385     //   'typedef struct S {} S;'
10386     //   'typedef struct S *S;'
10387     //   'struct S *pS;'
10388     // FinalizeDeclaratorGroup adds these as separate declarations.
10389     Decl *MaybeTagDecl = Group[0];
10390     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10391       Group = Group.slice(1);
10392     }
10393   }
10394 
10395   // See if there are any new comments that are not attached to a decl.
10396   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10397   if (!Comments.empty() &&
10398       !Comments.back()->isAttached()) {
10399     // There is at least one comment that not attached to a decl.
10400     // Maybe it should be attached to one of these decls?
10401     //
10402     // Note that this way we pick up not only comments that precede the
10403     // declaration, but also comments that *follow* the declaration -- thanks to
10404     // the lookahead in the lexer: we've consumed the semicolon and looked
10405     // ahead through comments.
10406     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10407       Context.getCommentForDecl(Group[i], &PP);
10408   }
10409 }
10410 
10411 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10412 /// to introduce parameters into function prototype scope.
10413 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10414   const DeclSpec &DS = D.getDeclSpec();
10415 
10416   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10417 
10418   // C++03 [dcl.stc]p2 also permits 'auto'.
10419   StorageClass SC = SC_None;
10420   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10421     SC = SC_Register;
10422   } else if (getLangOpts().CPlusPlus &&
10423              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10424     SC = SC_Auto;
10425   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10426     Diag(DS.getStorageClassSpecLoc(),
10427          diag::err_invalid_storage_class_in_func_decl);
10428     D.getMutableDeclSpec().ClearStorageClassSpecs();
10429   }
10430 
10431   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10432     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10433       << DeclSpec::getSpecifierName(TSCS);
10434   if (DS.isConstexprSpecified())
10435     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10436       << 0;
10437   if (DS.isConceptSpecified())
10438     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10439 
10440   DiagnoseFunctionSpecifiers(DS);
10441 
10442   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10443   QualType parmDeclType = TInfo->getType();
10444 
10445   if (getLangOpts().CPlusPlus) {
10446     // Check that there are no default arguments inside the type of this
10447     // parameter.
10448     CheckExtraCXXDefaultArguments(D);
10449 
10450     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10451     if (D.getCXXScopeSpec().isSet()) {
10452       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10453         << D.getCXXScopeSpec().getRange();
10454       D.getCXXScopeSpec().clear();
10455     }
10456   }
10457 
10458   // Ensure we have a valid name
10459   IdentifierInfo *II = nullptr;
10460   if (D.hasName()) {
10461     II = D.getIdentifier();
10462     if (!II) {
10463       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10464         << GetNameForDeclarator(D).getName();
10465       D.setInvalidType(true);
10466     }
10467   }
10468 
10469   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10470   if (II) {
10471     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10472                    ForRedeclaration);
10473     LookupName(R, S);
10474     if (R.isSingleResult()) {
10475       NamedDecl *PrevDecl = R.getFoundDecl();
10476       if (PrevDecl->isTemplateParameter()) {
10477         // Maybe we will complain about the shadowed template parameter.
10478         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10479         // Just pretend that we didn't see the previous declaration.
10480         PrevDecl = nullptr;
10481       } else if (S->isDeclScope(PrevDecl)) {
10482         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10483         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10484 
10485         // Recover by removing the name
10486         II = nullptr;
10487         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10488         D.setInvalidType(true);
10489       }
10490     }
10491   }
10492 
10493   // Temporarily put parameter variables in the translation unit, not
10494   // the enclosing context.  This prevents them from accidentally
10495   // looking like class members in C++.
10496   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10497                                     D.getLocStart(),
10498                                     D.getIdentifierLoc(), II,
10499                                     parmDeclType, TInfo,
10500                                     SC);
10501 
10502   if (D.isInvalidType())
10503     New->setInvalidDecl();
10504 
10505   assert(S->isFunctionPrototypeScope());
10506   assert(S->getFunctionPrototypeDepth() >= 1);
10507   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10508                     S->getNextFunctionPrototypeIndex());
10509 
10510   // Add the parameter declaration into this scope.
10511   S->AddDecl(New);
10512   if (II)
10513     IdResolver.AddDecl(New);
10514 
10515   ProcessDeclAttributes(S, New, D);
10516 
10517   if (D.getDeclSpec().isModulePrivateSpecified())
10518     Diag(New->getLocation(), diag::err_module_private_local)
10519       << 1 << New->getDeclName()
10520       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10521       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10522 
10523   if (New->hasAttr<BlocksAttr>()) {
10524     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10525   }
10526   return New;
10527 }
10528 
10529 /// \brief Synthesizes a variable for a parameter arising from a
10530 /// typedef.
10531 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10532                                               SourceLocation Loc,
10533                                               QualType T) {
10534   /* FIXME: setting StartLoc == Loc.
10535      Would it be worth to modify callers so as to provide proper source
10536      location for the unnamed parameters, embedding the parameter's type? */
10537   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10538                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10539                                            SC_None, nullptr);
10540   Param->setImplicit();
10541   return Param;
10542 }
10543 
10544 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10545                                     ParmVarDecl * const *ParamEnd) {
10546   // Don't diagnose unused-parameter errors in template instantiations; we
10547   // will already have done so in the template itself.
10548   if (!ActiveTemplateInstantiations.empty())
10549     return;
10550 
10551   for (; Param != ParamEnd; ++Param) {
10552     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10553         !(*Param)->hasAttr<UnusedAttr>()) {
10554       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10555         << (*Param)->getDeclName();
10556     }
10557   }
10558 }
10559 
10560 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10561                                                   ParmVarDecl * const *ParamEnd,
10562                                                   QualType ReturnTy,
10563                                                   NamedDecl *D) {
10564   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10565     return;
10566 
10567   // Warn if the return value is pass-by-value and larger than the specified
10568   // threshold.
10569   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10570     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10571     if (Size > LangOpts.NumLargeByValueCopy)
10572       Diag(D->getLocation(), diag::warn_return_value_size)
10573           << D->getDeclName() << Size;
10574   }
10575 
10576   // Warn if any parameter is pass-by-value and larger than the specified
10577   // threshold.
10578   for (; Param != ParamEnd; ++Param) {
10579     QualType T = (*Param)->getType();
10580     if (T->isDependentType() || !T.isPODType(Context))
10581       continue;
10582     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10583     if (Size > LangOpts.NumLargeByValueCopy)
10584       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10585           << (*Param)->getDeclName() << Size;
10586   }
10587 }
10588 
10589 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10590                                   SourceLocation NameLoc, IdentifierInfo *Name,
10591                                   QualType T, TypeSourceInfo *TSInfo,
10592                                   StorageClass SC) {
10593   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10594   if (getLangOpts().ObjCAutoRefCount &&
10595       T.getObjCLifetime() == Qualifiers::OCL_None &&
10596       T->isObjCLifetimeType()) {
10597 
10598     Qualifiers::ObjCLifetime lifetime;
10599 
10600     // Special cases for arrays:
10601     //   - if it's const, use __unsafe_unretained
10602     //   - otherwise, it's an error
10603     if (T->isArrayType()) {
10604       if (!T.isConstQualified()) {
10605         DelayedDiagnostics.add(
10606             sema::DelayedDiagnostic::makeForbiddenType(
10607             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10608       }
10609       lifetime = Qualifiers::OCL_ExplicitNone;
10610     } else {
10611       lifetime = T->getObjCARCImplicitLifetime();
10612     }
10613     T = Context.getLifetimeQualifiedType(T, lifetime);
10614   }
10615 
10616   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10617                                          Context.getAdjustedParameterType(T),
10618                                          TSInfo, SC, nullptr);
10619 
10620   // Parameters can not be abstract class types.
10621   // For record types, this is done by the AbstractClassUsageDiagnoser once
10622   // the class has been completely parsed.
10623   if (!CurContext->isRecord() &&
10624       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10625                              AbstractParamType))
10626     New->setInvalidDecl();
10627 
10628   // Parameter declarators cannot be interface types. All ObjC objects are
10629   // passed by reference.
10630   if (T->isObjCObjectType()) {
10631     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10632     Diag(NameLoc,
10633          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10634       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10635     T = Context.getObjCObjectPointerType(T);
10636     New->setType(T);
10637   }
10638 
10639   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10640   // duration shall not be qualified by an address-space qualifier."
10641   // Since all parameters have automatic store duration, they can not have
10642   // an address space.
10643   if (T.getAddressSpace() != 0) {
10644     // OpenCL allows function arguments declared to be an array of a type
10645     // to be qualified with an address space.
10646     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10647       Diag(NameLoc, diag::err_arg_with_address_space);
10648       New->setInvalidDecl();
10649     }
10650   }
10651 
10652   return New;
10653 }
10654 
10655 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10656                                            SourceLocation LocAfterDecls) {
10657   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10658 
10659   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10660   // for a K&R function.
10661   if (!FTI.hasPrototype) {
10662     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10663       --i;
10664       if (FTI.Params[i].Param == nullptr) {
10665         SmallString<256> Code;
10666         llvm::raw_svector_ostream(Code)
10667             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10668         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10669             << FTI.Params[i].Ident
10670             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10671 
10672         // Implicitly declare the argument as type 'int' for lack of a better
10673         // type.
10674         AttributeFactory attrs;
10675         DeclSpec DS(attrs);
10676         const char* PrevSpec; // unused
10677         unsigned DiagID; // unused
10678         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10679                            DiagID, Context.getPrintingPolicy());
10680         // Use the identifier location for the type source range.
10681         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10682         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10683         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10684         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10685         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10686       }
10687     }
10688   }
10689 }
10690 
10691 Decl *
10692 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10693                               MultiTemplateParamsArg TemplateParameterLists,
10694                               SkipBodyInfo *SkipBody) {
10695   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10696   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10697   Scope *ParentScope = FnBodyScope->getParent();
10698 
10699   D.setFunctionDefinitionKind(FDK_Definition);
10700   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10701   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10702 }
10703 
10704 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10705   Consumer.HandleInlineMethodDefinition(D);
10706 }
10707 
10708 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10709                              const FunctionDecl*& PossibleZeroParamPrototype) {
10710   // Don't warn about invalid declarations.
10711   if (FD->isInvalidDecl())
10712     return false;
10713 
10714   // Or declarations that aren't global.
10715   if (!FD->isGlobal())
10716     return false;
10717 
10718   // Don't warn about C++ member functions.
10719   if (isa<CXXMethodDecl>(FD))
10720     return false;
10721 
10722   // Don't warn about 'main'.
10723   if (FD->isMain())
10724     return false;
10725 
10726   // Don't warn about inline functions.
10727   if (FD->isInlined())
10728     return false;
10729 
10730   // Don't warn about function templates.
10731   if (FD->getDescribedFunctionTemplate())
10732     return false;
10733 
10734   // Don't warn about function template specializations.
10735   if (FD->isFunctionTemplateSpecialization())
10736     return false;
10737 
10738   // Don't warn for OpenCL kernels.
10739   if (FD->hasAttr<OpenCLKernelAttr>())
10740     return false;
10741 
10742   // Don't warn on explicitly deleted functions.
10743   if (FD->isDeleted())
10744     return false;
10745 
10746   bool MissingPrototype = true;
10747   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10748        Prev; Prev = Prev->getPreviousDecl()) {
10749     // Ignore any declarations that occur in function or method
10750     // scope, because they aren't visible from the header.
10751     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10752       continue;
10753 
10754     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10755     if (FD->getNumParams() == 0)
10756       PossibleZeroParamPrototype = Prev;
10757     break;
10758   }
10759 
10760   return MissingPrototype;
10761 }
10762 
10763 void
10764 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10765                                    const FunctionDecl *EffectiveDefinition,
10766                                    SkipBodyInfo *SkipBody) {
10767   // Don't complain if we're in GNU89 mode and the previous definition
10768   // was an extern inline function.
10769   const FunctionDecl *Definition = EffectiveDefinition;
10770   if (!Definition)
10771     if (!FD->isDefined(Definition))
10772       return;
10773 
10774   if (canRedefineFunction(Definition, getLangOpts()))
10775     return;
10776 
10777   // If we don't have a visible definition of the function, and it's inline or
10778   // a template, skip the new definition.
10779   if (SkipBody && !hasVisibleDefinition(Definition) &&
10780       (Definition->getFormalLinkage() == InternalLinkage ||
10781        Definition->isInlined() ||
10782        Definition->getDescribedFunctionTemplate() ||
10783        Definition->getNumTemplateParameterLists())) {
10784     SkipBody->ShouldSkip = true;
10785     if (auto *TD = Definition->getDescribedFunctionTemplate())
10786       makeMergedDefinitionVisible(TD, FD->getLocation());
10787     else
10788       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10789                                   FD->getLocation());
10790     return;
10791   }
10792 
10793   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10794       Definition->getStorageClass() == SC_Extern)
10795     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10796         << FD->getDeclName() << getLangOpts().CPlusPlus;
10797   else
10798     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10799 
10800   Diag(Definition->getLocation(), diag::note_previous_definition);
10801   FD->setInvalidDecl();
10802 }
10803 
10804 
10805 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10806                                    Sema &S) {
10807   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10808 
10809   LambdaScopeInfo *LSI = S.PushLambdaScope();
10810   LSI->CallOperator = CallOperator;
10811   LSI->Lambda = LambdaClass;
10812   LSI->ReturnType = CallOperator->getReturnType();
10813   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10814 
10815   if (LCD == LCD_None)
10816     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10817   else if (LCD == LCD_ByCopy)
10818     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10819   else if (LCD == LCD_ByRef)
10820     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10821   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10822 
10823   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10824   LSI->Mutable = !CallOperator->isConst();
10825 
10826   // Add the captures to the LSI so they can be noted as already
10827   // captured within tryCaptureVar.
10828   auto I = LambdaClass->field_begin();
10829   for (const auto &C : LambdaClass->captures()) {
10830     if (C.capturesVariable()) {
10831       VarDecl *VD = C.getCapturedVar();
10832       if (VD->isInitCapture())
10833         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10834       QualType CaptureType = VD->getType();
10835       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10836       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10837           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10838           /*EllipsisLoc*/C.isPackExpansion()
10839                          ? C.getEllipsisLoc() : SourceLocation(),
10840           CaptureType, /*Expr*/ nullptr);
10841 
10842     } else if (C.capturesThis()) {
10843       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10844                               S.getCurrentThisType(), /*Expr*/ nullptr);
10845     } else {
10846       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10847     }
10848     ++I;
10849   }
10850 }
10851 
10852 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10853                                     SkipBodyInfo *SkipBody) {
10854   // Clear the last template instantiation error context.
10855   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10856 
10857   if (!D)
10858     return D;
10859   FunctionDecl *FD = nullptr;
10860 
10861   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10862     FD = FunTmpl->getTemplatedDecl();
10863   else
10864     FD = cast<FunctionDecl>(D);
10865 
10866   // See if this is a redefinition.
10867   if (!FD->isLateTemplateParsed()) {
10868     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10869 
10870     // If we're skipping the body, we're done. Don't enter the scope.
10871     if (SkipBody && SkipBody->ShouldSkip)
10872       return D;
10873   }
10874 
10875   // If we are instantiating a generic lambda call operator, push
10876   // a LambdaScopeInfo onto the function stack.  But use the information
10877   // that's already been calculated (ActOnLambdaExpr) to prime the current
10878   // LambdaScopeInfo.
10879   // When the template operator is being specialized, the LambdaScopeInfo,
10880   // has to be properly restored so that tryCaptureVariable doesn't try
10881   // and capture any new variables. In addition when calculating potential
10882   // captures during transformation of nested lambdas, it is necessary to
10883   // have the LSI properly restored.
10884   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10885     assert(ActiveTemplateInstantiations.size() &&
10886       "There should be an active template instantiation on the stack "
10887       "when instantiating a generic lambda!");
10888     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10889   }
10890   else
10891     // Enter a new function scope
10892     PushFunctionScope();
10893 
10894   // Builtin functions cannot be defined.
10895   if (unsigned BuiltinID = FD->getBuiltinID()) {
10896     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10897         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10898       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10899       FD->setInvalidDecl();
10900     }
10901   }
10902 
10903   // The return type of a function definition must be complete
10904   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10905   QualType ResultType = FD->getReturnType();
10906   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10907       !FD->isInvalidDecl() &&
10908       RequireCompleteType(FD->getLocation(), ResultType,
10909                           diag::err_func_def_incomplete_result))
10910     FD->setInvalidDecl();
10911 
10912   if (FnBodyScope)
10913     PushDeclContext(FnBodyScope, FD);
10914 
10915   // Check the validity of our function parameters
10916   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10917                            /*CheckParameterNames=*/true);
10918 
10919   // Introduce our parameters into the function scope
10920   for (auto Param : FD->params()) {
10921     Param->setOwningFunction(FD);
10922 
10923     // If this has an identifier, add it to the scope stack.
10924     if (Param->getIdentifier() && FnBodyScope) {
10925       CheckShadow(FnBodyScope, Param);
10926 
10927       PushOnScopeChains(Param, FnBodyScope);
10928     }
10929   }
10930 
10931   // If we had any tags defined in the function prototype,
10932   // introduce them into the function scope.
10933   if (FnBodyScope) {
10934     for (ArrayRef<NamedDecl *>::iterator
10935              I = FD->getDeclsInPrototypeScope().begin(),
10936              E = FD->getDeclsInPrototypeScope().end();
10937          I != E; ++I) {
10938       NamedDecl *D = *I;
10939 
10940       // Some of these decls (like enums) may have been pinned to the
10941       // translation unit for lack of a real context earlier. If so, remove
10942       // from the translation unit and reattach to the current context.
10943       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10944         // Is the decl actually in the context?
10945         if (Context.getTranslationUnitDecl()->containsDecl(D))
10946           Context.getTranslationUnitDecl()->removeDecl(D);
10947         // Either way, reassign the lexical decl context to our FunctionDecl.
10948         D->setLexicalDeclContext(CurContext);
10949       }
10950 
10951       // If the decl has a non-null name, make accessible in the current scope.
10952       if (!D->getName().empty())
10953         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10954 
10955       // Similarly, dive into enums and fish their constants out, making them
10956       // accessible in this scope.
10957       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10958         for (auto *EI : ED->enumerators())
10959           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10960       }
10961     }
10962   }
10963 
10964   // Ensure that the function's exception specification is instantiated.
10965   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10966     ResolveExceptionSpec(D->getLocation(), FPT);
10967 
10968   // dllimport cannot be applied to non-inline function definitions.
10969   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10970       !FD->isTemplateInstantiation()) {
10971     assert(!FD->hasAttr<DLLExportAttr>());
10972     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10973     FD->setInvalidDecl();
10974     return D;
10975   }
10976   // We want to attach documentation to original Decl (which might be
10977   // a function template).
10978   ActOnDocumentableDecl(D);
10979   if (getCurLexicalContext()->isObjCContainer() &&
10980       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10981       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10982     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10983 
10984   return D;
10985 }
10986 
10987 /// \brief Given the set of return statements within a function body,
10988 /// compute the variables that are subject to the named return value
10989 /// optimization.
10990 ///
10991 /// Each of the variables that is subject to the named return value
10992 /// optimization will be marked as NRVO variables in the AST, and any
10993 /// return statement that has a marked NRVO variable as its NRVO candidate can
10994 /// use the named return value optimization.
10995 ///
10996 /// This function applies a very simplistic algorithm for NRVO: if every return
10997 /// statement in the scope of a variable has the same NRVO candidate, that
10998 /// candidate is an NRVO variable.
10999 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11000   ReturnStmt **Returns = Scope->Returns.data();
11001 
11002   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11003     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11004       if (!NRVOCandidate->isNRVOVariable())
11005         Returns[I]->setNRVOCandidate(nullptr);
11006     }
11007   }
11008 }
11009 
11010 bool Sema::canDelayFunctionBody(const Declarator &D) {
11011   // We can't delay parsing the body of a constexpr function template (yet).
11012   if (D.getDeclSpec().isConstexprSpecified())
11013     return false;
11014 
11015   // We can't delay parsing the body of a function template with a deduced
11016   // return type (yet).
11017   if (D.getDeclSpec().containsPlaceholderType()) {
11018     // If the placeholder introduces a non-deduced trailing return type,
11019     // we can still delay parsing it.
11020     if (D.getNumTypeObjects()) {
11021       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11022       if (Outer.Kind == DeclaratorChunk::Function &&
11023           Outer.Fun.hasTrailingReturnType()) {
11024         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11025         return Ty.isNull() || !Ty->isUndeducedType();
11026       }
11027     }
11028     return false;
11029   }
11030 
11031   return true;
11032 }
11033 
11034 bool Sema::canSkipFunctionBody(Decl *D) {
11035   // We cannot skip the body of a function (or function template) which is
11036   // constexpr, since we may need to evaluate its body in order to parse the
11037   // rest of the file.
11038   // We cannot skip the body of a function with an undeduced return type,
11039   // because any callers of that function need to know the type.
11040   if (const FunctionDecl *FD = D->getAsFunction())
11041     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11042       return false;
11043   return Consumer.shouldSkipFunctionBody(D);
11044 }
11045 
11046 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11047   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11048     FD->setHasSkippedBody();
11049   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11050     MD->setHasSkippedBody();
11051   return ActOnFinishFunctionBody(Decl, nullptr);
11052 }
11053 
11054 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11055   return ActOnFinishFunctionBody(D, BodyArg, false);
11056 }
11057 
11058 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11059                                     bool IsInstantiation) {
11060   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11061 
11062   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11063   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11064 
11065   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11066     CheckCompletedCoroutineBody(FD, Body);
11067 
11068   if (FD) {
11069     FD->setBody(Body);
11070 
11071     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11072         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11073       // If the function has a deduced result type but contains no 'return'
11074       // statements, the result type as written must be exactly 'auto', and
11075       // the deduced result type is 'void'.
11076       if (!FD->getReturnType()->getAs<AutoType>()) {
11077         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11078             << FD->getReturnType();
11079         FD->setInvalidDecl();
11080       } else {
11081         // Substitute 'void' for the 'auto' in the type.
11082         TypeLoc ResultType = getReturnTypeLoc(FD);
11083         Context.adjustDeducedFunctionResultType(
11084             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11085       }
11086     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11087       auto *LSI = getCurLambda();
11088       if (LSI->HasImplicitReturnType) {
11089         deduceClosureReturnType(*LSI);
11090 
11091         // C++11 [expr.prim.lambda]p4:
11092         //   [...] if there are no return statements in the compound-statement
11093         //   [the deduced type is] the type void
11094         QualType RetType =
11095             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11096 
11097         // Update the return type to the deduced type.
11098         const FunctionProtoType *Proto =
11099             FD->getType()->getAs<FunctionProtoType>();
11100         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11101                                             Proto->getExtProtoInfo()));
11102       }
11103     }
11104 
11105     // The only way to be included in UndefinedButUsed is if there is an
11106     // ODR use before the definition. Avoid the expensive map lookup if this
11107     // is the first declaration.
11108     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11109       if (!FD->isExternallyVisible())
11110         UndefinedButUsed.erase(FD);
11111       else if (FD->isInlined() &&
11112                !LangOpts.GNUInline &&
11113                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11114         UndefinedButUsed.erase(FD);
11115     }
11116 
11117     // If the function implicitly returns zero (like 'main') or is naked,
11118     // don't complain about missing return statements.
11119     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11120       WP.disableCheckFallThrough();
11121 
11122     // MSVC permits the use of pure specifier (=0) on function definition,
11123     // defined at class scope, warn about this non-standard construct.
11124     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11125       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11126 
11127     if (!FD->isInvalidDecl()) {
11128       // Don't diagnose unused parameters of defaulted or deleted functions.
11129       if (!FD->isDeleted() && !FD->isDefaulted())
11130         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11131       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11132                                              FD->getReturnType(), FD);
11133 
11134       // If this is a structor, we need a vtable.
11135       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11136         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11137       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11138         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11139 
11140       // Try to apply the named return value optimization. We have to check
11141       // if we can do this here because lambdas keep return statements around
11142       // to deduce an implicit return type.
11143       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11144           !FD->isDependentContext())
11145         computeNRVO(Body, getCurFunction());
11146     }
11147 
11148     // GNU warning -Wmissing-prototypes:
11149     //   Warn if a global function is defined without a previous
11150     //   prototype declaration. This warning is issued even if the
11151     //   definition itself provides a prototype. The aim is to detect
11152     //   global functions that fail to be declared in header files.
11153     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11154     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11155       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11156 
11157       if (PossibleZeroParamPrototype) {
11158         // We found a declaration that is not a prototype,
11159         // but that could be a zero-parameter prototype
11160         if (TypeSourceInfo *TI =
11161                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11162           TypeLoc TL = TI->getTypeLoc();
11163           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11164             Diag(PossibleZeroParamPrototype->getLocation(),
11165                  diag::note_declaration_not_a_prototype)
11166                 << PossibleZeroParamPrototype
11167                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11168         }
11169       }
11170     }
11171 
11172     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11173       const CXXMethodDecl *KeyFunction;
11174       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11175           MD->isVirtual() &&
11176           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11177           MD == KeyFunction->getCanonicalDecl()) {
11178         // Update the key-function state if necessary for this ABI.
11179         if (FD->isInlined() &&
11180             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11181           Context.setNonKeyFunction(MD);
11182 
11183           // If the newly-chosen key function is already defined, then we
11184           // need to mark the vtable as used retroactively.
11185           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11186           const FunctionDecl *Definition;
11187           if (KeyFunction && KeyFunction->isDefined(Definition))
11188             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11189         } else {
11190           // We just defined they key function; mark the vtable as used.
11191           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11192         }
11193       }
11194     }
11195 
11196     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11197            "Function parsing confused");
11198   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11199     assert(MD == getCurMethodDecl() && "Method parsing confused");
11200     MD->setBody(Body);
11201     if (!MD->isInvalidDecl()) {
11202       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11203       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11204                                              MD->getReturnType(), MD);
11205 
11206       if (Body)
11207         computeNRVO(Body, getCurFunction());
11208     }
11209     if (getCurFunction()->ObjCShouldCallSuper) {
11210       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11211         << MD->getSelector().getAsString();
11212       getCurFunction()->ObjCShouldCallSuper = false;
11213     }
11214     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11215       const ObjCMethodDecl *InitMethod = nullptr;
11216       bool isDesignated =
11217           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11218       assert(isDesignated && InitMethod);
11219       (void)isDesignated;
11220 
11221       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11222         auto IFace = MD->getClassInterface();
11223         if (!IFace)
11224           return false;
11225         auto SuperD = IFace->getSuperClass();
11226         if (!SuperD)
11227           return false;
11228         return SuperD->getIdentifier() ==
11229             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11230       };
11231       // Don't issue this warning for unavailable inits or direct subclasses
11232       // of NSObject.
11233       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11234         Diag(MD->getLocation(),
11235              diag::warn_objc_designated_init_missing_super_call);
11236         Diag(InitMethod->getLocation(),
11237              diag::note_objc_designated_init_marked_here);
11238       }
11239       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11240     }
11241     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11242       // Don't issue this warning for unavaialable inits.
11243       if (!MD->isUnavailable())
11244         Diag(MD->getLocation(),
11245              diag::warn_objc_secondary_init_missing_init_call);
11246       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11247     }
11248   } else {
11249     return nullptr;
11250   }
11251 
11252   assert(!getCurFunction()->ObjCShouldCallSuper &&
11253          "This should only be set for ObjC methods, which should have been "
11254          "handled in the block above.");
11255 
11256   // Verify and clean out per-function state.
11257   if (Body && (!FD || !FD->isDefaulted())) {
11258     // C++ constructors that have function-try-blocks can't have return
11259     // statements in the handlers of that block. (C++ [except.handle]p14)
11260     // Verify this.
11261     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11262       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11263 
11264     // Verify that gotos and switch cases don't jump into scopes illegally.
11265     if (getCurFunction()->NeedsScopeChecking() &&
11266         !PP.isCodeCompletionEnabled())
11267       DiagnoseInvalidJumps(Body);
11268 
11269     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11270       if (!Destructor->getParent()->isDependentType())
11271         CheckDestructor(Destructor);
11272 
11273       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11274                                              Destructor->getParent());
11275     }
11276 
11277     // If any errors have occurred, clear out any temporaries that may have
11278     // been leftover. This ensures that these temporaries won't be picked up for
11279     // deletion in some later function.
11280     if (getDiagnostics().hasErrorOccurred() ||
11281         getDiagnostics().getSuppressAllDiagnostics()) {
11282       DiscardCleanupsInEvaluationContext();
11283     }
11284     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11285         !isa<FunctionTemplateDecl>(dcl)) {
11286       // Since the body is valid, issue any analysis-based warnings that are
11287       // enabled.
11288       ActivePolicy = &WP;
11289     }
11290 
11291     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11292         (!CheckConstexprFunctionDecl(FD) ||
11293          !CheckConstexprFunctionBody(FD, Body)))
11294       FD->setInvalidDecl();
11295 
11296     if (FD && FD->hasAttr<NakedAttr>()) {
11297       for (const Stmt *S : Body->children()) {
11298         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11299           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11300           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11301           FD->setInvalidDecl();
11302           break;
11303         }
11304       }
11305     }
11306 
11307     assert(ExprCleanupObjects.size() ==
11308                ExprEvalContexts.back().NumCleanupObjects &&
11309            "Leftover temporaries in function");
11310     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11311     assert(MaybeODRUseExprs.empty() &&
11312            "Leftover expressions for odr-use checking");
11313   }
11314 
11315   if (!IsInstantiation)
11316     PopDeclContext();
11317 
11318   PopFunctionScopeInfo(ActivePolicy, dcl);
11319   // If any errors have occurred, clear out any temporaries that may have
11320   // been leftover. This ensures that these temporaries won't be picked up for
11321   // deletion in some later function.
11322   if (getDiagnostics().hasErrorOccurred()) {
11323     DiscardCleanupsInEvaluationContext();
11324   }
11325 
11326   return dcl;
11327 }
11328 
11329 
11330 /// When we finish delayed parsing of an attribute, we must attach it to the
11331 /// relevant Decl.
11332 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11333                                        ParsedAttributes &Attrs) {
11334   // Always attach attributes to the underlying decl.
11335   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11336     D = TD->getTemplatedDecl();
11337   ProcessDeclAttributeList(S, D, Attrs.getList());
11338 
11339   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11340     if (Method->isStatic())
11341       checkThisInStaticMemberFunctionAttributes(Method);
11342 }
11343 
11344 
11345 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11346 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11347 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11348                                           IdentifierInfo &II, Scope *S) {
11349   // Before we produce a declaration for an implicitly defined
11350   // function, see whether there was a locally-scoped declaration of
11351   // this name as a function or variable. If so, use that
11352   // (non-visible) declaration, and complain about it.
11353   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11354     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11355     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11356     return ExternCPrev;
11357   }
11358 
11359   // Extension in C99.  Legal in C90, but warn about it.
11360   unsigned diag_id;
11361   if (II.getName().startswith("__builtin_"))
11362     diag_id = diag::warn_builtin_unknown;
11363   else if (getLangOpts().C99)
11364     diag_id = diag::ext_implicit_function_decl;
11365   else
11366     diag_id = diag::warn_implicit_function_decl;
11367   Diag(Loc, diag_id) << &II;
11368 
11369   // Because typo correction is expensive, only do it if the implicit
11370   // function declaration is going to be treated as an error.
11371   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11372     TypoCorrection Corrected;
11373     if (S &&
11374         (Corrected = CorrectTypo(
11375              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11376              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11377       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11378                    /*ErrorRecovery*/false);
11379   }
11380 
11381   // Set a Declarator for the implicit definition: int foo();
11382   const char *Dummy;
11383   AttributeFactory attrFactory;
11384   DeclSpec DS(attrFactory);
11385   unsigned DiagID;
11386   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11387                                   Context.getPrintingPolicy());
11388   (void)Error; // Silence warning.
11389   assert(!Error && "Error setting up implicit decl!");
11390   SourceLocation NoLoc;
11391   Declarator D(DS, Declarator::BlockContext);
11392   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11393                                              /*IsAmbiguous=*/false,
11394                                              /*LParenLoc=*/NoLoc,
11395                                              /*Params=*/nullptr,
11396                                              /*NumParams=*/0,
11397                                              /*EllipsisLoc=*/NoLoc,
11398                                              /*RParenLoc=*/NoLoc,
11399                                              /*TypeQuals=*/0,
11400                                              /*RefQualifierIsLvalueRef=*/true,
11401                                              /*RefQualifierLoc=*/NoLoc,
11402                                              /*ConstQualifierLoc=*/NoLoc,
11403                                              /*VolatileQualifierLoc=*/NoLoc,
11404                                              /*RestrictQualifierLoc=*/NoLoc,
11405                                              /*MutableLoc=*/NoLoc,
11406                                              EST_None,
11407                                              /*ESpecRange=*/SourceRange(),
11408                                              /*Exceptions=*/nullptr,
11409                                              /*ExceptionRanges=*/nullptr,
11410                                              /*NumExceptions=*/0,
11411                                              /*NoexceptExpr=*/nullptr,
11412                                              /*ExceptionSpecTokens=*/nullptr,
11413                                              Loc, Loc, D),
11414                 DS.getAttributes(),
11415                 SourceLocation());
11416   D.SetIdentifier(&II, Loc);
11417 
11418   // Insert this function into translation-unit scope.
11419 
11420   DeclContext *PrevDC = CurContext;
11421   CurContext = Context.getTranslationUnitDecl();
11422 
11423   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11424   FD->setImplicit();
11425 
11426   CurContext = PrevDC;
11427 
11428   AddKnownFunctionAttributes(FD);
11429 
11430   return FD;
11431 }
11432 
11433 /// \brief Adds any function attributes that we know a priori based on
11434 /// the declaration of this function.
11435 ///
11436 /// These attributes can apply both to implicitly-declared builtins
11437 /// (like __builtin___printf_chk) or to library-declared functions
11438 /// like NSLog or printf.
11439 ///
11440 /// We need to check for duplicate attributes both here and where user-written
11441 /// attributes are applied to declarations.
11442 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11443   if (FD->isInvalidDecl())
11444     return;
11445 
11446   // If this is a built-in function, map its builtin attributes to
11447   // actual attributes.
11448   if (unsigned BuiltinID = FD->getBuiltinID()) {
11449     // Handle printf-formatting attributes.
11450     unsigned FormatIdx;
11451     bool HasVAListArg;
11452     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11453       if (!FD->hasAttr<FormatAttr>()) {
11454         const char *fmt = "printf";
11455         unsigned int NumParams = FD->getNumParams();
11456         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11457             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11458           fmt = "NSString";
11459         FD->addAttr(FormatAttr::CreateImplicit(Context,
11460                                                &Context.Idents.get(fmt),
11461                                                FormatIdx+1,
11462                                                HasVAListArg ? 0 : FormatIdx+2,
11463                                                FD->getLocation()));
11464       }
11465     }
11466     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11467                                              HasVAListArg)) {
11468      if (!FD->hasAttr<FormatAttr>())
11469        FD->addAttr(FormatAttr::CreateImplicit(Context,
11470                                               &Context.Idents.get("scanf"),
11471                                               FormatIdx+1,
11472                                               HasVAListArg ? 0 : FormatIdx+2,
11473                                               FD->getLocation()));
11474     }
11475 
11476     // Mark const if we don't care about errno and that is the only
11477     // thing preventing the function from being const. This allows
11478     // IRgen to use LLVM intrinsics for such functions.
11479     if (!getLangOpts().MathErrno &&
11480         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11481       if (!FD->hasAttr<ConstAttr>())
11482         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11483     }
11484 
11485     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11486         !FD->hasAttr<ReturnsTwiceAttr>())
11487       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11488                                          FD->getLocation()));
11489     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11490       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11491     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11492       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11493     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11494         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11495         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11496       // Assign appropriate attribute depending on CUDA compilation
11497       // mode and the target builtin belongs to. E.g. during host
11498       // compilation, aux builtins are __device__, the rest are __host__.
11499       if (getLangOpts().CUDAIsDevice !=
11500           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11501         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11502       else
11503         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11504     }
11505   }
11506 
11507   IdentifierInfo *Name = FD->getIdentifier();
11508   if (!Name)
11509     return;
11510   if ((!getLangOpts().CPlusPlus &&
11511        FD->getDeclContext()->isTranslationUnit()) ||
11512       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11513        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11514        LinkageSpecDecl::lang_c)) {
11515     // Okay: this could be a libc/libm/Objective-C function we know
11516     // about.
11517   } else
11518     return;
11519 
11520   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11521     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11522     // target-specific builtins, perhaps?
11523     if (!FD->hasAttr<FormatAttr>())
11524       FD->addAttr(FormatAttr::CreateImplicit(Context,
11525                                              &Context.Idents.get("printf"), 2,
11526                                              Name->isStr("vasprintf") ? 0 : 3,
11527                                              FD->getLocation()));
11528   }
11529 
11530   if (Name->isStr("__CFStringMakeConstantString")) {
11531     // We already have a __builtin___CFStringMakeConstantString,
11532     // but builds that use -fno-constant-cfstrings don't go through that.
11533     if (!FD->hasAttr<FormatArgAttr>())
11534       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11535                                                 FD->getLocation()));
11536   }
11537 }
11538 
11539 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11540                                     TypeSourceInfo *TInfo) {
11541   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11542   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11543 
11544   if (!TInfo) {
11545     assert(D.isInvalidType() && "no declarator info for valid type");
11546     TInfo = Context.getTrivialTypeSourceInfo(T);
11547   }
11548 
11549   // Scope manipulation handled by caller.
11550   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11551                                            D.getLocStart(),
11552                                            D.getIdentifierLoc(),
11553                                            D.getIdentifier(),
11554                                            TInfo);
11555 
11556   // Bail out immediately if we have an invalid declaration.
11557   if (D.isInvalidType()) {
11558     NewTD->setInvalidDecl();
11559     return NewTD;
11560   }
11561 
11562   if (D.getDeclSpec().isModulePrivateSpecified()) {
11563     if (CurContext->isFunctionOrMethod())
11564       Diag(NewTD->getLocation(), diag::err_module_private_local)
11565         << 2 << NewTD->getDeclName()
11566         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11567         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11568     else
11569       NewTD->setModulePrivate();
11570   }
11571 
11572   // C++ [dcl.typedef]p8:
11573   //   If the typedef declaration defines an unnamed class (or
11574   //   enum), the first typedef-name declared by the declaration
11575   //   to be that class type (or enum type) is used to denote the
11576   //   class type (or enum type) for linkage purposes only.
11577   // We need to check whether the type was declared in the declaration.
11578   switch (D.getDeclSpec().getTypeSpecType()) {
11579   case TST_enum:
11580   case TST_struct:
11581   case TST_interface:
11582   case TST_union:
11583   case TST_class: {
11584     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11585     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11586     break;
11587   }
11588 
11589   default:
11590     break;
11591   }
11592 
11593   return NewTD;
11594 }
11595 
11596 
11597 /// \brief Check that this is a valid underlying type for an enum declaration.
11598 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11599   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11600   QualType T = TI->getType();
11601 
11602   if (T->isDependentType())
11603     return false;
11604 
11605   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11606     if (BT->isInteger())
11607       return false;
11608 
11609   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11610   return true;
11611 }
11612 
11613 /// Check whether this is a valid redeclaration of a previous enumeration.
11614 /// \return true if the redeclaration was invalid.
11615 bool Sema::CheckEnumRedeclaration(
11616     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11617     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11618   bool IsFixed = !EnumUnderlyingTy.isNull();
11619 
11620   if (IsScoped != Prev->isScoped()) {
11621     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11622       << Prev->isScoped();
11623     Diag(Prev->getLocation(), diag::note_previous_declaration);
11624     return true;
11625   }
11626 
11627   if (IsFixed && Prev->isFixed()) {
11628     if (!EnumUnderlyingTy->isDependentType() &&
11629         !Prev->getIntegerType()->isDependentType() &&
11630         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11631                                         Prev->getIntegerType())) {
11632       // TODO: Highlight the underlying type of the redeclaration.
11633       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11634         << EnumUnderlyingTy << Prev->getIntegerType();
11635       Diag(Prev->getLocation(), diag::note_previous_declaration)
11636           << Prev->getIntegerTypeRange();
11637       return true;
11638     }
11639   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11640     ;
11641   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11642     ;
11643   } else if (IsFixed != Prev->isFixed()) {
11644     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11645       << Prev->isFixed();
11646     Diag(Prev->getLocation(), diag::note_previous_declaration);
11647     return true;
11648   }
11649 
11650   return false;
11651 }
11652 
11653 /// \brief Get diagnostic %select index for tag kind for
11654 /// redeclaration diagnostic message.
11655 /// WARNING: Indexes apply to particular diagnostics only!
11656 ///
11657 /// \returns diagnostic %select index.
11658 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11659   switch (Tag) {
11660   case TTK_Struct: return 0;
11661   case TTK_Interface: return 1;
11662   case TTK_Class:  return 2;
11663   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11664   }
11665 }
11666 
11667 /// \brief Determine if tag kind is a class-key compatible with
11668 /// class for redeclaration (class, struct, or __interface).
11669 ///
11670 /// \returns true iff the tag kind is compatible.
11671 static bool isClassCompatTagKind(TagTypeKind Tag)
11672 {
11673   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11674 }
11675 
11676 /// \brief Determine whether a tag with a given kind is acceptable
11677 /// as a redeclaration of the given tag declaration.
11678 ///
11679 /// \returns true if the new tag kind is acceptable, false otherwise.
11680 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11681                                         TagTypeKind NewTag, bool isDefinition,
11682                                         SourceLocation NewTagLoc,
11683                                         const IdentifierInfo *Name) {
11684   // C++ [dcl.type.elab]p3:
11685   //   The class-key or enum keyword present in the
11686   //   elaborated-type-specifier shall agree in kind with the
11687   //   declaration to which the name in the elaborated-type-specifier
11688   //   refers. This rule also applies to the form of
11689   //   elaborated-type-specifier that declares a class-name or
11690   //   friend class since it can be construed as referring to the
11691   //   definition of the class. Thus, in any
11692   //   elaborated-type-specifier, the enum keyword shall be used to
11693   //   refer to an enumeration (7.2), the union class-key shall be
11694   //   used to refer to a union (clause 9), and either the class or
11695   //   struct class-key shall be used to refer to a class (clause 9)
11696   //   declared using the class or struct class-key.
11697   TagTypeKind OldTag = Previous->getTagKind();
11698   if (!isDefinition || !isClassCompatTagKind(NewTag))
11699     if (OldTag == NewTag)
11700       return true;
11701 
11702   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11703     // Warn about the struct/class tag mismatch.
11704     bool isTemplate = false;
11705     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11706       isTemplate = Record->getDescribedClassTemplate();
11707 
11708     if (!ActiveTemplateInstantiations.empty()) {
11709       // In a template instantiation, do not offer fix-its for tag mismatches
11710       // since they usually mess up the template instead of fixing the problem.
11711       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11712         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11713         << getRedeclDiagFromTagKind(OldTag);
11714       return true;
11715     }
11716 
11717     if (isDefinition) {
11718       // On definitions, check previous tags and issue a fix-it for each
11719       // one that doesn't match the current tag.
11720       if (Previous->getDefinition()) {
11721         // Don't suggest fix-its for redefinitions.
11722         return true;
11723       }
11724 
11725       bool previousMismatch = false;
11726       for (auto I : Previous->redecls()) {
11727         if (I->getTagKind() != NewTag) {
11728           if (!previousMismatch) {
11729             previousMismatch = true;
11730             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11731               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11732               << getRedeclDiagFromTagKind(I->getTagKind());
11733           }
11734           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11735             << getRedeclDiagFromTagKind(NewTag)
11736             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11737                  TypeWithKeyword::getTagTypeKindName(NewTag));
11738         }
11739       }
11740       return true;
11741     }
11742 
11743     // Check for a previous definition.  If current tag and definition
11744     // are same type, do nothing.  If no definition, but disagree with
11745     // with previous tag type, give a warning, but no fix-it.
11746     const TagDecl *Redecl = Previous->getDefinition() ?
11747                             Previous->getDefinition() : Previous;
11748     if (Redecl->getTagKind() == NewTag) {
11749       return true;
11750     }
11751 
11752     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11753       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11754       << getRedeclDiagFromTagKind(OldTag);
11755     Diag(Redecl->getLocation(), diag::note_previous_use);
11756 
11757     // If there is a previous definition, suggest a fix-it.
11758     if (Previous->getDefinition()) {
11759         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11760           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11761           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11762                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11763     }
11764 
11765     return true;
11766   }
11767   return false;
11768 }
11769 
11770 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11771 /// from an outer enclosing namespace or file scope inside a friend declaration.
11772 /// This should provide the commented out code in the following snippet:
11773 ///   namespace N {
11774 ///     struct X;
11775 ///     namespace M {
11776 ///       struct Y { friend struct /*N::*/ X; };
11777 ///     }
11778 ///   }
11779 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11780                                          SourceLocation NameLoc) {
11781   // While the decl is in a namespace, do repeated lookup of that name and see
11782   // if we get the same namespace back.  If we do not, continue until
11783   // translation unit scope, at which point we have a fully qualified NNS.
11784   SmallVector<IdentifierInfo *, 4> Namespaces;
11785   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11786   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11787     // This tag should be declared in a namespace, which can only be enclosed by
11788     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11789     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11790     if (!Namespace || Namespace->isAnonymousNamespace())
11791       return FixItHint();
11792     IdentifierInfo *II = Namespace->getIdentifier();
11793     Namespaces.push_back(II);
11794     NamedDecl *Lookup = SemaRef.LookupSingleName(
11795         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11796     if (Lookup == Namespace)
11797       break;
11798   }
11799 
11800   // Once we have all the namespaces, reverse them to go outermost first, and
11801   // build an NNS.
11802   SmallString<64> Insertion;
11803   llvm::raw_svector_ostream OS(Insertion);
11804   if (DC->isTranslationUnit())
11805     OS << "::";
11806   std::reverse(Namespaces.begin(), Namespaces.end());
11807   for (auto *II : Namespaces)
11808     OS << II->getName() << "::";
11809   return FixItHint::CreateInsertion(NameLoc, Insertion);
11810 }
11811 
11812 /// \brief Determine whether a tag originally declared in context \p OldDC can
11813 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11814 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11815 /// using-declaration).
11816 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11817                                          DeclContext *NewDC) {
11818   OldDC = OldDC->getRedeclContext();
11819   NewDC = NewDC->getRedeclContext();
11820 
11821   if (OldDC->Equals(NewDC))
11822     return true;
11823 
11824   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11825   // encloses the other).
11826   if (S.getLangOpts().MSVCCompat &&
11827       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11828     return true;
11829 
11830   return false;
11831 }
11832 
11833 /// Find the DeclContext in which a tag is implicitly declared if we see an
11834 /// elaborated type specifier in the specified context, and lookup finds
11835 /// nothing.
11836 static DeclContext *getTagInjectionContext(DeclContext *DC) {
11837   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
11838     DC = DC->getParent();
11839   return DC;
11840 }
11841 
11842 /// Find the Scope in which a tag is implicitly declared if we see an
11843 /// elaborated type specifier in the specified context, and lookup finds
11844 /// nothing.
11845 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
11846   while (S->isClassScope() ||
11847          (LangOpts.CPlusPlus &&
11848           S->isFunctionPrototypeScope()) ||
11849          ((S->getFlags() & Scope::DeclScope) == 0) ||
11850          (S->getEntity() && S->getEntity()->isTransparentContext()))
11851     S = S->getParent();
11852   return S;
11853 }
11854 
11855 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11856 /// former case, Name will be non-null.  In the later case, Name will be null.
11857 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11858 /// reference/declaration/definition of a tag.
11859 ///
11860 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11861 /// trailing-type-specifier) other than one in an alias-declaration.
11862 ///
11863 /// \param SkipBody If non-null, will be set to indicate if the caller should
11864 /// skip the definition of this tag and treat it as if it were a declaration.
11865 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11866                      SourceLocation KWLoc, CXXScopeSpec &SS,
11867                      IdentifierInfo *Name, SourceLocation NameLoc,
11868                      AttributeList *Attr, AccessSpecifier AS,
11869                      SourceLocation ModulePrivateLoc,
11870                      MultiTemplateParamsArg TemplateParameterLists,
11871                      bool &OwnedDecl, bool &IsDependent,
11872                      SourceLocation ScopedEnumKWLoc,
11873                      bool ScopedEnumUsesClassTag,
11874                      TypeResult UnderlyingType,
11875                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11876   // If this is not a definition, it must have a name.
11877   IdentifierInfo *OrigName = Name;
11878   assert((Name != nullptr || TUK == TUK_Definition) &&
11879          "Nameless record must be a definition!");
11880   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11881 
11882   OwnedDecl = false;
11883   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11884   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11885 
11886   // FIXME: Check explicit specializations more carefully.
11887   bool isExplicitSpecialization = false;
11888   bool Invalid = false;
11889 
11890   // We only need to do this matching if we have template parameters
11891   // or a scope specifier, which also conveniently avoids this work
11892   // for non-C++ cases.
11893   if (TemplateParameterLists.size() > 0 ||
11894       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11895     if (TemplateParameterList *TemplateParams =
11896             MatchTemplateParametersToScopeSpecifier(
11897                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11898                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11899       if (Kind == TTK_Enum) {
11900         Diag(KWLoc, diag::err_enum_template);
11901         return nullptr;
11902       }
11903 
11904       if (TemplateParams->size() > 0) {
11905         // This is a declaration or definition of a class template (which may
11906         // be a member of another template).
11907 
11908         if (Invalid)
11909           return nullptr;
11910 
11911         OwnedDecl = false;
11912         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11913                                                SS, Name, NameLoc, Attr,
11914                                                TemplateParams, AS,
11915                                                ModulePrivateLoc,
11916                                                /*FriendLoc*/SourceLocation(),
11917                                                TemplateParameterLists.size()-1,
11918                                                TemplateParameterLists.data(),
11919                                                SkipBody);
11920         return Result.get();
11921       } else {
11922         // The "template<>" header is extraneous.
11923         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11924           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11925         isExplicitSpecialization = true;
11926       }
11927     }
11928   }
11929 
11930   // Figure out the underlying type if this a enum declaration. We need to do
11931   // this early, because it's needed to detect if this is an incompatible
11932   // redeclaration.
11933   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11934   bool EnumUnderlyingIsImplicit = false;
11935 
11936   if (Kind == TTK_Enum) {
11937     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11938       // No underlying type explicitly specified, or we failed to parse the
11939       // type, default to int.
11940       EnumUnderlying = Context.IntTy.getTypePtr();
11941     else if (UnderlyingType.get()) {
11942       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11943       // integral type; any cv-qualification is ignored.
11944       TypeSourceInfo *TI = nullptr;
11945       GetTypeFromParser(UnderlyingType.get(), &TI);
11946       EnumUnderlying = TI;
11947 
11948       if (CheckEnumUnderlyingType(TI))
11949         // Recover by falling back to int.
11950         EnumUnderlying = Context.IntTy.getTypePtr();
11951 
11952       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11953                                           UPPC_FixedUnderlyingType))
11954         EnumUnderlying = Context.IntTy.getTypePtr();
11955 
11956     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11957       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11958         // Microsoft enums are always of int type.
11959         EnumUnderlying = Context.IntTy.getTypePtr();
11960         EnumUnderlyingIsImplicit = true;
11961       }
11962     }
11963   }
11964 
11965   DeclContext *SearchDC = CurContext;
11966   DeclContext *DC = CurContext;
11967   bool isStdBadAlloc = false;
11968 
11969   RedeclarationKind Redecl = ForRedeclaration;
11970   if (TUK == TUK_Friend || TUK == TUK_Reference)
11971     Redecl = NotForRedeclaration;
11972 
11973   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11974   if (Name && SS.isNotEmpty()) {
11975     // We have a nested-name tag ('struct foo::bar').
11976 
11977     // Check for invalid 'foo::'.
11978     if (SS.isInvalid()) {
11979       Name = nullptr;
11980       goto CreateNewDecl;
11981     }
11982 
11983     // If this is a friend or a reference to a class in a dependent
11984     // context, don't try to make a decl for it.
11985     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11986       DC = computeDeclContext(SS, false);
11987       if (!DC) {
11988         IsDependent = true;
11989         return nullptr;
11990       }
11991     } else {
11992       DC = computeDeclContext(SS, true);
11993       if (!DC) {
11994         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11995           << SS.getRange();
11996         return nullptr;
11997       }
11998     }
11999 
12000     if (RequireCompleteDeclContext(SS, DC))
12001       return nullptr;
12002 
12003     SearchDC = DC;
12004     // Look-up name inside 'foo::'.
12005     LookupQualifiedName(Previous, DC);
12006 
12007     if (Previous.isAmbiguous())
12008       return nullptr;
12009 
12010     if (Previous.empty()) {
12011       // Name lookup did not find anything. However, if the
12012       // nested-name-specifier refers to the current instantiation,
12013       // and that current instantiation has any dependent base
12014       // classes, we might find something at instantiation time: treat
12015       // this as a dependent elaborated-type-specifier.
12016       // But this only makes any sense for reference-like lookups.
12017       if (Previous.wasNotFoundInCurrentInstantiation() &&
12018           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12019         IsDependent = true;
12020         return nullptr;
12021       }
12022 
12023       // A tag 'foo::bar' must already exist.
12024       Diag(NameLoc, diag::err_not_tag_in_scope)
12025         << Kind << Name << DC << SS.getRange();
12026       Name = nullptr;
12027       Invalid = true;
12028       goto CreateNewDecl;
12029     }
12030   } else if (Name) {
12031     // C++14 [class.mem]p14:
12032     //   If T is the name of a class, then each of the following shall have a
12033     //   name different from T:
12034     //    -- every member of class T that is itself a type
12035     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12036         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12037       return nullptr;
12038 
12039     // If this is a named struct, check to see if there was a previous forward
12040     // declaration or definition.
12041     // FIXME: We're looking into outer scopes here, even when we
12042     // shouldn't be. Doing so can result in ambiguities that we
12043     // shouldn't be diagnosing.
12044     LookupName(Previous, S);
12045 
12046     // When declaring or defining a tag, ignore ambiguities introduced
12047     // by types using'ed into this scope.
12048     if (Previous.isAmbiguous() &&
12049         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12050       LookupResult::Filter F = Previous.makeFilter();
12051       while (F.hasNext()) {
12052         NamedDecl *ND = F.next();
12053         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12054           F.erase();
12055       }
12056       F.done();
12057     }
12058 
12059     // C++11 [namespace.memdef]p3:
12060     //   If the name in a friend declaration is neither qualified nor
12061     //   a template-id and the declaration is a function or an
12062     //   elaborated-type-specifier, the lookup to determine whether
12063     //   the entity has been previously declared shall not consider
12064     //   any scopes outside the innermost enclosing namespace.
12065     //
12066     // MSVC doesn't implement the above rule for types, so a friend tag
12067     // declaration may be a redeclaration of a type declared in an enclosing
12068     // scope.  They do implement this rule for friend functions.
12069     //
12070     // Does it matter that this should be by scope instead of by
12071     // semantic context?
12072     if (!Previous.empty() && TUK == TUK_Friend) {
12073       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12074       LookupResult::Filter F = Previous.makeFilter();
12075       bool FriendSawTagOutsideEnclosingNamespace = false;
12076       while (F.hasNext()) {
12077         NamedDecl *ND = F.next();
12078         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12079         if (DC->isFileContext() &&
12080             !EnclosingNS->Encloses(ND->getDeclContext())) {
12081           if (getLangOpts().MSVCCompat)
12082             FriendSawTagOutsideEnclosingNamespace = true;
12083           else
12084             F.erase();
12085         }
12086       }
12087       F.done();
12088 
12089       // Diagnose this MSVC extension in the easy case where lookup would have
12090       // unambiguously found something outside the enclosing namespace.
12091       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12092         NamedDecl *ND = Previous.getFoundDecl();
12093         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12094             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12095       }
12096     }
12097 
12098     // Note:  there used to be some attempt at recovery here.
12099     if (Previous.isAmbiguous())
12100       return nullptr;
12101 
12102     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12103       // FIXME: This makes sure that we ignore the contexts associated
12104       // with C structs, unions, and enums when looking for a matching
12105       // tag declaration or definition. See the similar lookup tweak
12106       // in Sema::LookupName; is there a better way to deal with this?
12107       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12108         SearchDC = SearchDC->getParent();
12109     }
12110   }
12111 
12112   if (Previous.isSingleResult() &&
12113       Previous.getFoundDecl()->isTemplateParameter()) {
12114     // Maybe we will complain about the shadowed template parameter.
12115     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12116     // Just pretend that we didn't see the previous declaration.
12117     Previous.clear();
12118   }
12119 
12120   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12121       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12122     // This is a declaration of or a reference to "std::bad_alloc".
12123     isStdBadAlloc = true;
12124 
12125     if (Previous.empty() && StdBadAlloc) {
12126       // std::bad_alloc has been implicitly declared (but made invisible to
12127       // name lookup). Fill in this implicit declaration as the previous
12128       // declaration, so that the declarations get chained appropriately.
12129       Previous.addDecl(getStdBadAlloc());
12130     }
12131   }
12132 
12133   // If we didn't find a previous declaration, and this is a reference
12134   // (or friend reference), move to the correct scope.  In C++, we
12135   // also need to do a redeclaration lookup there, just in case
12136   // there's a shadow friend decl.
12137   if (Name && Previous.empty() &&
12138       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12139     if (Invalid) goto CreateNewDecl;
12140     assert(SS.isEmpty());
12141 
12142     if (TUK == TUK_Reference) {
12143       // C++ [basic.scope.pdecl]p5:
12144       //   -- for an elaborated-type-specifier of the form
12145       //
12146       //          class-key identifier
12147       //
12148       //      if the elaborated-type-specifier is used in the
12149       //      decl-specifier-seq or parameter-declaration-clause of a
12150       //      function defined in namespace scope, the identifier is
12151       //      declared as a class-name in the namespace that contains
12152       //      the declaration; otherwise, except as a friend
12153       //      declaration, the identifier is declared in the smallest
12154       //      non-class, non-function-prototype scope that contains the
12155       //      declaration.
12156       //
12157       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12158       // C structs and unions.
12159       //
12160       // It is an error in C++ to declare (rather than define) an enum
12161       // type, including via an elaborated type specifier.  We'll
12162       // diagnose that later; for now, declare the enum in the same
12163       // scope as we would have picked for any other tag type.
12164       //
12165       // GNU C also supports this behavior as part of its incomplete
12166       // enum types extension, while GNU C++ does not.
12167       //
12168       // Find the context where we'll be declaring the tag.
12169       // FIXME: We would like to maintain the current DeclContext as the
12170       // lexical context,
12171       SearchDC = getTagInjectionContext(SearchDC);
12172 
12173       // Find the scope where we'll be declaring the tag.
12174       S = getTagInjectionScope(S, getLangOpts());
12175     } else {
12176       assert(TUK == TUK_Friend);
12177       // C++ [namespace.memdef]p3:
12178       //   If a friend declaration in a non-local class first declares a
12179       //   class or function, the friend class or function is a member of
12180       //   the innermost enclosing namespace.
12181       SearchDC = SearchDC->getEnclosingNamespaceContext();
12182     }
12183 
12184     // In C++, we need to do a redeclaration lookup to properly
12185     // diagnose some problems.
12186     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12187     // hidden declaration so that we don't get ambiguity errors when using a
12188     // type declared by an elaborated-type-specifier.  In C that is not correct
12189     // and we should instead merge compatible types found by lookup.
12190     if (getLangOpts().CPlusPlus) {
12191       Previous.setRedeclarationKind(ForRedeclaration);
12192       LookupQualifiedName(Previous, SearchDC);
12193     } else {
12194       Previous.setRedeclarationKind(ForRedeclaration);
12195       LookupName(Previous, S);
12196     }
12197   }
12198 
12199   // If we have a known previous declaration to use, then use it.
12200   if (Previous.empty() && SkipBody && SkipBody->Previous)
12201     Previous.addDecl(SkipBody->Previous);
12202 
12203   if (!Previous.empty()) {
12204     NamedDecl *PrevDecl = Previous.getFoundDecl();
12205     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12206 
12207     // It's okay to have a tag decl in the same scope as a typedef
12208     // which hides a tag decl in the same scope.  Finding this
12209     // insanity with a redeclaration lookup can only actually happen
12210     // in C++.
12211     //
12212     // This is also okay for elaborated-type-specifiers, which is
12213     // technically forbidden by the current standard but which is
12214     // okay according to the likely resolution of an open issue;
12215     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12216     if (getLangOpts().CPlusPlus) {
12217       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12218         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12219           TagDecl *Tag = TT->getDecl();
12220           if (Tag->getDeclName() == Name &&
12221               Tag->getDeclContext()->getRedeclContext()
12222                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12223             PrevDecl = Tag;
12224             Previous.clear();
12225             Previous.addDecl(Tag);
12226             Previous.resolveKind();
12227           }
12228         }
12229       }
12230     }
12231 
12232     // If this is a redeclaration of a using shadow declaration, it must
12233     // declare a tag in the same context. In MSVC mode, we allow a
12234     // redefinition if either context is within the other.
12235     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12236       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12237       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12238           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12239           !(OldTag && isAcceptableTagRedeclContext(
12240                           *this, OldTag->getDeclContext(), SearchDC))) {
12241         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12242         Diag(Shadow->getTargetDecl()->getLocation(),
12243              diag::note_using_decl_target);
12244         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12245             << 0;
12246         // Recover by ignoring the old declaration.
12247         Previous.clear();
12248         goto CreateNewDecl;
12249       }
12250     }
12251 
12252     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12253       // If this is a use of a previous tag, or if the tag is already declared
12254       // in the same scope (so that the definition/declaration completes or
12255       // rementions the tag), reuse the decl.
12256       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12257           isDeclInScope(DirectPrevDecl, SearchDC, S,
12258                         SS.isNotEmpty() || isExplicitSpecialization)) {
12259         // Make sure that this wasn't declared as an enum and now used as a
12260         // struct or something similar.
12261         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12262                                           TUK == TUK_Definition, KWLoc,
12263                                           Name)) {
12264           bool SafeToContinue
12265             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12266                Kind != TTK_Enum);
12267           if (SafeToContinue)
12268             Diag(KWLoc, diag::err_use_with_wrong_tag)
12269               << Name
12270               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12271                                               PrevTagDecl->getKindName());
12272           else
12273             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12274           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12275 
12276           if (SafeToContinue)
12277             Kind = PrevTagDecl->getTagKind();
12278           else {
12279             // Recover by making this an anonymous redefinition.
12280             Name = nullptr;
12281             Previous.clear();
12282             Invalid = true;
12283           }
12284         }
12285 
12286         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12287           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12288 
12289           // If this is an elaborated-type-specifier for a scoped enumeration,
12290           // the 'class' keyword is not necessary and not permitted.
12291           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12292             if (ScopedEnum)
12293               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12294                 << PrevEnum->isScoped()
12295                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12296             return PrevTagDecl;
12297           }
12298 
12299           QualType EnumUnderlyingTy;
12300           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12301             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12302           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12303             EnumUnderlyingTy = QualType(T, 0);
12304 
12305           // All conflicts with previous declarations are recovered by
12306           // returning the previous declaration, unless this is a definition,
12307           // in which case we want the caller to bail out.
12308           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12309                                      ScopedEnum, EnumUnderlyingTy,
12310                                      EnumUnderlyingIsImplicit, PrevEnum))
12311             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12312         }
12313 
12314         // C++11 [class.mem]p1:
12315         //   A member shall not be declared twice in the member-specification,
12316         //   except that a nested class or member class template can be declared
12317         //   and then later defined.
12318         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12319             S->isDeclScope(PrevDecl)) {
12320           Diag(NameLoc, diag::ext_member_redeclared);
12321           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12322         }
12323 
12324         if (!Invalid) {
12325           // If this is a use, just return the declaration we found, unless
12326           // we have attributes.
12327           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12328             if (Attr) {
12329               // FIXME: Diagnose these attributes. For now, we create a new
12330               // declaration to hold them.
12331             } else if (TUK == TUK_Reference &&
12332                        (PrevTagDecl->getFriendObjectKind() ==
12333                             Decl::FOK_Undeclared ||
12334                         PP.getModuleContainingLocation(
12335                             PrevDecl->getLocation()) !=
12336                             PP.getModuleContainingLocation(KWLoc)) &&
12337                        SS.isEmpty()) {
12338               // This declaration is a reference to an existing entity, but
12339               // has different visibility from that entity: it either makes
12340               // a friend visible or it makes a type visible in a new module.
12341               // In either case, create a new declaration. We only do this if
12342               // the declaration would have meant the same thing if no prior
12343               // declaration were found, that is, if it was found in the same
12344               // scope where we would have injected a declaration.
12345               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12346                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12347                 return PrevTagDecl;
12348               // This is in the injected scope, create a new declaration in
12349               // that scope.
12350               S = getTagInjectionScope(S, getLangOpts());
12351             } else {
12352               return PrevTagDecl;
12353             }
12354           }
12355 
12356           // Diagnose attempts to redefine a tag.
12357           if (TUK == TUK_Definition) {
12358             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12359               // If we're defining a specialization and the previous definition
12360               // is from an implicit instantiation, don't emit an error
12361               // here; we'll catch this in the general case below.
12362               bool IsExplicitSpecializationAfterInstantiation = false;
12363               if (isExplicitSpecialization) {
12364                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12365                   IsExplicitSpecializationAfterInstantiation =
12366                     RD->getTemplateSpecializationKind() !=
12367                     TSK_ExplicitSpecialization;
12368                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12369                   IsExplicitSpecializationAfterInstantiation =
12370                     ED->getTemplateSpecializationKind() !=
12371                     TSK_ExplicitSpecialization;
12372               }
12373 
12374               NamedDecl *Hidden = nullptr;
12375               if (SkipBody && getLangOpts().CPlusPlus &&
12376                   !hasVisibleDefinition(Def, &Hidden)) {
12377                 // There is a definition of this tag, but it is not visible. We
12378                 // explicitly make use of C++'s one definition rule here, and
12379                 // assume that this definition is identical to the hidden one
12380                 // we already have. Make the existing definition visible and
12381                 // use it in place of this one.
12382                 SkipBody->ShouldSkip = true;
12383                 makeMergedDefinitionVisible(Hidden, KWLoc);
12384                 return Def;
12385               } else if (!IsExplicitSpecializationAfterInstantiation) {
12386                 // A redeclaration in function prototype scope in C isn't
12387                 // visible elsewhere, so merely issue a warning.
12388                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12389                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12390                 else
12391                   Diag(NameLoc, diag::err_redefinition) << Name;
12392                 Diag(Def->getLocation(), diag::note_previous_definition);
12393                 // If this is a redefinition, recover by making this
12394                 // struct be anonymous, which will make any later
12395                 // references get the previous definition.
12396                 Name = nullptr;
12397                 Previous.clear();
12398                 Invalid = true;
12399               }
12400             } else {
12401               // If the type is currently being defined, complain
12402               // about a nested redefinition.
12403               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12404               if (TD->isBeingDefined()) {
12405                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12406                 Diag(PrevTagDecl->getLocation(),
12407                      diag::note_previous_definition);
12408                 Name = nullptr;
12409                 Previous.clear();
12410                 Invalid = true;
12411               }
12412             }
12413 
12414             // Okay, this is definition of a previously declared or referenced
12415             // tag. We're going to create a new Decl for it.
12416           }
12417 
12418           // Okay, we're going to make a redeclaration.  If this is some kind
12419           // of reference, make sure we build the redeclaration in the same DC
12420           // as the original, and ignore the current access specifier.
12421           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12422             SearchDC = PrevTagDecl->getDeclContext();
12423             AS = AS_none;
12424           }
12425         }
12426         // If we get here we have (another) forward declaration or we
12427         // have a definition.  Just create a new decl.
12428 
12429       } else {
12430         // If we get here, this is a definition of a new tag type in a nested
12431         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12432         // new decl/type.  We set PrevDecl to NULL so that the entities
12433         // have distinct types.
12434         Previous.clear();
12435       }
12436       // If we get here, we're going to create a new Decl. If PrevDecl
12437       // is non-NULL, it's a definition of the tag declared by
12438       // PrevDecl. If it's NULL, we have a new definition.
12439 
12440 
12441     // Otherwise, PrevDecl is not a tag, but was found with tag
12442     // lookup.  This is only actually possible in C++, where a few
12443     // things like templates still live in the tag namespace.
12444     } else {
12445       // Use a better diagnostic if an elaborated-type-specifier
12446       // found the wrong kind of type on the first
12447       // (non-redeclaration) lookup.
12448       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12449           !Previous.isForRedeclaration()) {
12450         unsigned Kind = 0;
12451         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12452         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12453         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12454         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12455         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12456         Invalid = true;
12457 
12458       // Otherwise, only diagnose if the declaration is in scope.
12459       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12460                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12461         // do nothing
12462 
12463       // Diagnose implicit declarations introduced by elaborated types.
12464       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12465         unsigned Kind = 0;
12466         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12467         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12468         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12469         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12470         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12471         Invalid = true;
12472 
12473       // Otherwise it's a declaration.  Call out a particularly common
12474       // case here.
12475       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12476         unsigned Kind = 0;
12477         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12478         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12479           << Name << Kind << TND->getUnderlyingType();
12480         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12481         Invalid = true;
12482 
12483       // Otherwise, diagnose.
12484       } else {
12485         // The tag name clashes with something else in the target scope,
12486         // issue an error and recover by making this tag be anonymous.
12487         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12488         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12489         Name = nullptr;
12490         Invalid = true;
12491       }
12492 
12493       // The existing declaration isn't relevant to us; we're in a
12494       // new scope, so clear out the previous declaration.
12495       Previous.clear();
12496     }
12497   }
12498 
12499 CreateNewDecl:
12500 
12501   TagDecl *PrevDecl = nullptr;
12502   if (Previous.isSingleResult())
12503     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12504 
12505   // If there is an identifier, use the location of the identifier as the
12506   // location of the decl, otherwise use the location of the struct/union
12507   // keyword.
12508   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12509 
12510   // Otherwise, create a new declaration. If there is a previous
12511   // declaration of the same entity, the two will be linked via
12512   // PrevDecl.
12513   TagDecl *New;
12514 
12515   bool IsForwardReference = false;
12516   if (Kind == TTK_Enum) {
12517     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12518     // enum X { A, B, C } D;    D should chain to X.
12519     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12520                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12521                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12522     // If this is an undefined enum, warn.
12523     if (TUK != TUK_Definition && !Invalid) {
12524       TagDecl *Def;
12525       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12526           cast<EnumDecl>(New)->isFixed()) {
12527         // C++0x: 7.2p2: opaque-enum-declaration.
12528         // Conflicts are diagnosed above. Do nothing.
12529       }
12530       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12531         Diag(Loc, diag::ext_forward_ref_enum_def)
12532           << New;
12533         Diag(Def->getLocation(), diag::note_previous_definition);
12534       } else {
12535         unsigned DiagID = diag::ext_forward_ref_enum;
12536         if (getLangOpts().MSVCCompat)
12537           DiagID = diag::ext_ms_forward_ref_enum;
12538         else if (getLangOpts().CPlusPlus)
12539           DiagID = diag::err_forward_ref_enum;
12540         Diag(Loc, DiagID);
12541 
12542         // If this is a forward-declared reference to an enumeration, make a
12543         // note of it; we won't actually be introducing the declaration into
12544         // the declaration context.
12545         if (TUK == TUK_Reference)
12546           IsForwardReference = true;
12547       }
12548     }
12549 
12550     if (EnumUnderlying) {
12551       EnumDecl *ED = cast<EnumDecl>(New);
12552       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12553         ED->setIntegerTypeSourceInfo(TI);
12554       else
12555         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12556       ED->setPromotionType(ED->getIntegerType());
12557     }
12558 
12559   } else {
12560     // struct/union/class
12561 
12562     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12563     // struct X { int A; } D;    D should chain to X.
12564     if (getLangOpts().CPlusPlus) {
12565       // FIXME: Look for a way to use RecordDecl for simple structs.
12566       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12567                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12568 
12569       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12570         StdBadAlloc = cast<CXXRecordDecl>(New);
12571     } else
12572       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12573                                cast_or_null<RecordDecl>(PrevDecl));
12574   }
12575 
12576   // C++11 [dcl.type]p3:
12577   //   A type-specifier-seq shall not define a class or enumeration [...].
12578   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12579     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12580       << Context.getTagDeclType(New);
12581     Invalid = true;
12582   }
12583 
12584   // Maybe add qualifier info.
12585   if (SS.isNotEmpty()) {
12586     if (SS.isSet()) {
12587       // If this is either a declaration or a definition, check the
12588       // nested-name-specifier against the current context. We don't do this
12589       // for explicit specializations, because they have similar checking
12590       // (with more specific diagnostics) in the call to
12591       // CheckMemberSpecialization, below.
12592       if (!isExplicitSpecialization &&
12593           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12594           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12595         Invalid = true;
12596 
12597       New->setQualifierInfo(SS.getWithLocInContext(Context));
12598       if (TemplateParameterLists.size() > 0) {
12599         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12600       }
12601     }
12602     else
12603       Invalid = true;
12604   }
12605 
12606   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12607     // Add alignment attributes if necessary; these attributes are checked when
12608     // the ASTContext lays out the structure.
12609     //
12610     // It is important for implementing the correct semantics that this
12611     // happen here (in act on tag decl). The #pragma pack stack is
12612     // maintained as a result of parser callbacks which can occur at
12613     // many points during the parsing of a struct declaration (because
12614     // the #pragma tokens are effectively skipped over during the
12615     // parsing of the struct).
12616     if (TUK == TUK_Definition) {
12617       AddAlignmentAttributesForRecord(RD);
12618       AddMsStructLayoutForRecord(RD);
12619     }
12620   }
12621 
12622   if (ModulePrivateLoc.isValid()) {
12623     if (isExplicitSpecialization)
12624       Diag(New->getLocation(), diag::err_module_private_specialization)
12625         << 2
12626         << FixItHint::CreateRemoval(ModulePrivateLoc);
12627     // __module_private__ does not apply to local classes. However, we only
12628     // diagnose this as an error when the declaration specifiers are
12629     // freestanding. Here, we just ignore the __module_private__.
12630     else if (!SearchDC->isFunctionOrMethod())
12631       New->setModulePrivate();
12632   }
12633 
12634   // If this is a specialization of a member class (of a class template),
12635   // check the specialization.
12636   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12637     Invalid = true;
12638 
12639   // If we're declaring or defining a tag in function prototype scope in C,
12640   // note that this type can only be used within the function and add it to
12641   // the list of decls to inject into the function definition scope.
12642   if ((Name || Kind == TTK_Enum) &&
12643       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12644     if (getLangOpts().CPlusPlus) {
12645       // C++ [dcl.fct]p6:
12646       //   Types shall not be defined in return or parameter types.
12647       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12648         Diag(Loc, diag::err_type_defined_in_param_type)
12649             << Name;
12650         Invalid = true;
12651       }
12652     } else if (!PrevDecl) {
12653       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12654     }
12655     DeclsInPrototypeScope.push_back(New);
12656   }
12657 
12658   if (Invalid)
12659     New->setInvalidDecl();
12660 
12661   if (Attr)
12662     ProcessDeclAttributeList(S, New, Attr);
12663 
12664   // Set the lexical context. If the tag has a C++ scope specifier, the
12665   // lexical context will be different from the semantic context.
12666   New->setLexicalDeclContext(CurContext);
12667 
12668   // Mark this as a friend decl if applicable.
12669   // In Microsoft mode, a friend declaration also acts as a forward
12670   // declaration so we always pass true to setObjectOfFriendDecl to make
12671   // the tag name visible.
12672   if (TUK == TUK_Friend)
12673     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12674 
12675   // Set the access specifier.
12676   if (!Invalid && SearchDC->isRecord())
12677     SetMemberAccessSpecifier(New, PrevDecl, AS);
12678 
12679   if (TUK == TUK_Definition)
12680     New->startDefinition();
12681 
12682   // If this has an identifier, add it to the scope stack.
12683   if (TUK == TUK_Friend) {
12684     // We might be replacing an existing declaration in the lookup tables;
12685     // if so, borrow its access specifier.
12686     if (PrevDecl)
12687       New->setAccess(PrevDecl->getAccess());
12688 
12689     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12690     DC->makeDeclVisibleInContext(New);
12691     if (Name) // can be null along some error paths
12692       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12693         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12694   } else if (Name) {
12695     S = getNonFieldDeclScope(S);
12696     PushOnScopeChains(New, S, !IsForwardReference);
12697     if (IsForwardReference)
12698       SearchDC->makeDeclVisibleInContext(New);
12699 
12700   } else {
12701     CurContext->addDecl(New);
12702   }
12703 
12704   // If this is the C FILE type, notify the AST context.
12705   if (IdentifierInfo *II = New->getIdentifier())
12706     if (!New->isInvalidDecl() &&
12707         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12708         II->isStr("FILE"))
12709       Context.setFILEDecl(New);
12710 
12711   if (PrevDecl)
12712     mergeDeclAttributes(New, PrevDecl);
12713 
12714   // If there's a #pragma GCC visibility in scope, set the visibility of this
12715   // record.
12716   AddPushedVisibilityAttribute(New);
12717 
12718   OwnedDecl = true;
12719   // In C++, don't return an invalid declaration. We can't recover well from
12720   // the cases where we make the type anonymous.
12721   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12722 }
12723 
12724 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12725   AdjustDeclIfTemplate(TagD);
12726   TagDecl *Tag = cast<TagDecl>(TagD);
12727 
12728   // Enter the tag context.
12729   PushDeclContext(S, Tag);
12730 
12731   ActOnDocumentableDecl(TagD);
12732 
12733   // If there's a #pragma GCC visibility in scope, set the visibility of this
12734   // record.
12735   AddPushedVisibilityAttribute(Tag);
12736 }
12737 
12738 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12739   assert(isa<ObjCContainerDecl>(IDecl) &&
12740          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12741   DeclContext *OCD = cast<DeclContext>(IDecl);
12742   assert(getContainingDC(OCD) == CurContext &&
12743       "The next DeclContext should be lexically contained in the current one.");
12744   CurContext = OCD;
12745   return IDecl;
12746 }
12747 
12748 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12749                                            SourceLocation FinalLoc,
12750                                            bool IsFinalSpelledSealed,
12751                                            SourceLocation LBraceLoc) {
12752   AdjustDeclIfTemplate(TagD);
12753   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12754 
12755   FieldCollector->StartClass();
12756 
12757   if (!Record->getIdentifier())
12758     return;
12759 
12760   if (FinalLoc.isValid())
12761     Record->addAttr(new (Context)
12762                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12763 
12764   // C++ [class]p2:
12765   //   [...] The class-name is also inserted into the scope of the
12766   //   class itself; this is known as the injected-class-name. For
12767   //   purposes of access checking, the injected-class-name is treated
12768   //   as if it were a public member name.
12769   CXXRecordDecl *InjectedClassName
12770     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12771                             Record->getLocStart(), Record->getLocation(),
12772                             Record->getIdentifier(),
12773                             /*PrevDecl=*/nullptr,
12774                             /*DelayTypeCreation=*/true);
12775   Context.getTypeDeclType(InjectedClassName, Record);
12776   InjectedClassName->setImplicit();
12777   InjectedClassName->setAccess(AS_public);
12778   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12779       InjectedClassName->setDescribedClassTemplate(Template);
12780   PushOnScopeChains(InjectedClassName, S);
12781   assert(InjectedClassName->isInjectedClassName() &&
12782          "Broken injected-class-name");
12783 }
12784 
12785 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12786                                     SourceLocation RBraceLoc) {
12787   AdjustDeclIfTemplate(TagD);
12788   TagDecl *Tag = cast<TagDecl>(TagD);
12789   Tag->setRBraceLoc(RBraceLoc);
12790 
12791   // Make sure we "complete" the definition even it is invalid.
12792   if (Tag->isBeingDefined()) {
12793     assert(Tag->isInvalidDecl() && "We should already have completed it");
12794     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12795       RD->completeDefinition();
12796   }
12797 
12798   if (isa<CXXRecordDecl>(Tag))
12799     FieldCollector->FinishClass();
12800 
12801   // Exit this scope of this tag's definition.
12802   PopDeclContext();
12803 
12804   if (getCurLexicalContext()->isObjCContainer() &&
12805       Tag->getDeclContext()->isFileContext())
12806     Tag->setTopLevelDeclInObjCContainer();
12807 
12808   // Notify the consumer that we've defined a tag.
12809   if (!Tag->isInvalidDecl())
12810     Consumer.HandleTagDeclDefinition(Tag);
12811 }
12812 
12813 void Sema::ActOnObjCContainerFinishDefinition() {
12814   // Exit this scope of this interface definition.
12815   PopDeclContext();
12816 }
12817 
12818 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12819   assert(DC == CurContext && "Mismatch of container contexts");
12820   OriginalLexicalContext = DC;
12821   ActOnObjCContainerFinishDefinition();
12822 }
12823 
12824 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12825   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12826   OriginalLexicalContext = nullptr;
12827 }
12828 
12829 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12830   AdjustDeclIfTemplate(TagD);
12831   TagDecl *Tag = cast<TagDecl>(TagD);
12832   Tag->setInvalidDecl();
12833 
12834   // Make sure we "complete" the definition even it is invalid.
12835   if (Tag->isBeingDefined()) {
12836     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12837       RD->completeDefinition();
12838   }
12839 
12840   // We're undoing ActOnTagStartDefinition here, not
12841   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12842   // the FieldCollector.
12843 
12844   PopDeclContext();
12845 }
12846 
12847 // Note that FieldName may be null for anonymous bitfields.
12848 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12849                                 IdentifierInfo *FieldName,
12850                                 QualType FieldTy, bool IsMsStruct,
12851                                 Expr *BitWidth, bool *ZeroWidth) {
12852   // Default to true; that shouldn't confuse checks for emptiness
12853   if (ZeroWidth)
12854     *ZeroWidth = true;
12855 
12856   // C99 6.7.2.1p4 - verify the field type.
12857   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12858   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12859     // Handle incomplete types with specific error.
12860     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12861       return ExprError();
12862     if (FieldName)
12863       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12864         << FieldName << FieldTy << BitWidth->getSourceRange();
12865     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12866       << FieldTy << BitWidth->getSourceRange();
12867   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12868                                              UPPC_BitFieldWidth))
12869     return ExprError();
12870 
12871   // If the bit-width is type- or value-dependent, don't try to check
12872   // it now.
12873   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12874     return BitWidth;
12875 
12876   llvm::APSInt Value;
12877   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12878   if (ICE.isInvalid())
12879     return ICE;
12880   BitWidth = ICE.get();
12881 
12882   if (Value != 0 && ZeroWidth)
12883     *ZeroWidth = false;
12884 
12885   // Zero-width bitfield is ok for anonymous field.
12886   if (Value == 0 && FieldName)
12887     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12888 
12889   if (Value.isSigned() && Value.isNegative()) {
12890     if (FieldName)
12891       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12892                << FieldName << Value.toString(10);
12893     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12894       << Value.toString(10);
12895   }
12896 
12897   if (!FieldTy->isDependentType()) {
12898     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12899     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12900     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12901 
12902     // Over-wide bitfields are an error in C or when using the MSVC bitfield
12903     // ABI.
12904     bool CStdConstraintViolation =
12905         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12906     bool MSBitfieldViolation =
12907         Value.ugt(TypeStorageSize) &&
12908         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12909     if (CStdConstraintViolation || MSBitfieldViolation) {
12910       unsigned DiagWidth =
12911           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12912       if (FieldName)
12913         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12914                << FieldName << (unsigned)Value.getZExtValue()
12915                << !CStdConstraintViolation << DiagWidth;
12916 
12917       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12918              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12919              << DiagWidth;
12920     }
12921 
12922     // Warn on types where the user might conceivably expect to get all
12923     // specified bits as value bits: that's all integral types other than
12924     // 'bool'.
12925     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12926       if (FieldName)
12927         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12928             << FieldName << (unsigned)Value.getZExtValue()
12929             << (unsigned)TypeWidth;
12930       else
12931         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12932             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12933     }
12934   }
12935 
12936   return BitWidth;
12937 }
12938 
12939 /// ActOnField - Each field of a C struct/union is passed into this in order
12940 /// to create a FieldDecl object for it.
12941 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12942                        Declarator &D, Expr *BitfieldWidth) {
12943   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12944                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12945                                /*InitStyle=*/ICIS_NoInit, AS_public);
12946   return Res;
12947 }
12948 
12949 /// HandleField - Analyze a field of a C struct or a C++ data member.
12950 ///
12951 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12952                              SourceLocation DeclStart,
12953                              Declarator &D, Expr *BitWidth,
12954                              InClassInitStyle InitStyle,
12955                              AccessSpecifier AS) {
12956   IdentifierInfo *II = D.getIdentifier();
12957   SourceLocation Loc = DeclStart;
12958   if (II) Loc = D.getIdentifierLoc();
12959 
12960   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12961   QualType T = TInfo->getType();
12962   if (getLangOpts().CPlusPlus) {
12963     CheckExtraCXXDefaultArguments(D);
12964 
12965     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12966                                         UPPC_DataMemberType)) {
12967       D.setInvalidType();
12968       T = Context.IntTy;
12969       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12970     }
12971   }
12972 
12973   // TR 18037 does not allow fields to be declared with address spaces.
12974   if (T.getQualifiers().hasAddressSpace()) {
12975     Diag(Loc, diag::err_field_with_address_space);
12976     D.setInvalidType();
12977   }
12978 
12979   // OpenCL 1.2 spec, s6.9 r:
12980   // The event type cannot be used to declare a structure or union field.
12981   if (LangOpts.OpenCL && T->isEventT()) {
12982     Diag(Loc, diag::err_event_t_struct_field);
12983     D.setInvalidType();
12984   }
12985 
12986   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12987 
12988   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12989     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12990          diag::err_invalid_thread)
12991       << DeclSpec::getSpecifierName(TSCS);
12992 
12993   // Check to see if this name was declared as a member previously
12994   NamedDecl *PrevDecl = nullptr;
12995   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12996   LookupName(Previous, S);
12997   switch (Previous.getResultKind()) {
12998     case LookupResult::Found:
12999     case LookupResult::FoundUnresolvedValue:
13000       PrevDecl = Previous.getAsSingle<NamedDecl>();
13001       break;
13002 
13003     case LookupResult::FoundOverloaded:
13004       PrevDecl = Previous.getRepresentativeDecl();
13005       break;
13006 
13007     case LookupResult::NotFound:
13008     case LookupResult::NotFoundInCurrentInstantiation:
13009     case LookupResult::Ambiguous:
13010       break;
13011   }
13012   Previous.suppressDiagnostics();
13013 
13014   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13015     // Maybe we will complain about the shadowed template parameter.
13016     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13017     // Just pretend that we didn't see the previous declaration.
13018     PrevDecl = nullptr;
13019   }
13020 
13021   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13022     PrevDecl = nullptr;
13023 
13024   bool Mutable
13025     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13026   SourceLocation TSSL = D.getLocStart();
13027   FieldDecl *NewFD
13028     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13029                      TSSL, AS, PrevDecl, &D);
13030 
13031   if (NewFD->isInvalidDecl())
13032     Record->setInvalidDecl();
13033 
13034   if (D.getDeclSpec().isModulePrivateSpecified())
13035     NewFD->setModulePrivate();
13036 
13037   if (NewFD->isInvalidDecl() && PrevDecl) {
13038     // Don't introduce NewFD into scope; there's already something
13039     // with the same name in the same scope.
13040   } else if (II) {
13041     PushOnScopeChains(NewFD, S);
13042   } else
13043     Record->addDecl(NewFD);
13044 
13045   return NewFD;
13046 }
13047 
13048 /// \brief Build a new FieldDecl and check its well-formedness.
13049 ///
13050 /// This routine builds a new FieldDecl given the fields name, type,
13051 /// record, etc. \p PrevDecl should refer to any previous declaration
13052 /// with the same name and in the same scope as the field to be
13053 /// created.
13054 ///
13055 /// \returns a new FieldDecl.
13056 ///
13057 /// \todo The Declarator argument is a hack. It will be removed once
13058 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13059                                 TypeSourceInfo *TInfo,
13060                                 RecordDecl *Record, SourceLocation Loc,
13061                                 bool Mutable, Expr *BitWidth,
13062                                 InClassInitStyle InitStyle,
13063                                 SourceLocation TSSL,
13064                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13065                                 Declarator *D) {
13066   IdentifierInfo *II = Name.getAsIdentifierInfo();
13067   bool InvalidDecl = false;
13068   if (D) InvalidDecl = D->isInvalidType();
13069 
13070   // If we receive a broken type, recover by assuming 'int' and
13071   // marking this declaration as invalid.
13072   if (T.isNull()) {
13073     InvalidDecl = true;
13074     T = Context.IntTy;
13075   }
13076 
13077   QualType EltTy = Context.getBaseElementType(T);
13078   if (!EltTy->isDependentType()) {
13079     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13080       // Fields of incomplete type force their record to be invalid.
13081       Record->setInvalidDecl();
13082       InvalidDecl = true;
13083     } else {
13084       NamedDecl *Def;
13085       EltTy->isIncompleteType(&Def);
13086       if (Def && Def->isInvalidDecl()) {
13087         Record->setInvalidDecl();
13088         InvalidDecl = true;
13089       }
13090     }
13091   }
13092 
13093   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13094   if (BitWidth && getLangOpts().OpenCL) {
13095     Diag(Loc, diag::err_opencl_bitfields);
13096     InvalidDecl = true;
13097   }
13098 
13099   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13100   // than a variably modified type.
13101   if (!InvalidDecl && T->isVariablyModifiedType()) {
13102     bool SizeIsNegative;
13103     llvm::APSInt Oversized;
13104 
13105     TypeSourceInfo *FixedTInfo =
13106       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13107                                                     SizeIsNegative,
13108                                                     Oversized);
13109     if (FixedTInfo) {
13110       Diag(Loc, diag::warn_illegal_constant_array_size);
13111       TInfo = FixedTInfo;
13112       T = FixedTInfo->getType();
13113     } else {
13114       if (SizeIsNegative)
13115         Diag(Loc, diag::err_typecheck_negative_array_size);
13116       else if (Oversized.getBoolValue())
13117         Diag(Loc, diag::err_array_too_large)
13118           << Oversized.toString(10);
13119       else
13120         Diag(Loc, diag::err_typecheck_field_variable_size);
13121       InvalidDecl = true;
13122     }
13123   }
13124 
13125   // Fields can not have abstract class types
13126   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13127                                              diag::err_abstract_type_in_decl,
13128                                              AbstractFieldType))
13129     InvalidDecl = true;
13130 
13131   bool ZeroWidth = false;
13132   if (InvalidDecl)
13133     BitWidth = nullptr;
13134   // If this is declared as a bit-field, check the bit-field.
13135   if (BitWidth) {
13136     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13137                               &ZeroWidth).get();
13138     if (!BitWidth) {
13139       InvalidDecl = true;
13140       BitWidth = nullptr;
13141       ZeroWidth = false;
13142     }
13143   }
13144 
13145   // Check that 'mutable' is consistent with the type of the declaration.
13146   if (!InvalidDecl && Mutable) {
13147     unsigned DiagID = 0;
13148     if (T->isReferenceType())
13149       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13150                                         : diag::err_mutable_reference;
13151     else if (T.isConstQualified())
13152       DiagID = diag::err_mutable_const;
13153 
13154     if (DiagID) {
13155       SourceLocation ErrLoc = Loc;
13156       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13157         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13158       Diag(ErrLoc, DiagID);
13159       if (DiagID != diag::ext_mutable_reference) {
13160         Mutable = false;
13161         InvalidDecl = true;
13162       }
13163     }
13164   }
13165 
13166   // C++11 [class.union]p8 (DR1460):
13167   //   At most one variant member of a union may have a
13168   //   brace-or-equal-initializer.
13169   if (InitStyle != ICIS_NoInit)
13170     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13171 
13172   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13173                                        BitWidth, Mutable, InitStyle);
13174   if (InvalidDecl)
13175     NewFD->setInvalidDecl();
13176 
13177   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13178     Diag(Loc, diag::err_duplicate_member) << II;
13179     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13180     NewFD->setInvalidDecl();
13181   }
13182 
13183   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13184     if (Record->isUnion()) {
13185       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13186         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13187         if (RDecl->getDefinition()) {
13188           // C++ [class.union]p1: An object of a class with a non-trivial
13189           // constructor, a non-trivial copy constructor, a non-trivial
13190           // destructor, or a non-trivial copy assignment operator
13191           // cannot be a member of a union, nor can an array of such
13192           // objects.
13193           if (CheckNontrivialField(NewFD))
13194             NewFD->setInvalidDecl();
13195         }
13196       }
13197 
13198       // C++ [class.union]p1: If a union contains a member of reference type,
13199       // the program is ill-formed, except when compiling with MSVC extensions
13200       // enabled.
13201       if (EltTy->isReferenceType()) {
13202         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13203                                     diag::ext_union_member_of_reference_type :
13204                                     diag::err_union_member_of_reference_type)
13205           << NewFD->getDeclName() << EltTy;
13206         if (!getLangOpts().MicrosoftExt)
13207           NewFD->setInvalidDecl();
13208       }
13209     }
13210   }
13211 
13212   // FIXME: We need to pass in the attributes given an AST
13213   // representation, not a parser representation.
13214   if (D) {
13215     // FIXME: The current scope is almost... but not entirely... correct here.
13216     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13217 
13218     if (NewFD->hasAttrs())
13219       CheckAlignasUnderalignment(NewFD);
13220   }
13221 
13222   // In auto-retain/release, infer strong retension for fields of
13223   // retainable type.
13224   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13225     NewFD->setInvalidDecl();
13226 
13227   if (T.isObjCGCWeak())
13228     Diag(Loc, diag::warn_attribute_weak_on_field);
13229 
13230   NewFD->setAccess(AS);
13231   return NewFD;
13232 }
13233 
13234 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13235   assert(FD);
13236   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13237 
13238   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13239     return false;
13240 
13241   QualType EltTy = Context.getBaseElementType(FD->getType());
13242   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13243     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13244     if (RDecl->getDefinition()) {
13245       // We check for copy constructors before constructors
13246       // because otherwise we'll never get complaints about
13247       // copy constructors.
13248 
13249       CXXSpecialMember member = CXXInvalid;
13250       // We're required to check for any non-trivial constructors. Since the
13251       // implicit default constructor is suppressed if there are any
13252       // user-declared constructors, we just need to check that there is a
13253       // trivial default constructor and a trivial copy constructor. (We don't
13254       // worry about move constructors here, since this is a C++98 check.)
13255       if (RDecl->hasNonTrivialCopyConstructor())
13256         member = CXXCopyConstructor;
13257       else if (!RDecl->hasTrivialDefaultConstructor())
13258         member = CXXDefaultConstructor;
13259       else if (RDecl->hasNonTrivialCopyAssignment())
13260         member = CXXCopyAssignment;
13261       else if (RDecl->hasNonTrivialDestructor())
13262         member = CXXDestructor;
13263 
13264       if (member != CXXInvalid) {
13265         if (!getLangOpts().CPlusPlus11 &&
13266             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13267           // Objective-C++ ARC: it is an error to have a non-trivial field of
13268           // a union. However, system headers in Objective-C programs
13269           // occasionally have Objective-C lifetime objects within unions,
13270           // and rather than cause the program to fail, we make those
13271           // members unavailable.
13272           SourceLocation Loc = FD->getLocation();
13273           if (getSourceManager().isInSystemHeader(Loc)) {
13274             if (!FD->hasAttr<UnavailableAttr>())
13275               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13276                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13277             return false;
13278           }
13279         }
13280 
13281         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13282                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13283                diag::err_illegal_union_or_anon_struct_member)
13284           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13285         DiagnoseNontrivial(RDecl, member);
13286         return !getLangOpts().CPlusPlus11;
13287       }
13288     }
13289   }
13290 
13291   return false;
13292 }
13293 
13294 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13295 ///  AST enum value.
13296 static ObjCIvarDecl::AccessControl
13297 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13298   switch (ivarVisibility) {
13299   default: llvm_unreachable("Unknown visitibility kind");
13300   case tok::objc_private: return ObjCIvarDecl::Private;
13301   case tok::objc_public: return ObjCIvarDecl::Public;
13302   case tok::objc_protected: return ObjCIvarDecl::Protected;
13303   case tok::objc_package: return ObjCIvarDecl::Package;
13304   }
13305 }
13306 
13307 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13308 /// in order to create an IvarDecl object for it.
13309 Decl *Sema::ActOnIvar(Scope *S,
13310                                 SourceLocation DeclStart,
13311                                 Declarator &D, Expr *BitfieldWidth,
13312                                 tok::ObjCKeywordKind Visibility) {
13313 
13314   IdentifierInfo *II = D.getIdentifier();
13315   Expr *BitWidth = (Expr*)BitfieldWidth;
13316   SourceLocation Loc = DeclStart;
13317   if (II) Loc = D.getIdentifierLoc();
13318 
13319   // FIXME: Unnamed fields can be handled in various different ways, for
13320   // example, unnamed unions inject all members into the struct namespace!
13321 
13322   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13323   QualType T = TInfo->getType();
13324 
13325   if (BitWidth) {
13326     // 6.7.2.1p3, 6.7.2.1p4
13327     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13328     if (!BitWidth)
13329       D.setInvalidType();
13330   } else {
13331     // Not a bitfield.
13332 
13333     // validate II.
13334 
13335   }
13336   if (T->isReferenceType()) {
13337     Diag(Loc, diag::err_ivar_reference_type);
13338     D.setInvalidType();
13339   }
13340   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13341   // than a variably modified type.
13342   else if (T->isVariablyModifiedType()) {
13343     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13344     D.setInvalidType();
13345   }
13346 
13347   // Get the visibility (access control) for this ivar.
13348   ObjCIvarDecl::AccessControl ac =
13349     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13350                                         : ObjCIvarDecl::None;
13351   // Must set ivar's DeclContext to its enclosing interface.
13352   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13353   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13354     return nullptr;
13355   ObjCContainerDecl *EnclosingContext;
13356   if (ObjCImplementationDecl *IMPDecl =
13357       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13358     if (LangOpts.ObjCRuntime.isFragile()) {
13359     // Case of ivar declared in an implementation. Context is that of its class.
13360       EnclosingContext = IMPDecl->getClassInterface();
13361       assert(EnclosingContext && "Implementation has no class interface!");
13362     }
13363     else
13364       EnclosingContext = EnclosingDecl;
13365   } else {
13366     if (ObjCCategoryDecl *CDecl =
13367         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13368       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13369         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13370         return nullptr;
13371       }
13372     }
13373     EnclosingContext = EnclosingDecl;
13374   }
13375 
13376   // Construct the decl.
13377   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13378                                              DeclStart, Loc, II, T,
13379                                              TInfo, ac, (Expr *)BitfieldWidth);
13380 
13381   if (II) {
13382     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13383                                            ForRedeclaration);
13384     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13385         && !isa<TagDecl>(PrevDecl)) {
13386       Diag(Loc, diag::err_duplicate_member) << II;
13387       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13388       NewID->setInvalidDecl();
13389     }
13390   }
13391 
13392   // Process attributes attached to the ivar.
13393   ProcessDeclAttributes(S, NewID, D);
13394 
13395   if (D.isInvalidType())
13396     NewID->setInvalidDecl();
13397 
13398   // In ARC, infer 'retaining' for ivars of retainable type.
13399   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13400     NewID->setInvalidDecl();
13401 
13402   if (D.getDeclSpec().isModulePrivateSpecified())
13403     NewID->setModulePrivate();
13404 
13405   if (II) {
13406     // FIXME: When interfaces are DeclContexts, we'll need to add
13407     // these to the interface.
13408     S->AddDecl(NewID);
13409     IdResolver.AddDecl(NewID);
13410   }
13411 
13412   if (LangOpts.ObjCRuntime.isNonFragile() &&
13413       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13414     Diag(Loc, diag::warn_ivars_in_interface);
13415 
13416   return NewID;
13417 }
13418 
13419 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13420 /// class and class extensions. For every class \@interface and class
13421 /// extension \@interface, if the last ivar is a bitfield of any type,
13422 /// then add an implicit `char :0` ivar to the end of that interface.
13423 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13424                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13425   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13426     return;
13427 
13428   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13429   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13430 
13431   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13432     return;
13433   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13434   if (!ID) {
13435     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13436       if (!CD->IsClassExtension())
13437         return;
13438     }
13439     // No need to add this to end of @implementation.
13440     else
13441       return;
13442   }
13443   // All conditions are met. Add a new bitfield to the tail end of ivars.
13444   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13445   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13446 
13447   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13448                               DeclLoc, DeclLoc, nullptr,
13449                               Context.CharTy,
13450                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13451                                                                DeclLoc),
13452                               ObjCIvarDecl::Private, BW,
13453                               true);
13454   AllIvarDecls.push_back(Ivar);
13455 }
13456 
13457 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13458                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13459                        SourceLocation RBrac, AttributeList *Attr) {
13460   assert(EnclosingDecl && "missing record or interface decl");
13461 
13462   // If this is an Objective-C @implementation or category and we have
13463   // new fields here we should reset the layout of the interface since
13464   // it will now change.
13465   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13466     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13467     switch (DC->getKind()) {
13468     default: break;
13469     case Decl::ObjCCategory:
13470       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13471       break;
13472     case Decl::ObjCImplementation:
13473       Context.
13474         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13475       break;
13476     }
13477   }
13478 
13479   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13480 
13481   // Start counting up the number of named members; make sure to include
13482   // members of anonymous structs and unions in the total.
13483   unsigned NumNamedMembers = 0;
13484   if (Record) {
13485     for (const auto *I : Record->decls()) {
13486       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13487         if (IFD->getDeclName())
13488           ++NumNamedMembers;
13489     }
13490   }
13491 
13492   // Verify that all the fields are okay.
13493   SmallVector<FieldDecl*, 32> RecFields;
13494 
13495   bool ARCErrReported = false;
13496   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13497        i != end; ++i) {
13498     FieldDecl *FD = cast<FieldDecl>(*i);
13499 
13500     // Get the type for the field.
13501     const Type *FDTy = FD->getType().getTypePtr();
13502 
13503     if (!FD->isAnonymousStructOrUnion()) {
13504       // Remember all fields written by the user.
13505       RecFields.push_back(FD);
13506     }
13507 
13508     // If the field is already invalid for some reason, don't emit more
13509     // diagnostics about it.
13510     if (FD->isInvalidDecl()) {
13511       EnclosingDecl->setInvalidDecl();
13512       continue;
13513     }
13514 
13515     // C99 6.7.2.1p2:
13516     //   A structure or union shall not contain a member with
13517     //   incomplete or function type (hence, a structure shall not
13518     //   contain an instance of itself, but may contain a pointer to
13519     //   an instance of itself), except that the last member of a
13520     //   structure with more than one named member may have incomplete
13521     //   array type; such a structure (and any union containing,
13522     //   possibly recursively, a member that is such a structure)
13523     //   shall not be a member of a structure or an element of an
13524     //   array.
13525     if (FDTy->isFunctionType()) {
13526       // Field declared as a function.
13527       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13528         << FD->getDeclName();
13529       FD->setInvalidDecl();
13530       EnclosingDecl->setInvalidDecl();
13531       continue;
13532     } else if (FDTy->isIncompleteArrayType() && Record &&
13533                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13534                 ((getLangOpts().MicrosoftExt ||
13535                   getLangOpts().CPlusPlus) &&
13536                  (i + 1 == Fields.end() || Record->isUnion())))) {
13537       // Flexible array member.
13538       // Microsoft and g++ is more permissive regarding flexible array.
13539       // It will accept flexible array in union and also
13540       // as the sole element of a struct/class.
13541       unsigned DiagID = 0;
13542       if (Record->isUnion())
13543         DiagID = getLangOpts().MicrosoftExt
13544                      ? diag::ext_flexible_array_union_ms
13545                      : getLangOpts().CPlusPlus
13546                            ? diag::ext_flexible_array_union_gnu
13547                            : diag::err_flexible_array_union;
13548       else if (Fields.size() == 1)
13549         DiagID = getLangOpts().MicrosoftExt
13550                      ? diag::ext_flexible_array_empty_aggregate_ms
13551                      : getLangOpts().CPlusPlus
13552                            ? diag::ext_flexible_array_empty_aggregate_gnu
13553                            : NumNamedMembers < 1
13554                                  ? diag::err_flexible_array_empty_aggregate
13555                                  : 0;
13556 
13557       if (DiagID)
13558         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13559                                         << Record->getTagKind();
13560       // While the layout of types that contain virtual bases is not specified
13561       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13562       // virtual bases after the derived members.  This would make a flexible
13563       // array member declared at the end of an object not adjacent to the end
13564       // of the type.
13565       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13566         if (RD->getNumVBases() != 0)
13567           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13568             << FD->getDeclName() << Record->getTagKind();
13569       if (!getLangOpts().C99)
13570         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13571           << FD->getDeclName() << Record->getTagKind();
13572 
13573       // If the element type has a non-trivial destructor, we would not
13574       // implicitly destroy the elements, so disallow it for now.
13575       //
13576       // FIXME: GCC allows this. We should probably either implicitly delete
13577       // the destructor of the containing class, or just allow this.
13578       QualType BaseElem = Context.getBaseElementType(FD->getType());
13579       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13580         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13581           << FD->getDeclName() << FD->getType();
13582         FD->setInvalidDecl();
13583         EnclosingDecl->setInvalidDecl();
13584         continue;
13585       }
13586       // Okay, we have a legal flexible array member at the end of the struct.
13587       Record->setHasFlexibleArrayMember(true);
13588     } else if (!FDTy->isDependentType() &&
13589                RequireCompleteType(FD->getLocation(), FD->getType(),
13590                                    diag::err_field_incomplete)) {
13591       // Incomplete type
13592       FD->setInvalidDecl();
13593       EnclosingDecl->setInvalidDecl();
13594       continue;
13595     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13596       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13597         // A type which contains a flexible array member is considered to be a
13598         // flexible array member.
13599         Record->setHasFlexibleArrayMember(true);
13600         if (!Record->isUnion()) {
13601           // If this is a struct/class and this is not the last element, reject
13602           // it.  Note that GCC supports variable sized arrays in the middle of
13603           // structures.
13604           if (i + 1 != Fields.end())
13605             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13606               << FD->getDeclName() << FD->getType();
13607           else {
13608             // We support flexible arrays at the end of structs in
13609             // other structs as an extension.
13610             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13611               << FD->getDeclName();
13612           }
13613         }
13614       }
13615       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13616           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13617                                  diag::err_abstract_type_in_decl,
13618                                  AbstractIvarType)) {
13619         // Ivars can not have abstract class types
13620         FD->setInvalidDecl();
13621       }
13622       if (Record && FDTTy->getDecl()->hasObjectMember())
13623         Record->setHasObjectMember(true);
13624       if (Record && FDTTy->getDecl()->hasVolatileMember())
13625         Record->setHasVolatileMember(true);
13626     } else if (FDTy->isObjCObjectType()) {
13627       /// A field cannot be an Objective-c object
13628       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13629         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13630       QualType T = Context.getObjCObjectPointerType(FD->getType());
13631       FD->setType(T);
13632     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13633                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13634       // It's an error in ARC if a field has lifetime.
13635       // We don't want to report this in a system header, though,
13636       // so we just make the field unavailable.
13637       // FIXME: that's really not sufficient; we need to make the type
13638       // itself invalid to, say, initialize or copy.
13639       QualType T = FD->getType();
13640       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13641       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13642         SourceLocation loc = FD->getLocation();
13643         if (getSourceManager().isInSystemHeader(loc)) {
13644           if (!FD->hasAttr<UnavailableAttr>()) {
13645             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13646                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13647           }
13648         } else {
13649           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13650             << T->isBlockPointerType() << Record->getTagKind();
13651         }
13652         ARCErrReported = true;
13653       }
13654     } else if (getLangOpts().ObjC1 &&
13655                getLangOpts().getGC() != LangOptions::NonGC &&
13656                Record && !Record->hasObjectMember()) {
13657       if (FD->getType()->isObjCObjectPointerType() ||
13658           FD->getType().isObjCGCStrong())
13659         Record->setHasObjectMember(true);
13660       else if (Context.getAsArrayType(FD->getType())) {
13661         QualType BaseType = Context.getBaseElementType(FD->getType());
13662         if (BaseType->isRecordType() &&
13663             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13664           Record->setHasObjectMember(true);
13665         else if (BaseType->isObjCObjectPointerType() ||
13666                  BaseType.isObjCGCStrong())
13667                Record->setHasObjectMember(true);
13668       }
13669     }
13670     if (Record && FD->getType().isVolatileQualified())
13671       Record->setHasVolatileMember(true);
13672     // Keep track of the number of named members.
13673     if (FD->getIdentifier())
13674       ++NumNamedMembers;
13675   }
13676 
13677   // Okay, we successfully defined 'Record'.
13678   if (Record) {
13679     bool Completed = false;
13680     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13681       if (!CXXRecord->isInvalidDecl()) {
13682         // Set access bits correctly on the directly-declared conversions.
13683         for (CXXRecordDecl::conversion_iterator
13684                I = CXXRecord->conversion_begin(),
13685                E = CXXRecord->conversion_end(); I != E; ++I)
13686           I.setAccess((*I)->getAccess());
13687 
13688         if (!CXXRecord->isDependentType()) {
13689           if (CXXRecord->hasUserDeclaredDestructor()) {
13690             // Adjust user-defined destructor exception spec.
13691             if (getLangOpts().CPlusPlus11)
13692               AdjustDestructorExceptionSpec(CXXRecord,
13693                                             CXXRecord->getDestructor());
13694           }
13695 
13696           // Add any implicitly-declared members to this class.
13697           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13698 
13699           // If we have virtual base classes, we may end up finding multiple
13700           // final overriders for a given virtual function. Check for this
13701           // problem now.
13702           if (CXXRecord->getNumVBases()) {
13703             CXXFinalOverriderMap FinalOverriders;
13704             CXXRecord->getFinalOverriders(FinalOverriders);
13705 
13706             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13707                                              MEnd = FinalOverriders.end();
13708                  M != MEnd; ++M) {
13709               for (OverridingMethods::iterator SO = M->second.begin(),
13710                                             SOEnd = M->second.end();
13711                    SO != SOEnd; ++SO) {
13712                 assert(SO->second.size() > 0 &&
13713                        "Virtual function without overridding functions?");
13714                 if (SO->second.size() == 1)
13715                   continue;
13716 
13717                 // C++ [class.virtual]p2:
13718                 //   In a derived class, if a virtual member function of a base
13719                 //   class subobject has more than one final overrider the
13720                 //   program is ill-formed.
13721                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13722                   << (const NamedDecl *)M->first << Record;
13723                 Diag(M->first->getLocation(),
13724                      diag::note_overridden_virtual_function);
13725                 for (OverridingMethods::overriding_iterator
13726                           OM = SO->second.begin(),
13727                        OMEnd = SO->second.end();
13728                      OM != OMEnd; ++OM)
13729                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13730                     << (const NamedDecl *)M->first << OM->Method->getParent();
13731 
13732                 Record->setInvalidDecl();
13733               }
13734             }
13735             CXXRecord->completeDefinition(&FinalOverriders);
13736             Completed = true;
13737           }
13738         }
13739       }
13740     }
13741 
13742     if (!Completed)
13743       Record->completeDefinition();
13744 
13745     if (Record->hasAttrs()) {
13746       CheckAlignasUnderalignment(Record);
13747 
13748       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13749         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13750                                            IA->getRange(), IA->getBestCase(),
13751                                            IA->getSemanticSpelling());
13752     }
13753 
13754     // Check if the structure/union declaration is a type that can have zero
13755     // size in C. For C this is a language extension, for C++ it may cause
13756     // compatibility problems.
13757     bool CheckForZeroSize;
13758     if (!getLangOpts().CPlusPlus) {
13759       CheckForZeroSize = true;
13760     } else {
13761       // For C++ filter out types that cannot be referenced in C code.
13762       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13763       CheckForZeroSize =
13764           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13765           !CXXRecord->isDependentType() &&
13766           CXXRecord->isCLike();
13767     }
13768     if (CheckForZeroSize) {
13769       bool ZeroSize = true;
13770       bool IsEmpty = true;
13771       unsigned NonBitFields = 0;
13772       for (RecordDecl::field_iterator I = Record->field_begin(),
13773                                       E = Record->field_end();
13774            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13775         IsEmpty = false;
13776         if (I->isUnnamedBitfield()) {
13777           if (I->getBitWidthValue(Context) > 0)
13778             ZeroSize = false;
13779         } else {
13780           ++NonBitFields;
13781           QualType FieldType = I->getType();
13782           if (FieldType->isIncompleteType() ||
13783               !Context.getTypeSizeInChars(FieldType).isZero())
13784             ZeroSize = false;
13785         }
13786       }
13787 
13788       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13789       // allowed in C++, but warn if its declaration is inside
13790       // extern "C" block.
13791       if (ZeroSize) {
13792         Diag(RecLoc, getLangOpts().CPlusPlus ?
13793                          diag::warn_zero_size_struct_union_in_extern_c :
13794                          diag::warn_zero_size_struct_union_compat)
13795           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13796       }
13797 
13798       // Structs without named members are extension in C (C99 6.7.2.1p7),
13799       // but are accepted by GCC.
13800       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13801         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13802                                diag::ext_no_named_members_in_struct_union)
13803           << Record->isUnion();
13804       }
13805     }
13806   } else {
13807     ObjCIvarDecl **ClsFields =
13808       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13809     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13810       ID->setEndOfDefinitionLoc(RBrac);
13811       // Add ivar's to class's DeclContext.
13812       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13813         ClsFields[i]->setLexicalDeclContext(ID);
13814         ID->addDecl(ClsFields[i]);
13815       }
13816       // Must enforce the rule that ivars in the base classes may not be
13817       // duplicates.
13818       if (ID->getSuperClass())
13819         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13820     } else if (ObjCImplementationDecl *IMPDecl =
13821                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13822       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13823       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13824         // Ivar declared in @implementation never belongs to the implementation.
13825         // Only it is in implementation's lexical context.
13826         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13827       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13828       IMPDecl->setIvarLBraceLoc(LBrac);
13829       IMPDecl->setIvarRBraceLoc(RBrac);
13830     } else if (ObjCCategoryDecl *CDecl =
13831                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13832       // case of ivars in class extension; all other cases have been
13833       // reported as errors elsewhere.
13834       // FIXME. Class extension does not have a LocEnd field.
13835       // CDecl->setLocEnd(RBrac);
13836       // Add ivar's to class extension's DeclContext.
13837       // Diagnose redeclaration of private ivars.
13838       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13839       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13840         if (IDecl) {
13841           if (const ObjCIvarDecl *ClsIvar =
13842               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13843             Diag(ClsFields[i]->getLocation(),
13844                  diag::err_duplicate_ivar_declaration);
13845             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13846             continue;
13847           }
13848           for (const auto *Ext : IDecl->known_extensions()) {
13849             if (const ObjCIvarDecl *ClsExtIvar
13850                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13851               Diag(ClsFields[i]->getLocation(),
13852                    diag::err_duplicate_ivar_declaration);
13853               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13854               continue;
13855             }
13856           }
13857         }
13858         ClsFields[i]->setLexicalDeclContext(CDecl);
13859         CDecl->addDecl(ClsFields[i]);
13860       }
13861       CDecl->setIvarLBraceLoc(LBrac);
13862       CDecl->setIvarRBraceLoc(RBrac);
13863     }
13864   }
13865 
13866   if (Attr)
13867     ProcessDeclAttributeList(S, Record, Attr);
13868 }
13869 
13870 /// \brief Determine whether the given integral value is representable within
13871 /// the given type T.
13872 static bool isRepresentableIntegerValue(ASTContext &Context,
13873                                         llvm::APSInt &Value,
13874                                         QualType T) {
13875   assert(T->isIntegralType(Context) && "Integral type required!");
13876   unsigned BitWidth = Context.getIntWidth(T);
13877 
13878   if (Value.isUnsigned() || Value.isNonNegative()) {
13879     if (T->isSignedIntegerOrEnumerationType())
13880       --BitWidth;
13881     return Value.getActiveBits() <= BitWidth;
13882   }
13883   return Value.getMinSignedBits() <= BitWidth;
13884 }
13885 
13886 // \brief Given an integral type, return the next larger integral type
13887 // (or a NULL type of no such type exists).
13888 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13889   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13890   // enum checking below.
13891   assert(T->isIntegralType(Context) && "Integral type required!");
13892   const unsigned NumTypes = 4;
13893   QualType SignedIntegralTypes[NumTypes] = {
13894     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13895   };
13896   QualType UnsignedIntegralTypes[NumTypes] = {
13897     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13898     Context.UnsignedLongLongTy
13899   };
13900 
13901   unsigned BitWidth = Context.getTypeSize(T);
13902   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13903                                                         : UnsignedIntegralTypes;
13904   for (unsigned I = 0; I != NumTypes; ++I)
13905     if (Context.getTypeSize(Types[I]) > BitWidth)
13906       return Types[I];
13907 
13908   return QualType();
13909 }
13910 
13911 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13912                                           EnumConstantDecl *LastEnumConst,
13913                                           SourceLocation IdLoc,
13914                                           IdentifierInfo *Id,
13915                                           Expr *Val) {
13916   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13917   llvm::APSInt EnumVal(IntWidth);
13918   QualType EltTy;
13919 
13920   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13921     Val = nullptr;
13922 
13923   if (Val)
13924     Val = DefaultLvalueConversion(Val).get();
13925 
13926   if (Val) {
13927     if (Enum->isDependentType() || Val->isTypeDependent())
13928       EltTy = Context.DependentTy;
13929     else {
13930       SourceLocation ExpLoc;
13931       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13932           !getLangOpts().MSVCCompat) {
13933         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13934         // constant-expression in the enumerator-definition shall be a converted
13935         // constant expression of the underlying type.
13936         EltTy = Enum->getIntegerType();
13937         ExprResult Converted =
13938           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13939                                            CCEK_Enumerator);
13940         if (Converted.isInvalid())
13941           Val = nullptr;
13942         else
13943           Val = Converted.get();
13944       } else if (!Val->isValueDependent() &&
13945                  !(Val = VerifyIntegerConstantExpression(Val,
13946                                                          &EnumVal).get())) {
13947         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13948       } else {
13949         if (Enum->isFixed()) {
13950           EltTy = Enum->getIntegerType();
13951 
13952           // In Obj-C and Microsoft mode, require the enumeration value to be
13953           // representable in the underlying type of the enumeration. In C++11,
13954           // we perform a non-narrowing conversion as part of converted constant
13955           // expression checking.
13956           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13957             if (getLangOpts().MSVCCompat) {
13958               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13959               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13960             } else
13961               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13962           } else
13963             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13964         } else if (getLangOpts().CPlusPlus) {
13965           // C++11 [dcl.enum]p5:
13966           //   If the underlying type is not fixed, the type of each enumerator
13967           //   is the type of its initializing value:
13968           //     - If an initializer is specified for an enumerator, the
13969           //       initializing value has the same type as the expression.
13970           EltTy = Val->getType();
13971         } else {
13972           // C99 6.7.2.2p2:
13973           //   The expression that defines the value of an enumeration constant
13974           //   shall be an integer constant expression that has a value
13975           //   representable as an int.
13976 
13977           // Complain if the value is not representable in an int.
13978           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13979             Diag(IdLoc, diag::ext_enum_value_not_int)
13980               << EnumVal.toString(10) << Val->getSourceRange()
13981               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13982           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13983             // Force the type of the expression to 'int'.
13984             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13985           }
13986           EltTy = Val->getType();
13987         }
13988       }
13989     }
13990   }
13991 
13992   if (!Val) {
13993     if (Enum->isDependentType())
13994       EltTy = Context.DependentTy;
13995     else if (!LastEnumConst) {
13996       // C++0x [dcl.enum]p5:
13997       //   If the underlying type is not fixed, the type of each enumerator
13998       //   is the type of its initializing value:
13999       //     - If no initializer is specified for the first enumerator, the
14000       //       initializing value has an unspecified integral type.
14001       //
14002       // GCC uses 'int' for its unspecified integral type, as does
14003       // C99 6.7.2.2p3.
14004       if (Enum->isFixed()) {
14005         EltTy = Enum->getIntegerType();
14006       }
14007       else {
14008         EltTy = Context.IntTy;
14009       }
14010     } else {
14011       // Assign the last value + 1.
14012       EnumVal = LastEnumConst->getInitVal();
14013       ++EnumVal;
14014       EltTy = LastEnumConst->getType();
14015 
14016       // Check for overflow on increment.
14017       if (EnumVal < LastEnumConst->getInitVal()) {
14018         // C++0x [dcl.enum]p5:
14019         //   If the underlying type is not fixed, the type of each enumerator
14020         //   is the type of its initializing value:
14021         //
14022         //     - Otherwise the type of the initializing value is the same as
14023         //       the type of the initializing value of the preceding enumerator
14024         //       unless the incremented value is not representable in that type,
14025         //       in which case the type is an unspecified integral type
14026         //       sufficient to contain the incremented value. If no such type
14027         //       exists, the program is ill-formed.
14028         QualType T = getNextLargerIntegralType(Context, EltTy);
14029         if (T.isNull() || Enum->isFixed()) {
14030           // There is no integral type larger enough to represent this
14031           // value. Complain, then allow the value to wrap around.
14032           EnumVal = LastEnumConst->getInitVal();
14033           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14034           ++EnumVal;
14035           if (Enum->isFixed())
14036             // When the underlying type is fixed, this is ill-formed.
14037             Diag(IdLoc, diag::err_enumerator_wrapped)
14038               << EnumVal.toString(10)
14039               << EltTy;
14040           else
14041             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14042               << EnumVal.toString(10);
14043         } else {
14044           EltTy = T;
14045         }
14046 
14047         // Retrieve the last enumerator's value, extent that type to the
14048         // type that is supposed to be large enough to represent the incremented
14049         // value, then increment.
14050         EnumVal = LastEnumConst->getInitVal();
14051         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14052         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14053         ++EnumVal;
14054 
14055         // If we're not in C++, diagnose the overflow of enumerator values,
14056         // which in C99 means that the enumerator value is not representable in
14057         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14058         // permits enumerator values that are representable in some larger
14059         // integral type.
14060         if (!getLangOpts().CPlusPlus && !T.isNull())
14061           Diag(IdLoc, diag::warn_enum_value_overflow);
14062       } else if (!getLangOpts().CPlusPlus &&
14063                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14064         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14065         Diag(IdLoc, diag::ext_enum_value_not_int)
14066           << EnumVal.toString(10) << 1;
14067       }
14068     }
14069   }
14070 
14071   if (!EltTy->isDependentType()) {
14072     // Make the enumerator value match the signedness and size of the
14073     // enumerator's type.
14074     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14075     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14076   }
14077 
14078   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14079                                   Val, EnumVal);
14080 }
14081 
14082 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14083                                                 SourceLocation IILoc) {
14084   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14085       !getLangOpts().CPlusPlus)
14086     return SkipBodyInfo();
14087 
14088   // We have an anonymous enum definition. Look up the first enumerator to
14089   // determine if we should merge the definition with an existing one and
14090   // skip the body.
14091   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14092                                          ForRedeclaration);
14093   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14094   if (!PrevECD)
14095     return SkipBodyInfo();
14096 
14097   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14098   NamedDecl *Hidden;
14099   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14100     SkipBodyInfo Skip;
14101     Skip.Previous = Hidden;
14102     return Skip;
14103   }
14104 
14105   return SkipBodyInfo();
14106 }
14107 
14108 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14109                               SourceLocation IdLoc, IdentifierInfo *Id,
14110                               AttributeList *Attr,
14111                               SourceLocation EqualLoc, Expr *Val) {
14112   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14113   EnumConstantDecl *LastEnumConst =
14114     cast_or_null<EnumConstantDecl>(lastEnumConst);
14115 
14116   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14117   // we find one that is.
14118   S = getNonFieldDeclScope(S);
14119 
14120   // Verify that there isn't already something declared with this name in this
14121   // scope.
14122   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14123                                          ForRedeclaration);
14124   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14125     // Maybe we will complain about the shadowed template parameter.
14126     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14127     // Just pretend that we didn't see the previous declaration.
14128     PrevDecl = nullptr;
14129   }
14130 
14131   // C++ [class.mem]p15:
14132   // If T is the name of a class, then each of the following shall have a name
14133   // different from T:
14134   // - every enumerator of every member of class T that is an unscoped
14135   // enumerated type
14136   if (!TheEnumDecl->isScoped())
14137     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14138                             DeclarationNameInfo(Id, IdLoc));
14139 
14140   EnumConstantDecl *New =
14141     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14142   if (!New)
14143     return nullptr;
14144 
14145   if (PrevDecl) {
14146     // When in C++, we may get a TagDecl with the same name; in this case the
14147     // enum constant will 'hide' the tag.
14148     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14149            "Received TagDecl when not in C++!");
14150     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14151         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14152       if (isa<EnumConstantDecl>(PrevDecl))
14153         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14154       else
14155         Diag(IdLoc, diag::err_redefinition) << Id;
14156       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14157       return nullptr;
14158     }
14159   }
14160 
14161   // Process attributes.
14162   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14163 
14164   // Register this decl in the current scope stack.
14165   New->setAccess(TheEnumDecl->getAccess());
14166   PushOnScopeChains(New, S);
14167 
14168   ActOnDocumentableDecl(New);
14169 
14170   return New;
14171 }
14172 
14173 // Returns true when the enum initial expression does not trigger the
14174 // duplicate enum warning.  A few common cases are exempted as follows:
14175 // Element2 = Element1
14176 // Element2 = Element1 + 1
14177 // Element2 = Element1 - 1
14178 // Where Element2 and Element1 are from the same enum.
14179 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14180   Expr *InitExpr = ECD->getInitExpr();
14181   if (!InitExpr)
14182     return true;
14183   InitExpr = InitExpr->IgnoreImpCasts();
14184 
14185   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14186     if (!BO->isAdditiveOp())
14187       return true;
14188     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14189     if (!IL)
14190       return true;
14191     if (IL->getValue() != 1)
14192       return true;
14193 
14194     InitExpr = BO->getLHS();
14195   }
14196 
14197   // This checks if the elements are from the same enum.
14198   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14199   if (!DRE)
14200     return true;
14201 
14202   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14203   if (!EnumConstant)
14204     return true;
14205 
14206   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14207       Enum)
14208     return true;
14209 
14210   return false;
14211 }
14212 
14213 namespace {
14214 struct DupKey {
14215   int64_t val;
14216   bool isTombstoneOrEmptyKey;
14217   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14218     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14219 };
14220 
14221 static DupKey GetDupKey(const llvm::APSInt& Val) {
14222   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14223                 false);
14224 }
14225 
14226 struct DenseMapInfoDupKey {
14227   static DupKey getEmptyKey() { return DupKey(0, true); }
14228   static DupKey getTombstoneKey() { return DupKey(1, true); }
14229   static unsigned getHashValue(const DupKey Key) {
14230     return (unsigned)(Key.val * 37);
14231   }
14232   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14233     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14234            LHS.val == RHS.val;
14235   }
14236 };
14237 } // end anonymous namespace
14238 
14239 // Emits a warning when an element is implicitly set a value that
14240 // a previous element has already been set to.
14241 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14242                                         EnumDecl *Enum,
14243                                         QualType EnumType) {
14244   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14245     return;
14246   // Avoid anonymous enums
14247   if (!Enum->getIdentifier())
14248     return;
14249 
14250   // Only check for small enums.
14251   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14252     return;
14253 
14254   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14255   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14256 
14257   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14258   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14259           ValueToVectorMap;
14260 
14261   DuplicatesVector DupVector;
14262   ValueToVectorMap EnumMap;
14263 
14264   // Populate the EnumMap with all values represented by enum constants without
14265   // an initialier.
14266   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14267     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14268 
14269     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14270     // this constant.  Skip this enum since it may be ill-formed.
14271     if (!ECD) {
14272       return;
14273     }
14274 
14275     if (ECD->getInitExpr())
14276       continue;
14277 
14278     DupKey Key = GetDupKey(ECD->getInitVal());
14279     DeclOrVector &Entry = EnumMap[Key];
14280 
14281     // First time encountering this value.
14282     if (Entry.isNull())
14283       Entry = ECD;
14284   }
14285 
14286   // Create vectors for any values that has duplicates.
14287   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14288     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14289     if (!ValidDuplicateEnum(ECD, Enum))
14290       continue;
14291 
14292     DupKey Key = GetDupKey(ECD->getInitVal());
14293 
14294     DeclOrVector& Entry = EnumMap[Key];
14295     if (Entry.isNull())
14296       continue;
14297 
14298     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14299       // Ensure constants are different.
14300       if (D == ECD)
14301         continue;
14302 
14303       // Create new vector and push values onto it.
14304       ECDVector *Vec = new ECDVector();
14305       Vec->push_back(D);
14306       Vec->push_back(ECD);
14307 
14308       // Update entry to point to the duplicates vector.
14309       Entry = Vec;
14310 
14311       // Store the vector somewhere we can consult later for quick emission of
14312       // diagnostics.
14313       DupVector.push_back(Vec);
14314       continue;
14315     }
14316 
14317     ECDVector *Vec = Entry.get<ECDVector*>();
14318     // Make sure constants are not added more than once.
14319     if (*Vec->begin() == ECD)
14320       continue;
14321 
14322     Vec->push_back(ECD);
14323   }
14324 
14325   // Emit diagnostics.
14326   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14327                                   DupVectorEnd = DupVector.end();
14328        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14329     ECDVector *Vec = *DupVectorIter;
14330     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14331 
14332     // Emit warning for one enum constant.
14333     ECDVector::iterator I = Vec->begin();
14334     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14335       << (*I)->getName() << (*I)->getInitVal().toString(10)
14336       << (*I)->getSourceRange();
14337     ++I;
14338 
14339     // Emit one note for each of the remaining enum constants with
14340     // the same value.
14341     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14342       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14343         << (*I)->getName() << (*I)->getInitVal().toString(10)
14344         << (*I)->getSourceRange();
14345     delete Vec;
14346   }
14347 }
14348 
14349 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14350                              bool AllowMask) const {
14351   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14352   assert(ED->isCompleteDefinition() && "expected enum definition");
14353 
14354   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14355   llvm::APInt &FlagBits = R.first->second;
14356 
14357   if (R.second) {
14358     for (auto *E : ED->enumerators()) {
14359       const auto &EVal = E->getInitVal();
14360       // Only single-bit enumerators introduce new flag values.
14361       if (EVal.isPowerOf2())
14362         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14363     }
14364   }
14365 
14366   // A value is in a flag enum if either its bits are a subset of the enum's
14367   // flag bits (the first condition) or we are allowing masks and the same is
14368   // true of its complement (the second condition). When masks are allowed, we
14369   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14370   //
14371   // While it's true that any value could be used as a mask, the assumption is
14372   // that a mask will have all of the insignificant bits set. Anything else is
14373   // likely a logic error.
14374   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14375   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14376 }
14377 
14378 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14379                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14380                          ArrayRef<Decl *> Elements,
14381                          Scope *S, AttributeList *Attr) {
14382   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14383   QualType EnumType = Context.getTypeDeclType(Enum);
14384 
14385   if (Attr)
14386     ProcessDeclAttributeList(S, Enum, Attr);
14387 
14388   if (Enum->isDependentType()) {
14389     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14390       EnumConstantDecl *ECD =
14391         cast_or_null<EnumConstantDecl>(Elements[i]);
14392       if (!ECD) continue;
14393 
14394       ECD->setType(EnumType);
14395     }
14396 
14397     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14398     return;
14399   }
14400 
14401   // TODO: If the result value doesn't fit in an int, it must be a long or long
14402   // long value.  ISO C does not support this, but GCC does as an extension,
14403   // emit a warning.
14404   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14405   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14406   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14407 
14408   // Verify that all the values are okay, compute the size of the values, and
14409   // reverse the list.
14410   unsigned NumNegativeBits = 0;
14411   unsigned NumPositiveBits = 0;
14412 
14413   // Keep track of whether all elements have type int.
14414   bool AllElementsInt = true;
14415 
14416   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14417     EnumConstantDecl *ECD =
14418       cast_or_null<EnumConstantDecl>(Elements[i]);
14419     if (!ECD) continue;  // Already issued a diagnostic.
14420 
14421     const llvm::APSInt &InitVal = ECD->getInitVal();
14422 
14423     // Keep track of the size of positive and negative values.
14424     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14425       NumPositiveBits = std::max(NumPositiveBits,
14426                                  (unsigned)InitVal.getActiveBits());
14427     else
14428       NumNegativeBits = std::max(NumNegativeBits,
14429                                  (unsigned)InitVal.getMinSignedBits());
14430 
14431     // Keep track of whether every enum element has type int (very commmon).
14432     if (AllElementsInt)
14433       AllElementsInt = ECD->getType() == Context.IntTy;
14434   }
14435 
14436   // Figure out the type that should be used for this enum.
14437   QualType BestType;
14438   unsigned BestWidth;
14439 
14440   // C++0x N3000 [conv.prom]p3:
14441   //   An rvalue of an unscoped enumeration type whose underlying
14442   //   type is not fixed can be converted to an rvalue of the first
14443   //   of the following types that can represent all the values of
14444   //   the enumeration: int, unsigned int, long int, unsigned long
14445   //   int, long long int, or unsigned long long int.
14446   // C99 6.4.4.3p2:
14447   //   An identifier declared as an enumeration constant has type int.
14448   // The C99 rule is modified by a gcc extension
14449   QualType BestPromotionType;
14450 
14451   bool Packed = Enum->hasAttr<PackedAttr>();
14452   // -fshort-enums is the equivalent to specifying the packed attribute on all
14453   // enum definitions.
14454   if (LangOpts.ShortEnums)
14455     Packed = true;
14456 
14457   if (Enum->isFixed()) {
14458     BestType = Enum->getIntegerType();
14459     if (BestType->isPromotableIntegerType())
14460       BestPromotionType = Context.getPromotedIntegerType(BestType);
14461     else
14462       BestPromotionType = BestType;
14463 
14464     BestWidth = Context.getIntWidth(BestType);
14465   }
14466   else if (NumNegativeBits) {
14467     // If there is a negative value, figure out the smallest integer type (of
14468     // int/long/longlong) that fits.
14469     // If it's packed, check also if it fits a char or a short.
14470     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14471       BestType = Context.SignedCharTy;
14472       BestWidth = CharWidth;
14473     } else if (Packed && NumNegativeBits <= ShortWidth &&
14474                NumPositiveBits < ShortWidth) {
14475       BestType = Context.ShortTy;
14476       BestWidth = ShortWidth;
14477     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14478       BestType = Context.IntTy;
14479       BestWidth = IntWidth;
14480     } else {
14481       BestWidth = Context.getTargetInfo().getLongWidth();
14482 
14483       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14484         BestType = Context.LongTy;
14485       } else {
14486         BestWidth = Context.getTargetInfo().getLongLongWidth();
14487 
14488         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14489           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14490         BestType = Context.LongLongTy;
14491       }
14492     }
14493     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14494   } else {
14495     // If there is no negative value, figure out the smallest type that fits
14496     // all of the enumerator values.
14497     // If it's packed, check also if it fits a char or a short.
14498     if (Packed && NumPositiveBits <= CharWidth) {
14499       BestType = Context.UnsignedCharTy;
14500       BestPromotionType = Context.IntTy;
14501       BestWidth = CharWidth;
14502     } else if (Packed && NumPositiveBits <= ShortWidth) {
14503       BestType = Context.UnsignedShortTy;
14504       BestPromotionType = Context.IntTy;
14505       BestWidth = ShortWidth;
14506     } else if (NumPositiveBits <= IntWidth) {
14507       BestType = Context.UnsignedIntTy;
14508       BestWidth = IntWidth;
14509       BestPromotionType
14510         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14511                            ? Context.UnsignedIntTy : Context.IntTy;
14512     } else if (NumPositiveBits <=
14513                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14514       BestType = Context.UnsignedLongTy;
14515       BestPromotionType
14516         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14517                            ? Context.UnsignedLongTy : Context.LongTy;
14518     } else {
14519       BestWidth = Context.getTargetInfo().getLongLongWidth();
14520       assert(NumPositiveBits <= BestWidth &&
14521              "How could an initializer get larger than ULL?");
14522       BestType = Context.UnsignedLongLongTy;
14523       BestPromotionType
14524         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14525                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14526     }
14527   }
14528 
14529   // Loop over all of the enumerator constants, changing their types to match
14530   // the type of the enum if needed.
14531   for (auto *D : Elements) {
14532     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14533     if (!ECD) continue;  // Already issued a diagnostic.
14534 
14535     // Standard C says the enumerators have int type, but we allow, as an
14536     // extension, the enumerators to be larger than int size.  If each
14537     // enumerator value fits in an int, type it as an int, otherwise type it the
14538     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14539     // that X has type 'int', not 'unsigned'.
14540 
14541     // Determine whether the value fits into an int.
14542     llvm::APSInt InitVal = ECD->getInitVal();
14543 
14544     // If it fits into an integer type, force it.  Otherwise force it to match
14545     // the enum decl type.
14546     QualType NewTy;
14547     unsigned NewWidth;
14548     bool NewSign;
14549     if (!getLangOpts().CPlusPlus &&
14550         !Enum->isFixed() &&
14551         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14552       NewTy = Context.IntTy;
14553       NewWidth = IntWidth;
14554       NewSign = true;
14555     } else if (ECD->getType() == BestType) {
14556       // Already the right type!
14557       if (getLangOpts().CPlusPlus)
14558         // C++ [dcl.enum]p4: Following the closing brace of an
14559         // enum-specifier, each enumerator has the type of its
14560         // enumeration.
14561         ECD->setType(EnumType);
14562       continue;
14563     } else {
14564       NewTy = BestType;
14565       NewWidth = BestWidth;
14566       NewSign = BestType->isSignedIntegerOrEnumerationType();
14567     }
14568 
14569     // Adjust the APSInt value.
14570     InitVal = InitVal.extOrTrunc(NewWidth);
14571     InitVal.setIsSigned(NewSign);
14572     ECD->setInitVal(InitVal);
14573 
14574     // Adjust the Expr initializer and type.
14575     if (ECD->getInitExpr() &&
14576         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14577       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14578                                                 CK_IntegralCast,
14579                                                 ECD->getInitExpr(),
14580                                                 /*base paths*/ nullptr,
14581                                                 VK_RValue));
14582     if (getLangOpts().CPlusPlus)
14583       // C++ [dcl.enum]p4: Following the closing brace of an
14584       // enum-specifier, each enumerator has the type of its
14585       // enumeration.
14586       ECD->setType(EnumType);
14587     else
14588       ECD->setType(NewTy);
14589   }
14590 
14591   Enum->completeDefinition(BestType, BestPromotionType,
14592                            NumPositiveBits, NumNegativeBits);
14593 
14594   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14595 
14596   if (Enum->hasAttr<FlagEnumAttr>()) {
14597     for (Decl *D : Elements) {
14598       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14599       if (!ECD) continue;  // Already issued a diagnostic.
14600 
14601       llvm::APSInt InitVal = ECD->getInitVal();
14602       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14603           !IsValueInFlagEnum(Enum, InitVal, true))
14604         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14605           << ECD << Enum;
14606     }
14607   }
14608 
14609   // Now that the enum type is defined, ensure it's not been underaligned.
14610   if (Enum->hasAttrs())
14611     CheckAlignasUnderalignment(Enum);
14612 }
14613 
14614 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14615                                   SourceLocation StartLoc,
14616                                   SourceLocation EndLoc) {
14617   StringLiteral *AsmString = cast<StringLiteral>(expr);
14618 
14619   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14620                                                    AsmString, StartLoc,
14621                                                    EndLoc);
14622   CurContext->addDecl(New);
14623   return New;
14624 }
14625 
14626 static void checkModuleImportContext(Sema &S, Module *M,
14627                                      SourceLocation ImportLoc, DeclContext *DC,
14628                                      bool FromInclude = false) {
14629   SourceLocation ExternCLoc;
14630 
14631   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14632     switch (LSD->getLanguage()) {
14633     case LinkageSpecDecl::lang_c:
14634       if (ExternCLoc.isInvalid())
14635         ExternCLoc = LSD->getLocStart();
14636       break;
14637     case LinkageSpecDecl::lang_cxx:
14638       break;
14639     }
14640     DC = LSD->getParent();
14641   }
14642 
14643   while (isa<LinkageSpecDecl>(DC))
14644     DC = DC->getParent();
14645 
14646   if (!isa<TranslationUnitDecl>(DC)) {
14647     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14648                           ? diag::ext_module_import_not_at_top_level_noop
14649                           : diag::err_module_import_not_at_top_level_fatal)
14650         << M->getFullModuleName() << DC;
14651     S.Diag(cast<Decl>(DC)->getLocStart(),
14652            diag::note_module_import_not_at_top_level) << DC;
14653   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14654     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14655       << M->getFullModuleName();
14656     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14657   }
14658 }
14659 
14660 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14661   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14662 }
14663 
14664 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14665                                    SourceLocation ImportLoc,
14666                                    ModuleIdPath Path) {
14667   Module *Mod =
14668       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14669                                    /*IsIncludeDirective=*/false);
14670   if (!Mod)
14671     return true;
14672 
14673   VisibleModules.setVisible(Mod, ImportLoc);
14674 
14675   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14676 
14677   // FIXME: we should support importing a submodule within a different submodule
14678   // of the same top-level module. Until we do, make it an error rather than
14679   // silently ignoring the import.
14680   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14681     Diag(ImportLoc, diag::err_module_self_import)
14682         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14683   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14684     Diag(ImportLoc, diag::err_module_import_in_implementation)
14685         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14686 
14687   SmallVector<SourceLocation, 2> IdentifierLocs;
14688   Module *ModCheck = Mod;
14689   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14690     // If we've run out of module parents, just drop the remaining identifiers.
14691     // We need the length to be consistent.
14692     if (!ModCheck)
14693       break;
14694     ModCheck = ModCheck->Parent;
14695 
14696     IdentifierLocs.push_back(Path[I].second);
14697   }
14698 
14699   ImportDecl *Import = ImportDecl::Create(Context,
14700                                           Context.getTranslationUnitDecl(),
14701                                           AtLoc.isValid()? AtLoc : ImportLoc,
14702                                           Mod, IdentifierLocs);
14703   Context.getTranslationUnitDecl()->addDecl(Import);
14704   return Import;
14705 }
14706 
14707 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14708   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14709 
14710   // Determine whether we're in the #include buffer for a module. The #includes
14711   // in that buffer do not qualify as module imports; they're just an
14712   // implementation detail of us building the module.
14713   //
14714   // FIXME: Should we even get ActOnModuleInclude calls for those?
14715   bool IsInModuleIncludes =
14716       TUKind == TU_Module &&
14717       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14718 
14719   // If this module import was due to an inclusion directive, create an
14720   // implicit import declaration to capture it in the AST.
14721   if (!IsInModuleIncludes) {
14722     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14723     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14724                                                      DirectiveLoc, Mod,
14725                                                      DirectiveLoc);
14726     TU->addDecl(ImportD);
14727     Consumer.HandleImplicitImportDecl(ImportD);
14728   }
14729 
14730   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14731   VisibleModules.setVisible(Mod, DirectiveLoc);
14732 }
14733 
14734 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14735   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14736 
14737   if (getLangOpts().ModulesLocalVisibility)
14738     VisibleModulesStack.push_back(std::move(VisibleModules));
14739   VisibleModules.setVisible(Mod, DirectiveLoc);
14740 }
14741 
14742 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14743   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14744 
14745   if (getLangOpts().ModulesLocalVisibility) {
14746     VisibleModules = std::move(VisibleModulesStack.back());
14747     VisibleModulesStack.pop_back();
14748     VisibleModules.setVisible(Mod, DirectiveLoc);
14749   }
14750 }
14751 
14752 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14753                                                       Module *Mod) {
14754   // Bail if we're not allowed to implicitly import a module here.
14755   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14756     return;
14757 
14758   // Create the implicit import declaration.
14759   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14760   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14761                                                    Loc, Mod, Loc);
14762   TU->addDecl(ImportD);
14763   Consumer.HandleImplicitImportDecl(ImportD);
14764 
14765   // Make the module visible.
14766   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14767   VisibleModules.setVisible(Mod, Loc);
14768 }
14769 
14770 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14771                                       IdentifierInfo* AliasName,
14772                                       SourceLocation PragmaLoc,
14773                                       SourceLocation NameLoc,
14774                                       SourceLocation AliasNameLoc) {
14775   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14776                                          LookupOrdinaryName);
14777   AsmLabelAttr *Attr =
14778       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14779 
14780   // If a declaration that:
14781   // 1) declares a function or a variable
14782   // 2) has external linkage
14783   // already exists, add a label attribute to it.
14784   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14785     if (isDeclExternC(PrevDecl))
14786       PrevDecl->addAttr(Attr);
14787     else
14788       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14789           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14790   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14791   } else
14792     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14793 }
14794 
14795 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14796                              SourceLocation PragmaLoc,
14797                              SourceLocation NameLoc) {
14798   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14799 
14800   if (PrevDecl) {
14801     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14802   } else {
14803     (void)WeakUndeclaredIdentifiers.insert(
14804       std::pair<IdentifierInfo*,WeakInfo>
14805         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14806   }
14807 }
14808 
14809 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14810                                 IdentifierInfo* AliasName,
14811                                 SourceLocation PragmaLoc,
14812                                 SourceLocation NameLoc,
14813                                 SourceLocation AliasNameLoc) {
14814   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14815                                     LookupOrdinaryName);
14816   WeakInfo W = WeakInfo(Name, NameLoc);
14817 
14818   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14819     if (!PrevDecl->hasAttr<AliasAttr>())
14820       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14821         DeclApplyPragmaWeak(TUScope, ND, W);
14822   } else {
14823     (void)WeakUndeclaredIdentifiers.insert(
14824       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14825   }
14826 }
14827 
14828 Decl *Sema::getObjCDeclContext() const {
14829   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14830 }
14831 
14832 AvailabilityResult Sema::getCurContextAvailability() const {
14833   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14834   if (!D)
14835     return AR_Available;
14836 
14837   // If we are within an Objective-C method, we should consult
14838   // both the availability of the method as well as the
14839   // enclosing class.  If the class is (say) deprecated,
14840   // the entire method is considered deprecated from the
14841   // purpose of checking if the current context is deprecated.
14842   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14843     AvailabilityResult R = MD->getAvailability();
14844     if (R != AR_Available)
14845       return R;
14846     D = MD->getClassInterface();
14847   }
14848   // If we are within an Objective-c @implementation, it
14849   // gets the same availability context as the @interface.
14850   else if (const ObjCImplementationDecl *ID =
14851             dyn_cast<ObjCImplementationDecl>(D)) {
14852     D = ID->getClassInterface();
14853   }
14854   // Recover from user error.
14855   return D ? D->getAvailability() : AR_Available;
14856 }
14857