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/Parse/ParseDiagnostic.h"
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 }
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw_wchar_t:
112   case tok::kw_bool:
113   case tok::kw___underlying_type:
114     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 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
132                                                       const IdentifierInfo &II,
133                                                       SourceLocation NameLoc) {
134   // Find the first parent class template context, if any.
135   // FIXME: Perform the lookup in all enclosing class templates.
136   const CXXRecordDecl *RD = nullptr;
137   for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) {
138     RD = dyn_cast<CXXRecordDecl>(DC);
139     if (RD && RD->getDescribedClassTemplate())
140       break;
141   }
142   if (!RD)
143     return ParsedType();
144 
145   // Look for type decls in dependent base classes that have known primary
146   // templates.
147   bool FoundTypeDecl = false;
148   for (const auto &Base : RD->bases()) {
149     auto *TST = Base.getType()->getAs<TemplateSpecializationType>();
150     if (!TST || !TST->isDependentType())
151       continue;
152     auto *TD = TST->getTemplateName().getAsTemplateDecl();
153     if (!TD)
154       continue;
155     auto *BasePrimaryTemplate =
156         dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
157     if (!BasePrimaryTemplate)
158       continue;
159     // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly
160     // by calling or integrating with the main LookupQualifiedName mechanism.
161     for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) {
162       if (FoundTypeDecl)
163         return ParsedType();
164       FoundTypeDecl = isa<TypeDecl>(ND);
165       if (!FoundTypeDecl)
166         return ParsedType();
167     }
168   }
169   if (!FoundTypeDecl)
170     return ParsedType();
171 
172   // We found some types in dependent base classes.  Recover as if the user
173   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
174   // lookup during template instantiation.
175   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
176 
177   ASTContext &Context = S.Context;
178   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
179                                           cast<Type>(Context.getRecordType(RD)));
180   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
181 
182   CXXScopeSpec SS;
183   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
184 
185   TypeLocBuilder Builder;
186   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
187   DepTL.setNameLoc(NameLoc);
188   DepTL.setElaboratedKeywordLoc(SourceLocation());
189   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
190   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
191 }
192 
193 /// \brief If the identifier refers to a type name within this scope,
194 /// return the declaration of that type.
195 ///
196 /// This routine performs ordinary name lookup of the identifier II
197 /// within the given scope, with optional C++ scope specifier SS, to
198 /// determine whether the name refers to a type. If so, returns an
199 /// opaque pointer (actually a QualType) corresponding to that
200 /// type. Otherwise, returns NULL.
201 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
202                              Scope *S, CXXScopeSpec *SS,
203                              bool isClassName, bool HasTrailingDot,
204                              ParsedType ObjectTypePtr,
205                              bool IsCtorOrDtorName,
206                              bool WantNontrivialTypeSourceInfo,
207                              IdentifierInfo **CorrectedII) {
208   // Determine where we will perform name lookup.
209   DeclContext *LookupCtx = nullptr;
210   if (ObjectTypePtr) {
211     QualType ObjectType = ObjectTypePtr.get();
212     if (ObjectType->isRecordType())
213       LookupCtx = computeDeclContext(ObjectType);
214   } else if (SS && SS->isNotEmpty()) {
215     LookupCtx = computeDeclContext(*SS, false);
216 
217     if (!LookupCtx) {
218       if (isDependentScopeSpecifier(*SS)) {
219         // C++ [temp.res]p3:
220         //   A qualified-id that refers to a type and in which the
221         //   nested-name-specifier depends on a template-parameter (14.6.2)
222         //   shall be prefixed by the keyword typename to indicate that the
223         //   qualified-id denotes a type, forming an
224         //   elaborated-type-specifier (7.1.5.3).
225         //
226         // We therefore do not perform any name lookup if the result would
227         // refer to a member of an unknown specialization.
228         if (!isClassName && !IsCtorOrDtorName)
229           return ParsedType();
230 
231         // We know from the grammar that this name refers to a type,
232         // so build a dependent node to describe the type.
233         if (WantNontrivialTypeSourceInfo)
234           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
235 
236         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
237         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
238                                        II, NameLoc);
239         return ParsedType::make(T);
240       }
241 
242       return ParsedType();
243     }
244 
245     if (!LookupCtx->isDependentContext() &&
246         RequireCompleteDeclContext(*SS, LookupCtx))
247       return ParsedType();
248   }
249 
250   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
251   // lookup for class-names.
252   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
253                                       LookupOrdinaryName;
254   LookupResult Result(*this, &II, NameLoc, Kind);
255   if (LookupCtx) {
256     // Perform "qualified" name lookup into the declaration context we
257     // computed, which is either the type of the base of a member access
258     // expression or the declaration context associated with a prior
259     // nested-name-specifier.
260     LookupQualifiedName(Result, LookupCtx);
261 
262     if (ObjectTypePtr && Result.empty()) {
263       // C++ [basic.lookup.classref]p3:
264       //   If the unqualified-id is ~type-name, the type-name is looked up
265       //   in the context of the entire postfix-expression. If the type T of
266       //   the object expression is of a class type C, the type-name is also
267       //   looked up in the scope of class C. At least one of the lookups shall
268       //   find a name that refers to (possibly cv-qualified) T.
269       LookupName(Result, S);
270     }
271   } else {
272     // Perform unqualified name lookup.
273     LookupName(Result, S);
274 
275     // For unqualified lookup in a class template in MSVC mode, look into
276     // dependent base classes where the primary class template is known.
277     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
278       if (ParsedType TypeInBase =
279               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
280         return TypeInBase;
281     }
282   }
283 
284   NamedDecl *IIDecl = nullptr;
285   switch (Result.getResultKind()) {
286   case LookupResult::NotFound:
287   case LookupResult::NotFoundInCurrentInstantiation:
288     if (CorrectedII) {
289       TypoCorrection Correction = CorrectTypo(
290           Result.getLookupNameInfo(), Kind, S, SS,
291           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
292           CTK_ErrorRecovery);
293       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
294       TemplateTy Template;
295       bool MemberOfUnknownSpecialization;
296       UnqualifiedId TemplateName;
297       TemplateName.setIdentifier(NewII, NameLoc);
298       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
299       CXXScopeSpec NewSS, *NewSSPtr = SS;
300       if (SS && NNS) {
301         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
302         NewSSPtr = &NewSS;
303       }
304       if (Correction && (NNS || NewII != &II) &&
305           // Ignore a correction to a template type as the to-be-corrected
306           // identifier is not a template (typo correction for template names
307           // is handled elsewhere).
308           !(getLangOpts().CPlusPlus && NewSSPtr &&
309             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
310                            false, Template, MemberOfUnknownSpecialization))) {
311         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
312                                     isClassName, HasTrailingDot, ObjectTypePtr,
313                                     IsCtorOrDtorName,
314                                     WantNontrivialTypeSourceInfo);
315         if (Ty) {
316           diagnoseTypo(Correction,
317                        PDiag(diag::err_unknown_type_or_class_name_suggest)
318                          << Result.getLookupName() << isClassName);
319           if (SS && NNS)
320             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
321           *CorrectedII = NewII;
322           return Ty;
323         }
324       }
325     }
326     // If typo correction failed or was not performed, fall through
327   case LookupResult::FoundOverloaded:
328   case LookupResult::FoundUnresolvedValue:
329     Result.suppressDiagnostics();
330     return ParsedType();
331 
332   case LookupResult::Ambiguous:
333     // Recover from type-hiding ambiguities by hiding the type.  We'll
334     // do the lookup again when looking for an object, and we can
335     // diagnose the error then.  If we don't do this, then the error
336     // about hiding the type will be immediately followed by an error
337     // that only makes sense if the identifier was treated like a type.
338     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
339       Result.suppressDiagnostics();
340       return ParsedType();
341     }
342 
343     // Look to see if we have a type anywhere in the list of results.
344     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
345          Res != ResEnd; ++Res) {
346       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
347         if (!IIDecl ||
348             (*Res)->getLocation().getRawEncoding() <
349               IIDecl->getLocation().getRawEncoding())
350           IIDecl = *Res;
351       }
352     }
353 
354     if (!IIDecl) {
355       // None of the entities we found is a type, so there is no way
356       // to even assume that the result is a type. In this case, don't
357       // complain about the ambiguity. The parser will either try to
358       // perform this lookup again (e.g., as an object name), which
359       // will produce the ambiguity, or will complain that it expected
360       // a type name.
361       Result.suppressDiagnostics();
362       return ParsedType();
363     }
364 
365     // We found a type within the ambiguous lookup; diagnose the
366     // ambiguity and then return that type. This might be the right
367     // answer, or it might not be, but it suppresses any attempt to
368     // perform the name lookup again.
369     break;
370 
371   case LookupResult::Found:
372     IIDecl = Result.getFoundDecl();
373     break;
374   }
375 
376   assert(IIDecl && "Didn't find decl");
377 
378   QualType T;
379   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
380     DiagnoseUseOfDecl(IIDecl, NameLoc);
381 
382     T = Context.getTypeDeclType(TD);
383     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
384 
385     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
386     // constructor or destructor name (in such a case, the scope specifier
387     // will be attached to the enclosing Expr or Decl node).
388     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
389       if (WantNontrivialTypeSourceInfo) {
390         // Construct a type with type-source information.
391         TypeLocBuilder Builder;
392         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
393 
394         T = getElaboratedType(ETK_None, *SS, T);
395         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
396         ElabTL.setElaboratedKeywordLoc(SourceLocation());
397         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
398         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
399       } else {
400         T = getElaboratedType(ETK_None, *SS, T);
401       }
402     }
403   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
404     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
405     if (!HasTrailingDot)
406       T = Context.getObjCInterfaceType(IDecl);
407   }
408 
409   if (T.isNull()) {
410     // If it's not plausibly a type, suppress diagnostics.
411     Result.suppressDiagnostics();
412     return ParsedType();
413   }
414   return ParsedType::make(T);
415 }
416 
417 // Builds a fake NNS for the given decl context.
418 static NestedNameSpecifier *
419 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
420   for (;; DC = DC->getLookupParent()) {
421     DC = DC->getPrimaryContext();
422     auto *ND = dyn_cast<NamespaceDecl>(DC);
423     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
424       return NestedNameSpecifier::Create(Context, nullptr, ND);
425     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
426       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
427                                          RD->getTypeForDecl());
428     else if (isa<TranslationUnitDecl>(DC))
429       return NestedNameSpecifier::GlobalSpecifier(Context);
430   }
431   llvm_unreachable("something isn't in TU scope?");
432 }
433 
434 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
435                                                 SourceLocation NameLoc) {
436   // Accepting an undeclared identifier as a default argument for a template
437   // type parameter is a Microsoft extension.
438   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
439 
440   // Build a fake DependentNameType that will perform lookup into CurContext at
441   // instantiation time.  The name specifier isn't dependent, so template
442   // instantiation won't transform it.  It will retry the lookup, however.
443   NestedNameSpecifier *NNS =
444       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
445   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
446 
447   // Build type location information.  We synthesized the qualifier, so we have
448   // to build a fake NestedNameSpecifierLoc.
449   NestedNameSpecifierLocBuilder NNSLocBuilder;
450   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
451   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
452 
453   TypeLocBuilder Builder;
454   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
455   DepTL.setNameLoc(NameLoc);
456   DepTL.setElaboratedKeywordLoc(SourceLocation());
457   DepTL.setQualifierLoc(QualifierLoc);
458   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
459 }
460 
461 /// isTagName() - This method is called *for error recovery purposes only*
462 /// to determine if the specified name is a valid tag name ("struct foo").  If
463 /// so, this returns the TST for the tag corresponding to it (TST_enum,
464 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
465 /// cases in C where the user forgot to specify the tag.
466 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
467   // Do a tag name lookup in this scope.
468   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
469   LookupName(R, S, false);
470   R.suppressDiagnostics();
471   if (R.getResultKind() == LookupResult::Found)
472     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
473       switch (TD->getTagKind()) {
474       case TTK_Struct: return DeclSpec::TST_struct;
475       case TTK_Interface: return DeclSpec::TST_interface;
476       case TTK_Union:  return DeclSpec::TST_union;
477       case TTK_Class:  return DeclSpec::TST_class;
478       case TTK_Enum:   return DeclSpec::TST_enum;
479       }
480     }
481 
482   return DeclSpec::TST_unspecified;
483 }
484 
485 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
486 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
487 /// then downgrade the missing typename error to a warning.
488 /// This is needed for MSVC compatibility; Example:
489 /// @code
490 /// template<class T> class A {
491 /// public:
492 ///   typedef int TYPE;
493 /// };
494 /// template<class T> class B : public A<T> {
495 /// public:
496 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
497 /// };
498 /// @endcode
499 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
500   if (CurContext->isRecord()) {
501     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
502       return true;
503 
504     const Type *Ty = SS->getScopeRep()->getAsType();
505 
506     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
507     for (const auto &Base : RD->bases())
508       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
509         return true;
510     return S->isFunctionPrototypeScope();
511   }
512   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
513 }
514 
515 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
516                                    SourceLocation IILoc,
517                                    Scope *S,
518                                    CXXScopeSpec *SS,
519                                    ParsedType &SuggestedType,
520                                    bool AllowClassTemplates) {
521   // We don't have anything to suggest (yet).
522   SuggestedType = ParsedType();
523 
524   // There may have been a typo in the name of the type. Look up typo
525   // results, in case we have something that we can suggest.
526   if (TypoCorrection Corrected =
527           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
528                       llvm::make_unique<TypeNameValidatorCCC>(
529                           false, false, AllowClassTemplates),
530                       CTK_ErrorRecovery)) {
531     if (Corrected.isKeyword()) {
532       // We corrected to a keyword.
533       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
534       II = Corrected.getCorrectionAsIdentifierInfo();
535     } else {
536       // We found a similarly-named type or interface; suggest that.
537       if (!SS || !SS->isSet()) {
538         diagnoseTypo(Corrected,
539                      PDiag(diag::err_unknown_typename_suggest) << II);
540       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
541         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
542         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543                                 II->getName().equals(CorrectedStr);
544         diagnoseTypo(Corrected,
545                      PDiag(diag::err_unknown_nested_typename_suggest)
546                        << II << DC << DroppedSpecifier << SS->getRange());
547       } else {
548         llvm_unreachable("could not have corrected a typo here");
549       }
550 
551       CXXScopeSpec tmpSS;
552       if (Corrected.getCorrectionSpecifier())
553         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
554                           SourceRange(IILoc));
555       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
556                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
557                                   false, ParsedType(),
558                                   /*IsCtorOrDtorName=*/false,
559                                   /*NonTrivialTypeSourceInfo=*/true);
560     }
561     return;
562   }
563 
564   if (getLangOpts().CPlusPlus) {
565     // See if II is a class template that the user forgot to pass arguments to.
566     UnqualifiedId Name;
567     Name.setIdentifier(II, IILoc);
568     CXXScopeSpec EmptySS;
569     TemplateTy TemplateResult;
570     bool MemberOfUnknownSpecialization;
571     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
572                        Name, ParsedType(), true, TemplateResult,
573                        MemberOfUnknownSpecialization) == TNK_Type_template) {
574       TemplateName TplName = TemplateResult.get();
575       Diag(IILoc, diag::err_template_missing_args) << TplName;
576       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
577         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
578           << TplDecl->getTemplateParameters()->getSourceRange();
579       }
580       return;
581     }
582   }
583 
584   // FIXME: Should we move the logic that tries to recover from a missing tag
585   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
586 
587   if (!SS || (!SS->isSet() && !SS->isInvalid()))
588     Diag(IILoc, diag::err_unknown_typename) << II;
589   else if (DeclContext *DC = computeDeclContext(*SS, false))
590     Diag(IILoc, diag::err_typename_nested_not_found)
591       << II << DC << SS->getRange();
592   else if (isDependentScopeSpecifier(*SS)) {
593     unsigned DiagID = diag::err_typename_missing;
594     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
595       DiagID = diag::ext_typename_missing;
596 
597     Diag(SS->getRange().getBegin(), DiagID)
598       << SS->getScopeRep() << II->getName()
599       << SourceRange(SS->getRange().getBegin(), IILoc)
600       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
601     SuggestedType = ActOnTypenameType(S, SourceLocation(),
602                                       *SS, *II, IILoc).get();
603   } else {
604     assert(SS && SS->isInvalid() &&
605            "Invalid scope specifier has already been diagnosed");
606   }
607 }
608 
609 /// \brief Determine whether the given result set contains either a type name
610 /// or
611 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
612   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
613                        NextToken.is(tok::less);
614 
615   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
616     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
617       return true;
618 
619     if (CheckTemplate && isa<TemplateDecl>(*I))
620       return true;
621   }
622 
623   return false;
624 }
625 
626 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
627                                     Scope *S, CXXScopeSpec &SS,
628                                     IdentifierInfo *&Name,
629                                     SourceLocation NameLoc) {
630   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
631   SemaRef.LookupParsedName(R, S, &SS);
632   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
633     StringRef FixItTagName;
634     switch (Tag->getTagKind()) {
635       case TTK_Class:
636         FixItTagName = "class ";
637         break;
638 
639       case TTK_Enum:
640         FixItTagName = "enum ";
641         break;
642 
643       case TTK_Struct:
644         FixItTagName = "struct ";
645         break;
646 
647       case TTK_Interface:
648         FixItTagName = "__interface ";
649         break;
650 
651       case TTK_Union:
652         FixItTagName = "union ";
653         break;
654     }
655 
656     StringRef TagName = FixItTagName.drop_back();
657     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
658       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
659       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
660 
661     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
662          I != IEnd; ++I)
663       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
664         << Name << TagName;
665 
666     // Replace lookup results with just the tag decl.
667     Result.clear(Sema::LookupTagName);
668     SemaRef.LookupParsedName(Result, S, &SS);
669     return true;
670   }
671 
672   return false;
673 }
674 
675 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
676 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
677                                   QualType T, SourceLocation NameLoc) {
678   ASTContext &Context = S.Context;
679 
680   TypeLocBuilder Builder;
681   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
682 
683   T = S.getElaboratedType(ETK_None, SS, T);
684   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
685   ElabTL.setElaboratedKeywordLoc(SourceLocation());
686   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
687   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
688 }
689 
690 Sema::NameClassification
691 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
692                    SourceLocation NameLoc, const Token &NextToken,
693                    bool IsAddressOfOperand,
694                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
695   DeclarationNameInfo NameInfo(Name, NameLoc);
696   ObjCMethodDecl *CurMethod = getCurMethodDecl();
697 
698   if (NextToken.is(tok::coloncolon)) {
699     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
700                                 QualType(), false, SS, nullptr, false);
701   }
702 
703   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
704   LookupParsedName(Result, S, &SS, !CurMethod);
705 
706   // For unqualified lookup in a class template in MSVC mode, look into
707   // dependent base classes where the primary class template is known.
708   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
709     if (ParsedType TypeInBase =
710             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
711       return TypeInBase;
712   }
713 
714   // Perform lookup for Objective-C instance variables (including automatically
715   // synthesized instance variables), if we're in an Objective-C method.
716   // FIXME: This lookup really, really needs to be folded in to the normal
717   // unqualified lookup mechanism.
718   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
719     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
720     if (E.get() || E.isInvalid())
721       return E;
722   }
723 
724   bool SecondTry = false;
725   bool IsFilteredTemplateName = false;
726 
727 Corrected:
728   switch (Result.getResultKind()) {
729   case LookupResult::NotFound:
730     // If an unqualified-id is followed by a '(', then we have a function
731     // call.
732     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
733       // In C++, this is an ADL-only call.
734       // FIXME: Reference?
735       if (getLangOpts().CPlusPlus)
736         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
737 
738       // C90 6.3.2.2:
739       //   If the expression that precedes the parenthesized argument list in a
740       //   function call consists solely of an identifier, and if no
741       //   declaration is visible for this identifier, the identifier is
742       //   implicitly declared exactly as if, in the innermost block containing
743       //   the function call, the declaration
744       //
745       //     extern int identifier ();
746       //
747       //   appeared.
748       //
749       // We also allow this in C99 as an extension.
750       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
751         Result.addDecl(D);
752         Result.resolveKind();
753         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
754       }
755     }
756 
757     // In C, we first see whether there is a tag type by the same name, in
758     // which case it's likely that the user just forget to write "enum",
759     // "struct", or "union".
760     if (!getLangOpts().CPlusPlus && !SecondTry &&
761         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
762       break;
763     }
764 
765     // Perform typo correction to determine if there is another name that is
766     // close to this name.
767     if (!SecondTry && CCC) {
768       SecondTry = true;
769       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
770                                                  Result.getLookupKind(), S,
771                                                  &SS, std::move(CCC),
772                                                  CTK_ErrorRecovery)) {
773         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
774         unsigned QualifiedDiag = diag::err_no_member_suggest;
775 
776         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
777         NamedDecl *UnderlyingFirstDecl
778           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
779         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
781           UnqualifiedDiag = diag::err_no_template_suggest;
782           QualifiedDiag = diag::err_no_member_template_suggest;
783         } else if (UnderlyingFirstDecl &&
784                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
785                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
786                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
787           UnqualifiedDiag = diag::err_unknown_typename_suggest;
788           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
789         }
790 
791         if (SS.isEmpty()) {
792           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
793         } else {// FIXME: is this even reachable? Test it.
794           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
795           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
796                                   Name->getName().equals(CorrectedStr);
797           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
798                                     << Name << computeDeclContext(SS, false)
799                                     << DroppedSpecifier << SS.getRange());
800         }
801 
802         // Update the name, so that the caller has the new name.
803         Name = Corrected.getCorrectionAsIdentifierInfo();
804 
805         // Typo correction corrected to a keyword.
806         if (Corrected.isKeyword())
807           return Name;
808 
809         // Also update the LookupResult...
810         // FIXME: This should probably go away at some point
811         Result.clear();
812         Result.setLookupName(Corrected.getCorrection());
813         if (FirstDecl)
814           Result.addDecl(FirstDecl);
815 
816         // If we found an Objective-C instance variable, let
817         // LookupInObjCMethod build the appropriate expression to
818         // reference the ivar.
819         // FIXME: This is a gross hack.
820         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
821           Result.clear();
822           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
823           return E;
824         }
825 
826         goto Corrected;
827       }
828     }
829 
830     // We failed to correct; just fall through and let the parser deal with it.
831     Result.suppressDiagnostics();
832     return NameClassification::Unknown();
833 
834   case LookupResult::NotFoundInCurrentInstantiation: {
835     // We performed name lookup into the current instantiation, and there were
836     // dependent bases, so we treat this result the same way as any other
837     // dependent nested-name-specifier.
838 
839     // C++ [temp.res]p2:
840     //   A name used in a template declaration or definition and that is
841     //   dependent on a template-parameter is assumed not to name a type
842     //   unless the applicable name lookup finds a type name or the name is
843     //   qualified by the keyword typename.
844     //
845     // FIXME: If the next token is '<', we might want to ask the parser to
846     // perform some heroics to see if we actually have a
847     // template-argument-list, which would indicate a missing 'template'
848     // keyword here.
849     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
850                                       NameInfo, IsAddressOfOperand,
851                                       /*TemplateArgs=*/nullptr);
852   }
853 
854   case LookupResult::Found:
855   case LookupResult::FoundOverloaded:
856   case LookupResult::FoundUnresolvedValue:
857     break;
858 
859   case LookupResult::Ambiguous:
860     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
861         hasAnyAcceptableTemplateNames(Result)) {
862       // C++ [temp.local]p3:
863       //   A lookup that finds an injected-class-name (10.2) can result in an
864       //   ambiguity in certain cases (for example, if it is found in more than
865       //   one base class). If all of the injected-class-names that are found
866       //   refer to specializations of the same class template, and if the name
867       //   is followed by a template-argument-list, the reference refers to the
868       //   class template itself and not a specialization thereof, and is not
869       //   ambiguous.
870       //
871       // This filtering can make an ambiguous result into an unambiguous one,
872       // so try again after filtering out template names.
873       FilterAcceptableTemplateNames(Result);
874       if (!Result.isAmbiguous()) {
875         IsFilteredTemplateName = true;
876         break;
877       }
878     }
879 
880     // Diagnose the ambiguity and return an error.
881     return NameClassification::Error();
882   }
883 
884   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
885       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
886     // C++ [temp.names]p3:
887     //   After name lookup (3.4) finds that a name is a template-name or that
888     //   an operator-function-id or a literal- operator-id refers to a set of
889     //   overloaded functions any member of which is a function template if
890     //   this is followed by a <, the < is always taken as the delimiter of a
891     //   template-argument-list and never as the less-than operator.
892     if (!IsFilteredTemplateName)
893       FilterAcceptableTemplateNames(Result);
894 
895     if (!Result.empty()) {
896       bool IsFunctionTemplate;
897       bool IsVarTemplate;
898       TemplateName Template;
899       if (Result.end() - Result.begin() > 1) {
900         IsFunctionTemplate = true;
901         Template = Context.getOverloadedTemplateName(Result.begin(),
902                                                      Result.end());
903       } else {
904         TemplateDecl *TD
905           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
906         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
907         IsVarTemplate = isa<VarTemplateDecl>(TD);
908 
909         if (SS.isSet() && !SS.isInvalid())
910           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
911                                                     /*TemplateKeyword=*/false,
912                                                       TD);
913         else
914           Template = TemplateName(TD);
915       }
916 
917       if (IsFunctionTemplate) {
918         // Function templates always go through overload resolution, at which
919         // point we'll perform the various checks (e.g., accessibility) we need
920         // to based on which function we selected.
921         Result.suppressDiagnostics();
922 
923         return NameClassification::FunctionTemplate(Template);
924       }
925 
926       return IsVarTemplate ? NameClassification::VarTemplate(Template)
927                            : NameClassification::TypeTemplate(Template);
928     }
929   }
930 
931   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
932   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
933     DiagnoseUseOfDecl(Type, NameLoc);
934     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
935     QualType T = Context.getTypeDeclType(Type);
936     if (SS.isNotEmpty())
937       return buildNestedType(*this, SS, T, NameLoc);
938     return ParsedType::make(T);
939   }
940 
941   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
942   if (!Class) {
943     // FIXME: It's unfortunate that we don't have a Type node for handling this.
944     if (ObjCCompatibleAliasDecl *Alias =
945             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
946       Class = Alias->getClassInterface();
947   }
948 
949   if (Class) {
950     DiagnoseUseOfDecl(Class, NameLoc);
951 
952     if (NextToken.is(tok::period)) {
953       // Interface. <something> is parsed as a property reference expression.
954       // Just return "unknown" as a fall-through for now.
955       Result.suppressDiagnostics();
956       return NameClassification::Unknown();
957     }
958 
959     QualType T = Context.getObjCInterfaceType(Class);
960     return ParsedType::make(T);
961   }
962 
963   // We can have a type template here if we're classifying a template argument.
964   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
965     return NameClassification::TypeTemplate(
966         TemplateName(cast<TemplateDecl>(FirstDecl)));
967 
968   // Check for a tag type hidden by a non-type decl in a few cases where it
969   // seems likely a type is wanted instead of the non-type that was found.
970   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
971   if ((NextToken.is(tok::identifier) ||
972        (NextIsOp &&
973         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
974       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
975     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
976     DiagnoseUseOfDecl(Type, NameLoc);
977     QualType T = Context.getTypeDeclType(Type);
978     if (SS.isNotEmpty())
979       return buildNestedType(*this, SS, T, NameLoc);
980     return ParsedType::make(T);
981   }
982 
983   if (FirstDecl->isCXXClassMember())
984     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
985                                            nullptr);
986 
987   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
988   return BuildDeclarationNameExpr(SS, Result, ADL);
989 }
990 
991 // Determines the context to return to after temporarily entering a
992 // context.  This depends in an unnecessarily complicated way on the
993 // exact ordering of callbacks from the parser.
994 DeclContext *Sema::getContainingDC(DeclContext *DC) {
995 
996   // Functions defined inline within classes aren't parsed until we've
997   // finished parsing the top-level class, so the top-level class is
998   // the context we'll need to return to.
999   // A Lambda call operator whose parent is a class must not be treated
1000   // as an inline member function.  A Lambda can be used legally
1001   // either as an in-class member initializer or a default argument.  These
1002   // are parsed once the class has been marked complete and so the containing
1003   // context would be the nested class (when the lambda is defined in one);
1004   // If the class is not complete, then the lambda is being used in an
1005   // ill-formed fashion (such as to specify the width of a bit-field, or
1006   // in an array-bound) - in which case we still want to return the
1007   // lexically containing DC (which could be a nested class).
1008   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1009     DC = DC->getLexicalParent();
1010 
1011     // A function not defined within a class will always return to its
1012     // lexical context.
1013     if (!isa<CXXRecordDecl>(DC))
1014       return DC;
1015 
1016     // A C++ inline method/friend is parsed *after* the topmost class
1017     // it was declared in is fully parsed ("complete");  the topmost
1018     // class is the context we need to return to.
1019     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1020       DC = RD;
1021 
1022     // Return the declaration context of the topmost class the inline method is
1023     // declared in.
1024     return DC;
1025   }
1026 
1027   return DC->getLexicalParent();
1028 }
1029 
1030 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1031   assert(getContainingDC(DC) == CurContext &&
1032       "The next DeclContext should be lexically contained in the current one.");
1033   CurContext = DC;
1034   S->setEntity(DC);
1035 }
1036 
1037 void Sema::PopDeclContext() {
1038   assert(CurContext && "DeclContext imbalance!");
1039 
1040   CurContext = getContainingDC(CurContext);
1041   assert(CurContext && "Popped translation unit!");
1042 }
1043 
1044 /// EnterDeclaratorContext - Used when we must lookup names in the context
1045 /// of a declarator's nested name specifier.
1046 ///
1047 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1048   // C++0x [basic.lookup.unqual]p13:
1049   //   A name used in the definition of a static data member of class
1050   //   X (after the qualified-id of the static member) is looked up as
1051   //   if the name was used in a member function of X.
1052   // C++0x [basic.lookup.unqual]p14:
1053   //   If a variable member of a namespace is defined outside of the
1054   //   scope of its namespace then any name used in the definition of
1055   //   the variable member (after the declarator-id) is looked up as
1056   //   if the definition of the variable member occurred in its
1057   //   namespace.
1058   // Both of these imply that we should push a scope whose context
1059   // is the semantic context of the declaration.  We can't use
1060   // PushDeclContext here because that context is not necessarily
1061   // lexically contained in the current context.  Fortunately,
1062   // the containing scope should have the appropriate information.
1063 
1064   assert(!S->getEntity() && "scope already has entity");
1065 
1066 #ifndef NDEBUG
1067   Scope *Ancestor = S->getParent();
1068   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1069   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1070 #endif
1071 
1072   CurContext = DC;
1073   S->setEntity(DC);
1074 }
1075 
1076 void Sema::ExitDeclaratorContext(Scope *S) {
1077   assert(S->getEntity() == CurContext && "Context imbalance!");
1078 
1079   // Switch back to the lexical context.  The safety of this is
1080   // enforced by an assert in EnterDeclaratorContext.
1081   Scope *Ancestor = S->getParent();
1082   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1083   CurContext = Ancestor->getEntity();
1084 
1085   // We don't need to do anything with the scope, which is going to
1086   // disappear.
1087 }
1088 
1089 
1090 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1091   // We assume that the caller has already called
1092   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1093   FunctionDecl *FD = D->getAsFunction();
1094   if (!FD)
1095     return;
1096 
1097   // Same implementation as PushDeclContext, but enters the context
1098   // from the lexical parent, rather than the top-level class.
1099   assert(CurContext == FD->getLexicalParent() &&
1100     "The next DeclContext should be lexically contained in the current one.");
1101   CurContext = FD;
1102   S->setEntity(CurContext);
1103 
1104   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1105     ParmVarDecl *Param = FD->getParamDecl(P);
1106     // If the parameter has an identifier, then add it to the scope
1107     if (Param->getIdentifier()) {
1108       S->AddDecl(Param);
1109       IdResolver.AddDecl(Param);
1110     }
1111   }
1112 }
1113 
1114 
1115 void Sema::ActOnExitFunctionContext() {
1116   // Same implementation as PopDeclContext, but returns to the lexical parent,
1117   // rather than the top-level class.
1118   assert(CurContext && "DeclContext imbalance!");
1119   CurContext = CurContext->getLexicalParent();
1120   assert(CurContext && "Popped translation unit!");
1121 }
1122 
1123 
1124 /// \brief Determine whether we allow overloading of the function
1125 /// PrevDecl with another declaration.
1126 ///
1127 /// This routine determines whether overloading is possible, not
1128 /// whether some new function is actually an overload. It will return
1129 /// true in C++ (where we can always provide overloads) or, as an
1130 /// extension, in C when the previous function is already an
1131 /// overloaded function declaration or has the "overloadable"
1132 /// attribute.
1133 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1134                                        ASTContext &Context) {
1135   if (Context.getLangOpts().CPlusPlus)
1136     return true;
1137 
1138   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1139     return true;
1140 
1141   return (Previous.getResultKind() == LookupResult::Found
1142           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1143 }
1144 
1145 /// Add this decl to the scope shadowed decl chains.
1146 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1147   // Move up the scope chain until we find the nearest enclosing
1148   // non-transparent context. The declaration will be introduced into this
1149   // scope.
1150   while (S->getEntity() && S->getEntity()->isTransparentContext())
1151     S = S->getParent();
1152 
1153   // Add scoped declarations into their context, so that they can be
1154   // found later. Declarations without a context won't be inserted
1155   // into any context.
1156   if (AddToContext)
1157     CurContext->addDecl(D);
1158 
1159   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1160   // are function-local declarations.
1161   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1162       !D->getDeclContext()->getRedeclContext()->Equals(
1163         D->getLexicalDeclContext()->getRedeclContext()) &&
1164       !D->getLexicalDeclContext()->isFunctionOrMethod())
1165     return;
1166 
1167   // Template instantiations should also not be pushed into scope.
1168   if (isa<FunctionDecl>(D) &&
1169       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1170     return;
1171 
1172   // If this replaces anything in the current scope,
1173   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1174                                IEnd = IdResolver.end();
1175   for (; I != IEnd; ++I) {
1176     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1177       S->RemoveDecl(*I);
1178       IdResolver.RemoveDecl(*I);
1179 
1180       // Should only need to replace one decl.
1181       break;
1182     }
1183   }
1184 
1185   S->AddDecl(D);
1186 
1187   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1188     // Implicitly-generated labels may end up getting generated in an order that
1189     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1190     // the label at the appropriate place in the identifier chain.
1191     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1192       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1193       if (IDC == CurContext) {
1194         if (!S->isDeclScope(*I))
1195           continue;
1196       } else if (IDC->Encloses(CurContext))
1197         break;
1198     }
1199 
1200     IdResolver.InsertDeclAfter(I, D);
1201   } else {
1202     IdResolver.AddDecl(D);
1203   }
1204 }
1205 
1206 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1207   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1208     TUScope->AddDecl(D);
1209 }
1210 
1211 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1212                          bool AllowInlineNamespace) {
1213   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1214 }
1215 
1216 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1217   DeclContext *TargetDC = DC->getPrimaryContext();
1218   do {
1219     if (DeclContext *ScopeDC = S->getEntity())
1220       if (ScopeDC->getPrimaryContext() == TargetDC)
1221         return S;
1222   } while ((S = S->getParent()));
1223 
1224   return nullptr;
1225 }
1226 
1227 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1228                                             DeclContext*,
1229                                             ASTContext&);
1230 
1231 /// Filters out lookup results that don't fall within the given scope
1232 /// as determined by isDeclInScope.
1233 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1234                                 bool ConsiderLinkage,
1235                                 bool AllowInlineNamespace) {
1236   LookupResult::Filter F = R.makeFilter();
1237   while (F.hasNext()) {
1238     NamedDecl *D = F.next();
1239 
1240     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1241       continue;
1242 
1243     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1244       continue;
1245 
1246     F.erase();
1247   }
1248 
1249   F.done();
1250 }
1251 
1252 static bool isUsingDecl(NamedDecl *D) {
1253   return isa<UsingShadowDecl>(D) ||
1254          isa<UnresolvedUsingTypenameDecl>(D) ||
1255          isa<UnresolvedUsingValueDecl>(D);
1256 }
1257 
1258 /// Removes using shadow declarations from the lookup results.
1259 static void RemoveUsingDecls(LookupResult &R) {
1260   LookupResult::Filter F = R.makeFilter();
1261   while (F.hasNext())
1262     if (isUsingDecl(F.next()))
1263       F.erase();
1264 
1265   F.done();
1266 }
1267 
1268 /// \brief Check for this common pattern:
1269 /// @code
1270 /// class S {
1271 ///   S(const S&); // DO NOT IMPLEMENT
1272 ///   void operator=(const S&); // DO NOT IMPLEMENT
1273 /// };
1274 /// @endcode
1275 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1276   // FIXME: Should check for private access too but access is set after we get
1277   // the decl here.
1278   if (D->doesThisDeclarationHaveABody())
1279     return false;
1280 
1281   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1282     return CD->isCopyConstructor();
1283   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1284     return Method->isCopyAssignmentOperator();
1285   return false;
1286 }
1287 
1288 // We need this to handle
1289 //
1290 // typedef struct {
1291 //   void *foo() { return 0; }
1292 // } A;
1293 //
1294 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1295 // for example. If 'A', foo will have external linkage. If we have '*A',
1296 // foo will have no linkage. Since we can't know until we get to the end
1297 // of the typedef, this function finds out if D might have non-external linkage.
1298 // Callers should verify at the end of the TU if it D has external linkage or
1299 // not.
1300 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1301   const DeclContext *DC = D->getDeclContext();
1302   while (!DC->isTranslationUnit()) {
1303     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1304       if (!RD->hasNameForLinkage())
1305         return true;
1306     }
1307     DC = DC->getParent();
1308   }
1309 
1310   return !D->isExternallyVisible();
1311 }
1312 
1313 // FIXME: This needs to be refactored; some other isInMainFile users want
1314 // these semantics.
1315 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1316   if (S.TUKind != TU_Complete)
1317     return false;
1318   return S.SourceMgr.isInMainFile(Loc);
1319 }
1320 
1321 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1322   assert(D);
1323 
1324   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1325     return false;
1326 
1327   // Ignore all entities declared within templates, and out-of-line definitions
1328   // of members of class templates.
1329   if (D->getDeclContext()->isDependentContext() ||
1330       D->getLexicalDeclContext()->isDependentContext())
1331     return false;
1332 
1333   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1334     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1335       return false;
1336 
1337     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1338       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1339         return false;
1340     } else {
1341       // 'static inline' functions are defined in headers; don't warn.
1342       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1343         return false;
1344     }
1345 
1346     if (FD->doesThisDeclarationHaveABody() &&
1347         Context.DeclMustBeEmitted(FD))
1348       return false;
1349   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1350     // Constants and utility variables are defined in headers with internal
1351     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1352     // like "inline".)
1353     if (!isMainFileLoc(*this, VD->getLocation()))
1354       return false;
1355 
1356     if (Context.DeclMustBeEmitted(VD))
1357       return false;
1358 
1359     if (VD->isStaticDataMember() &&
1360         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1361       return false;
1362   } else {
1363     return false;
1364   }
1365 
1366   // Only warn for unused decls internal to the translation unit.
1367   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1368   // for inline functions defined in the main source file, for instance.
1369   return mightHaveNonExternalLinkage(D);
1370 }
1371 
1372 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1373   if (!D)
1374     return;
1375 
1376   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1377     const FunctionDecl *First = FD->getFirstDecl();
1378     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1379       return; // First should already be in the vector.
1380   }
1381 
1382   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1383     const VarDecl *First = VD->getFirstDecl();
1384     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1385       return; // First should already be in the vector.
1386   }
1387 
1388   if (ShouldWarnIfUnusedFileScopedDecl(D))
1389     UnusedFileScopedDecls.push_back(D);
1390 }
1391 
1392 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1393   if (D->isInvalidDecl())
1394     return false;
1395 
1396   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1397       D->hasAttr<ObjCPreciseLifetimeAttr>())
1398     return false;
1399 
1400   if (isa<LabelDecl>(D))
1401     return true;
1402 
1403   // Except for labels, we only care about unused decls that are local to
1404   // functions.
1405   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1406   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1407     // For dependent types, the diagnostic is deferred.
1408     WithinFunction =
1409         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1410   if (!WithinFunction)
1411     return false;
1412 
1413   if (isa<TypedefNameDecl>(D))
1414     return true;
1415 
1416   // White-list anything that isn't a local variable.
1417   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1418     return false;
1419 
1420   // Types of valid local variables should be complete, so this should succeed.
1421   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1422 
1423     // White-list anything with an __attribute__((unused)) type.
1424     QualType Ty = VD->getType();
1425 
1426     // Only look at the outermost level of typedef.
1427     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1428       if (TT->getDecl()->hasAttr<UnusedAttr>())
1429         return false;
1430     }
1431 
1432     // If we failed to complete the type for some reason, or if the type is
1433     // dependent, don't diagnose the variable.
1434     if (Ty->isIncompleteType() || Ty->isDependentType())
1435       return false;
1436 
1437     if (const TagType *TT = Ty->getAs<TagType>()) {
1438       const TagDecl *Tag = TT->getDecl();
1439       if (Tag->hasAttr<UnusedAttr>())
1440         return false;
1441 
1442       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1443         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1444           return false;
1445 
1446         if (const Expr *Init = VD->getInit()) {
1447           if (const ExprWithCleanups *Cleanups =
1448                   dyn_cast<ExprWithCleanups>(Init))
1449             Init = Cleanups->getSubExpr();
1450           const CXXConstructExpr *Construct =
1451             dyn_cast<CXXConstructExpr>(Init);
1452           if (Construct && !Construct->isElidable()) {
1453             CXXConstructorDecl *CD = Construct->getConstructor();
1454             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1455               return false;
1456           }
1457         }
1458       }
1459     }
1460 
1461     // TODO: __attribute__((unused)) templates?
1462   }
1463 
1464   return true;
1465 }
1466 
1467 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1468                                      FixItHint &Hint) {
1469   if (isa<LabelDecl>(D)) {
1470     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1471                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1472     if (AfterColon.isInvalid())
1473       return;
1474     Hint = FixItHint::CreateRemoval(CharSourceRange::
1475                                     getCharRange(D->getLocStart(), AfterColon));
1476   }
1477   return;
1478 }
1479 
1480 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1481   if (D->getTypeForDecl()->isDependentType())
1482     return;
1483 
1484   for (auto *TmpD : D->decls()) {
1485     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1486       DiagnoseUnusedDecl(T);
1487     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1488       DiagnoseUnusedNestedTypedefs(R);
1489   }
1490 }
1491 
1492 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1493 /// unless they are marked attr(unused).
1494 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1495   if (!ShouldDiagnoseUnusedDecl(D))
1496     return;
1497 
1498   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1499     // typedefs can be referenced later on, so the diagnostics are emitted
1500     // at end-of-translation-unit.
1501     UnusedLocalTypedefNameCandidates.insert(TD);
1502     return;
1503   }
1504 
1505   FixItHint Hint;
1506   GenerateFixForUnusedDecl(D, Context, Hint);
1507 
1508   unsigned DiagID;
1509   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1510     DiagID = diag::warn_unused_exception_param;
1511   else if (isa<LabelDecl>(D))
1512     DiagID = diag::warn_unused_label;
1513   else
1514     DiagID = diag::warn_unused_variable;
1515 
1516   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1517 }
1518 
1519 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1520   // Verify that we have no forward references left.  If so, there was a goto
1521   // or address of a label taken, but no definition of it.  Label fwd
1522   // definitions are indicated with a null substmt which is also not a resolved
1523   // MS inline assembly label name.
1524   bool Diagnose = false;
1525   if (L->isMSAsmLabel())
1526     Diagnose = !L->isResolvedMSAsmLabel();
1527   else
1528     Diagnose = L->getStmt() == nullptr;
1529   if (Diagnose)
1530     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1531 }
1532 
1533 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1534   S->mergeNRVOIntoParent();
1535 
1536   if (S->decl_empty()) return;
1537   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1538          "Scope shouldn't contain decls!");
1539 
1540   for (auto *TmpD : S->decls()) {
1541     assert(TmpD && "This decl didn't get pushed??");
1542 
1543     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1544     NamedDecl *D = cast<NamedDecl>(TmpD);
1545 
1546     if (!D->getDeclName()) continue;
1547 
1548     // Diagnose unused variables in this scope.
1549     if (!S->hasUnrecoverableErrorOccurred()) {
1550       DiagnoseUnusedDecl(D);
1551       if (const auto *RD = dyn_cast<RecordDecl>(D))
1552         DiagnoseUnusedNestedTypedefs(RD);
1553     }
1554 
1555     // If this was a forward reference to a label, verify it was defined.
1556     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1557       CheckPoppedLabel(LD, *this);
1558 
1559     // Remove this name from our lexical scope.
1560     IdResolver.RemoveDecl(D);
1561   }
1562 }
1563 
1564 /// \brief Look for an Objective-C class in the translation unit.
1565 ///
1566 /// \param Id The name of the Objective-C class we're looking for. If
1567 /// typo-correction fixes this name, the Id will be updated
1568 /// to the fixed name.
1569 ///
1570 /// \param IdLoc The location of the name in the translation unit.
1571 ///
1572 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1573 /// if there is no class with the given name.
1574 ///
1575 /// \returns The declaration of the named Objective-C class, or NULL if the
1576 /// class could not be found.
1577 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1578                                               SourceLocation IdLoc,
1579                                               bool DoTypoCorrection) {
1580   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1581   // creation from this context.
1582   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1583 
1584   if (!IDecl && DoTypoCorrection) {
1585     // Perform typo correction at the given location, but only if we
1586     // find an Objective-C class name.
1587     if (TypoCorrection C = CorrectTypo(
1588             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1589             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1590             CTK_ErrorRecovery)) {
1591       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1592       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1593       Id = IDecl->getIdentifier();
1594     }
1595   }
1596   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1597   // This routine must always return a class definition, if any.
1598   if (Def && Def->getDefinition())
1599       Def = Def->getDefinition();
1600   return Def;
1601 }
1602 
1603 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1604 /// from S, where a non-field would be declared. This routine copes
1605 /// with the difference between C and C++ scoping rules in structs and
1606 /// unions. For example, the following code is well-formed in C but
1607 /// ill-formed in C++:
1608 /// @code
1609 /// struct S6 {
1610 ///   enum { BAR } e;
1611 /// };
1612 ///
1613 /// void test_S6() {
1614 ///   struct S6 a;
1615 ///   a.e = BAR;
1616 /// }
1617 /// @endcode
1618 /// For the declaration of BAR, this routine will return a different
1619 /// scope. The scope S will be the scope of the unnamed enumeration
1620 /// within S6. In C++, this routine will return the scope associated
1621 /// with S6, because the enumeration's scope is a transparent
1622 /// context but structures can contain non-field names. In C, this
1623 /// routine will return the translation unit scope, since the
1624 /// enumeration's scope is a transparent context and structures cannot
1625 /// contain non-field names.
1626 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1627   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1628          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1629          (S->isClassScope() && !getLangOpts().CPlusPlus))
1630     S = S->getParent();
1631   return S;
1632 }
1633 
1634 /// \brief Looks up the declaration of "struct objc_super" and
1635 /// saves it for later use in building builtin declaration of
1636 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1637 /// pre-existing declaration exists no action takes place.
1638 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1639                                         IdentifierInfo *II) {
1640   if (!II->isStr("objc_msgSendSuper"))
1641     return;
1642   ASTContext &Context = ThisSema.Context;
1643 
1644   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1645                       SourceLocation(), Sema::LookupTagName);
1646   ThisSema.LookupName(Result, S);
1647   if (Result.getResultKind() == LookupResult::Found)
1648     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1649       Context.setObjCSuperType(Context.getTagDeclType(TD));
1650 }
1651 
1652 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1653   switch (Error) {
1654   case ASTContext::GE_None:
1655     return "";
1656   case ASTContext::GE_Missing_stdio:
1657     return "stdio.h";
1658   case ASTContext::GE_Missing_setjmp:
1659     return "setjmp.h";
1660   case ASTContext::GE_Missing_ucontext:
1661     return "ucontext.h";
1662   }
1663   llvm_unreachable("unhandled error kind");
1664 }
1665 
1666 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1667 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1668 /// if we're creating this built-in in anticipation of redeclaring the
1669 /// built-in.
1670 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1671                                      Scope *S, bool ForRedeclaration,
1672                                      SourceLocation Loc) {
1673   LookupPredefedObjCSuperType(*this, S, II);
1674 
1675   ASTContext::GetBuiltinTypeError Error;
1676   QualType R = Context.GetBuiltinType(ID, Error);
1677   if (Error) {
1678     if (ForRedeclaration)
1679       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1680           << getHeaderName(Error)
1681           << Context.BuiltinInfo.GetName(ID);
1682     return nullptr;
1683   }
1684 
1685   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1686     Diag(Loc, diag::ext_implicit_lib_function_decl)
1687       << Context.BuiltinInfo.GetName(ID)
1688       << R;
1689     if (Context.BuiltinInfo.getHeaderName(ID) &&
1690         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1691       Diag(Loc, diag::note_include_header_or_declare)
1692           << Context.BuiltinInfo.getHeaderName(ID)
1693           << Context.BuiltinInfo.GetName(ID);
1694   }
1695 
1696   DeclContext *Parent = Context.getTranslationUnitDecl();
1697   if (getLangOpts().CPlusPlus) {
1698     LinkageSpecDecl *CLinkageDecl =
1699         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1700                                 LinkageSpecDecl::lang_c, false);
1701     CLinkageDecl->setImplicit();
1702     Parent->addDecl(CLinkageDecl);
1703     Parent = CLinkageDecl;
1704   }
1705 
1706   FunctionDecl *New = FunctionDecl::Create(Context,
1707                                            Parent,
1708                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1709                                            SC_Extern,
1710                                            false,
1711                                            /*hasPrototype=*/true);
1712   New->setImplicit();
1713 
1714   // Create Decl objects for each parameter, adding them to the
1715   // FunctionDecl.
1716   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1717     SmallVector<ParmVarDecl*, 16> Params;
1718     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1719       ParmVarDecl *parm =
1720           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1721                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1722                               SC_None, nullptr);
1723       parm->setScopeInfo(0, i);
1724       Params.push_back(parm);
1725     }
1726     New->setParams(Params);
1727   }
1728 
1729   AddKnownFunctionAttributes(New);
1730   RegisterLocallyScopedExternCDecl(New, S);
1731 
1732   // TUScope is the translation-unit scope to insert this function into.
1733   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1734   // relate Scopes to DeclContexts, and probably eliminate CurContext
1735   // entirely, but we're not there yet.
1736   DeclContext *SavedContext = CurContext;
1737   CurContext = Parent;
1738   PushOnScopeChains(New, TUScope);
1739   CurContext = SavedContext;
1740   return New;
1741 }
1742 
1743 /// \brief Filter out any previous declarations that the given declaration
1744 /// should not consider because they are not permitted to conflict, e.g.,
1745 /// because they come from hidden sub-modules and do not refer to the same
1746 /// entity.
1747 static void filterNonConflictingPreviousDecls(ASTContext &context,
1748                                               NamedDecl *decl,
1749                                               LookupResult &previous){
1750   // This is only interesting when modules are enabled.
1751   if (!context.getLangOpts().Modules)
1752     return;
1753 
1754   // Empty sets are uninteresting.
1755   if (previous.empty())
1756     return;
1757 
1758   LookupResult::Filter filter = previous.makeFilter();
1759   while (filter.hasNext()) {
1760     NamedDecl *old = filter.next();
1761 
1762     // Non-hidden declarations are never ignored.
1763     if (!old->isHidden())
1764       continue;
1765 
1766     if (!old->isExternallyVisible())
1767       filter.erase();
1768   }
1769 
1770   filter.done();
1771 }
1772 
1773 /// Typedef declarations don't have linkage, but they still denote the same
1774 /// entity if their types are the same.
1775 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1776 /// isSameEntity.
1777 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context,
1778                                                      TypedefNameDecl *Decl,
1779                                                      LookupResult &Previous) {
1780   // This is only interesting when modules are enabled.
1781   if (!Context.getLangOpts().Modules)
1782     return;
1783 
1784   // Empty sets are uninteresting.
1785   if (Previous.empty())
1786     return;
1787 
1788   LookupResult::Filter Filter = Previous.makeFilter();
1789   while (Filter.hasNext()) {
1790     NamedDecl *Old = Filter.next();
1791 
1792     // Non-hidden declarations are never ignored.
1793     if (!Old->isHidden())
1794       continue;
1795 
1796     // Declarations of the same entity are not ignored, even if they have
1797     // different linkages.
1798     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old))
1799       if (Context.hasSameType(OldTD->getUnderlyingType(),
1800                               Decl->getUnderlyingType()))
1801         continue;
1802 
1803     if (!Old->isExternallyVisible())
1804       Filter.erase();
1805   }
1806 
1807   Filter.done();
1808 }
1809 
1810 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1811   QualType OldType;
1812   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1813     OldType = OldTypedef->getUnderlyingType();
1814   else
1815     OldType = Context.getTypeDeclType(Old);
1816   QualType NewType = New->getUnderlyingType();
1817 
1818   if (NewType->isVariablyModifiedType()) {
1819     // Must not redefine a typedef with a variably-modified type.
1820     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1821     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1822       << Kind << NewType;
1823     if (Old->getLocation().isValid())
1824       Diag(Old->getLocation(), diag::note_previous_definition);
1825     New->setInvalidDecl();
1826     return true;
1827   }
1828 
1829   if (OldType != NewType &&
1830       !OldType->isDependentType() &&
1831       !NewType->isDependentType() &&
1832       !Context.hasSameType(OldType, NewType)) {
1833     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1834     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1835       << Kind << NewType << OldType;
1836     if (Old->getLocation().isValid())
1837       Diag(Old->getLocation(), diag::note_previous_definition);
1838     New->setInvalidDecl();
1839     return true;
1840   }
1841   return false;
1842 }
1843 
1844 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1845 /// same name and scope as a previous declaration 'Old'.  Figure out
1846 /// how to resolve this situation, merging decls or emitting
1847 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1848 ///
1849 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1850   // If the new decl is known invalid already, don't bother doing any
1851   // merging checks.
1852   if (New->isInvalidDecl()) return;
1853 
1854   // Allow multiple definitions for ObjC built-in typedefs.
1855   // FIXME: Verify the underlying types are equivalent!
1856   if (getLangOpts().ObjC1) {
1857     const IdentifierInfo *TypeID = New->getIdentifier();
1858     switch (TypeID->getLength()) {
1859     default: break;
1860     case 2:
1861       {
1862         if (!TypeID->isStr("id"))
1863           break;
1864         QualType T = New->getUnderlyingType();
1865         if (!T->isPointerType())
1866           break;
1867         if (!T->isVoidPointerType()) {
1868           QualType PT = T->getAs<PointerType>()->getPointeeType();
1869           if (!PT->isStructureType())
1870             break;
1871         }
1872         Context.setObjCIdRedefinitionType(T);
1873         // Install the built-in type for 'id', ignoring the current definition.
1874         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1875         return;
1876       }
1877     case 5:
1878       if (!TypeID->isStr("Class"))
1879         break;
1880       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1881       // Install the built-in type for 'Class', ignoring the current definition.
1882       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1883       return;
1884     case 3:
1885       if (!TypeID->isStr("SEL"))
1886         break;
1887       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1888       // Install the built-in type for 'SEL', ignoring the current definition.
1889       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1890       return;
1891     }
1892     // Fall through - the typedef name was not a builtin type.
1893   }
1894 
1895   // Verify the old decl was also a type.
1896   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1897   if (!Old) {
1898     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1899       << New->getDeclName();
1900 
1901     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1902     if (OldD->getLocation().isValid())
1903       Diag(OldD->getLocation(), diag::note_previous_definition);
1904 
1905     return New->setInvalidDecl();
1906   }
1907 
1908   // If the old declaration is invalid, just give up here.
1909   if (Old->isInvalidDecl())
1910     return New->setInvalidDecl();
1911 
1912   // If the typedef types are not identical, reject them in all languages and
1913   // with any extensions enabled.
1914   if (isIncompatibleTypedef(Old, New))
1915     return;
1916 
1917   // The types match.  Link up the redeclaration chain and merge attributes if
1918   // the old declaration was a typedef.
1919   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1920     New->setPreviousDecl(Typedef);
1921     mergeDeclAttributes(New, Old);
1922   }
1923 
1924   if (getLangOpts().MicrosoftExt)
1925     return;
1926 
1927   if (getLangOpts().CPlusPlus) {
1928     // C++ [dcl.typedef]p2:
1929     //   In a given non-class scope, a typedef specifier can be used to
1930     //   redefine the name of any type declared in that scope to refer
1931     //   to the type to which it already refers.
1932     if (!isa<CXXRecordDecl>(CurContext))
1933       return;
1934 
1935     // C++0x [dcl.typedef]p4:
1936     //   In a given class scope, a typedef specifier can be used to redefine
1937     //   any class-name declared in that scope that is not also a typedef-name
1938     //   to refer to the type to which it already refers.
1939     //
1940     // This wording came in via DR424, which was a correction to the
1941     // wording in DR56, which accidentally banned code like:
1942     //
1943     //   struct S {
1944     //     typedef struct A { } A;
1945     //   };
1946     //
1947     // in the C++03 standard. We implement the C++0x semantics, which
1948     // allow the above but disallow
1949     //
1950     //   struct S {
1951     //     typedef int I;
1952     //     typedef int I;
1953     //   };
1954     //
1955     // since that was the intent of DR56.
1956     if (!isa<TypedefNameDecl>(Old))
1957       return;
1958 
1959     Diag(New->getLocation(), diag::err_redefinition)
1960       << New->getDeclName();
1961     Diag(Old->getLocation(), diag::note_previous_definition);
1962     return New->setInvalidDecl();
1963   }
1964 
1965   // Modules always permit redefinition of typedefs, as does C11.
1966   if (getLangOpts().Modules || getLangOpts().C11)
1967     return;
1968 
1969   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1970   // is normally mapped to an error, but can be controlled with
1971   // -Wtypedef-redefinition.  If either the original or the redefinition is
1972   // in a system header, don't emit this for compatibility with GCC.
1973   if (getDiagnostics().getSuppressSystemWarnings() &&
1974       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1975        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1976     return;
1977 
1978   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
1979     << New->getDeclName();
1980   Diag(Old->getLocation(), diag::note_previous_definition);
1981   return;
1982 }
1983 
1984 /// DeclhasAttr - returns true if decl Declaration already has the target
1985 /// attribute.
1986 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1987   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1988   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1989   for (const auto *i : D->attrs())
1990     if (i->getKind() == A->getKind()) {
1991       if (Ann) {
1992         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
1993           return true;
1994         continue;
1995       }
1996       // FIXME: Don't hardcode this check
1997       if (OA && isa<OwnershipAttr>(i))
1998         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
1999       return true;
2000     }
2001 
2002   return false;
2003 }
2004 
2005 static bool isAttributeTargetADefinition(Decl *D) {
2006   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2007     return VD->isThisDeclarationADefinition();
2008   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2009     return TD->isCompleteDefinition() || TD->isBeingDefined();
2010   return true;
2011 }
2012 
2013 /// Merge alignment attributes from \p Old to \p New, taking into account the
2014 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2015 ///
2016 /// \return \c true if any attributes were added to \p New.
2017 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2018   // Look for alignas attributes on Old, and pick out whichever attribute
2019   // specifies the strictest alignment requirement.
2020   AlignedAttr *OldAlignasAttr = nullptr;
2021   AlignedAttr *OldStrictestAlignAttr = nullptr;
2022   unsigned OldAlign = 0;
2023   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2024     // FIXME: We have no way of representing inherited dependent alignments
2025     // in a case like:
2026     //   template<int A, int B> struct alignas(A) X;
2027     //   template<int A, int B> struct alignas(B) X {};
2028     // For now, we just ignore any alignas attributes which are not on the
2029     // definition in such a case.
2030     if (I->isAlignmentDependent())
2031       return false;
2032 
2033     if (I->isAlignas())
2034       OldAlignasAttr = I;
2035 
2036     unsigned Align = I->getAlignment(S.Context);
2037     if (Align > OldAlign) {
2038       OldAlign = Align;
2039       OldStrictestAlignAttr = I;
2040     }
2041   }
2042 
2043   // Look for alignas attributes on New.
2044   AlignedAttr *NewAlignasAttr = nullptr;
2045   unsigned NewAlign = 0;
2046   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2047     if (I->isAlignmentDependent())
2048       return false;
2049 
2050     if (I->isAlignas())
2051       NewAlignasAttr = I;
2052 
2053     unsigned Align = I->getAlignment(S.Context);
2054     if (Align > NewAlign)
2055       NewAlign = Align;
2056   }
2057 
2058   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2059     // Both declarations have 'alignas' attributes. We require them to match.
2060     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2061     // fall short. (If two declarations both have alignas, they must both match
2062     // every definition, and so must match each other if there is a definition.)
2063 
2064     // If either declaration only contains 'alignas(0)' specifiers, then it
2065     // specifies the natural alignment for the type.
2066     if (OldAlign == 0 || NewAlign == 0) {
2067       QualType Ty;
2068       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2069         Ty = VD->getType();
2070       else
2071         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2072 
2073       if (OldAlign == 0)
2074         OldAlign = S.Context.getTypeAlign(Ty);
2075       if (NewAlign == 0)
2076         NewAlign = S.Context.getTypeAlign(Ty);
2077     }
2078 
2079     if (OldAlign != NewAlign) {
2080       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2081         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2082         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2083       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2084     }
2085   }
2086 
2087   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2088     // C++11 [dcl.align]p6:
2089     //   if any declaration of an entity has an alignment-specifier,
2090     //   every defining declaration of that entity shall specify an
2091     //   equivalent alignment.
2092     // C11 6.7.5/7:
2093     //   If the definition of an object does not have an alignment
2094     //   specifier, any other declaration of that object shall also
2095     //   have no alignment specifier.
2096     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2097       << OldAlignasAttr;
2098     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2099       << OldAlignasAttr;
2100   }
2101 
2102   bool AnyAdded = false;
2103 
2104   // Ensure we have an attribute representing the strictest alignment.
2105   if (OldAlign > NewAlign) {
2106     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2107     Clone->setInherited(true);
2108     New->addAttr(Clone);
2109     AnyAdded = true;
2110   }
2111 
2112   // Ensure we have an alignas attribute if the old declaration had one.
2113   if (OldAlignasAttr && !NewAlignasAttr &&
2114       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2115     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2116     Clone->setInherited(true);
2117     New->addAttr(Clone);
2118     AnyAdded = true;
2119   }
2120 
2121   return AnyAdded;
2122 }
2123 
2124 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2125                                const InheritableAttr *Attr, bool Override) {
2126   InheritableAttr *NewAttr = nullptr;
2127   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2128   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2129     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2130                                       AA->getIntroduced(), AA->getDeprecated(),
2131                                       AA->getObsoleted(), AA->getUnavailable(),
2132                                       AA->getMessage(), Override,
2133                                       AttrSpellingListIndex);
2134   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2135     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2136                                     AttrSpellingListIndex);
2137   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2138     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2139                                         AttrSpellingListIndex);
2140   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2141     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2142                                    AttrSpellingListIndex);
2143   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2144     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2145                                    AttrSpellingListIndex);
2146   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2147     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2148                                 FA->getFormatIdx(), FA->getFirstArg(),
2149                                 AttrSpellingListIndex);
2150   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2151     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2152                                  AttrSpellingListIndex);
2153   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2154     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2155                                        AttrSpellingListIndex,
2156                                        IA->getSemanticSpelling());
2157   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2158     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), AttrSpellingListIndex);
2159   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2160     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2161   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2162     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2163   else if (isa<AlignedAttr>(Attr))
2164     // AlignedAttrs are handled separately, because we need to handle all
2165     // such attributes on a declaration at the same time.
2166     NewAttr = nullptr;
2167   else if (isa<DeprecatedAttr>(Attr) && Override)
2168     NewAttr = nullptr;
2169   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2170     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2171 
2172   if (NewAttr) {
2173     NewAttr->setInherited(true);
2174     D->addAttr(NewAttr);
2175     return true;
2176   }
2177 
2178   return false;
2179 }
2180 
2181 static const Decl *getDefinition(const Decl *D) {
2182   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2183     return TD->getDefinition();
2184   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2185     const VarDecl *Def = VD->getDefinition();
2186     if (Def)
2187       return Def;
2188     return VD->getActingDefinition();
2189   }
2190   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2191     const FunctionDecl* Def;
2192     if (FD->isDefined(Def))
2193       return Def;
2194   }
2195   return nullptr;
2196 }
2197 
2198 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2199   for (const auto *Attribute : D->attrs())
2200     if (Attribute->getKind() == Kind)
2201       return true;
2202   return false;
2203 }
2204 
2205 /// checkNewAttributesAfterDef - If we already have a definition, check that
2206 /// there are no new attributes in this declaration.
2207 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2208   if (!New->hasAttrs())
2209     return;
2210 
2211   const Decl *Def = getDefinition(Old);
2212   if (!Def || Def == New)
2213     return;
2214 
2215   AttrVec &NewAttributes = New->getAttrs();
2216   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2217     const Attr *NewAttribute = NewAttributes[I];
2218 
2219     if (isa<AliasAttr>(NewAttribute)) {
2220       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2221         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2222       else {
2223         VarDecl *VD = cast<VarDecl>(New);
2224         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2225                                 VarDecl::TentativeDefinition
2226                             ? diag::err_alias_after_tentative
2227                             : diag::err_redefinition;
2228         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2229         S.Diag(Def->getLocation(), diag::note_previous_definition);
2230         VD->setInvalidDecl();
2231       }
2232       ++I;
2233       continue;
2234     }
2235 
2236     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2237       // Tentative definitions are only interesting for the alias check above.
2238       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2239         ++I;
2240         continue;
2241       }
2242     }
2243 
2244     if (hasAttribute(Def, NewAttribute->getKind())) {
2245       ++I;
2246       continue; // regular attr merging will take care of validating this.
2247     }
2248 
2249     if (isa<C11NoReturnAttr>(NewAttribute)) {
2250       // C's _Noreturn is allowed to be added to a function after it is defined.
2251       ++I;
2252       continue;
2253     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2254       if (AA->isAlignas()) {
2255         // C++11 [dcl.align]p6:
2256         //   if any declaration of an entity has an alignment-specifier,
2257         //   every defining declaration of that entity shall specify an
2258         //   equivalent alignment.
2259         // C11 6.7.5/7:
2260         //   If the definition of an object does not have an alignment
2261         //   specifier, any other declaration of that object shall also
2262         //   have no alignment specifier.
2263         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2264           << AA;
2265         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2266           << AA;
2267         NewAttributes.erase(NewAttributes.begin() + I);
2268         --E;
2269         continue;
2270       }
2271     }
2272 
2273     S.Diag(NewAttribute->getLocation(),
2274            diag::warn_attribute_precede_definition);
2275     S.Diag(Def->getLocation(), diag::note_previous_definition);
2276     NewAttributes.erase(NewAttributes.begin() + I);
2277     --E;
2278   }
2279 }
2280 
2281 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2282 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2283                                AvailabilityMergeKind AMK) {
2284   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2285     UsedAttr *NewAttr = OldAttr->clone(Context);
2286     NewAttr->setInherited(true);
2287     New->addAttr(NewAttr);
2288   }
2289 
2290   if (!Old->hasAttrs() && !New->hasAttrs())
2291     return;
2292 
2293   // attributes declared post-definition are currently ignored
2294   checkNewAttributesAfterDef(*this, New, Old);
2295 
2296   if (!Old->hasAttrs())
2297     return;
2298 
2299   bool foundAny = New->hasAttrs();
2300 
2301   // Ensure that any moving of objects within the allocated map is done before
2302   // we process them.
2303   if (!foundAny) New->setAttrs(AttrVec());
2304 
2305   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2306     bool Override = false;
2307     // Ignore deprecated/unavailable/availability attributes if requested.
2308     if (isa<DeprecatedAttr>(I) ||
2309         isa<UnavailableAttr>(I) ||
2310         isa<AvailabilityAttr>(I)) {
2311       switch (AMK) {
2312       case AMK_None:
2313         continue;
2314 
2315       case AMK_Redeclaration:
2316         break;
2317 
2318       case AMK_Override:
2319         Override = true;
2320         break;
2321       }
2322     }
2323 
2324     // Already handled.
2325     if (isa<UsedAttr>(I))
2326       continue;
2327 
2328     if (mergeDeclAttribute(*this, New, I, Override))
2329       foundAny = true;
2330   }
2331 
2332   if (mergeAlignedAttrs(*this, New, Old))
2333     foundAny = true;
2334 
2335   if (!foundAny) New->dropAttrs();
2336 }
2337 
2338 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2339 /// to the new one.
2340 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2341                                      const ParmVarDecl *oldDecl,
2342                                      Sema &S) {
2343   // C++11 [dcl.attr.depend]p2:
2344   //   The first declaration of a function shall specify the
2345   //   carries_dependency attribute for its declarator-id if any declaration
2346   //   of the function specifies the carries_dependency attribute.
2347   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2348   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2349     S.Diag(CDA->getLocation(),
2350            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2351     // Find the first declaration of the parameter.
2352     // FIXME: Should we build redeclaration chains for function parameters?
2353     const FunctionDecl *FirstFD =
2354       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2355     const ParmVarDecl *FirstVD =
2356       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2357     S.Diag(FirstVD->getLocation(),
2358            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2359   }
2360 
2361   if (!oldDecl->hasAttrs())
2362     return;
2363 
2364   bool foundAny = newDecl->hasAttrs();
2365 
2366   // Ensure that any moving of objects within the allocated map is
2367   // done before we process them.
2368   if (!foundAny) newDecl->setAttrs(AttrVec());
2369 
2370   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2371     if (!DeclHasAttr(newDecl, I)) {
2372       InheritableAttr *newAttr =
2373         cast<InheritableParamAttr>(I->clone(S.Context));
2374       newAttr->setInherited(true);
2375       newDecl->addAttr(newAttr);
2376       foundAny = true;
2377     }
2378   }
2379 
2380   if (!foundAny) newDecl->dropAttrs();
2381 }
2382 
2383 namespace {
2384 
2385 /// Used in MergeFunctionDecl to keep track of function parameters in
2386 /// C.
2387 struct GNUCompatibleParamWarning {
2388   ParmVarDecl *OldParm;
2389   ParmVarDecl *NewParm;
2390   QualType PromotedType;
2391 };
2392 
2393 }
2394 
2395 /// getSpecialMember - get the special member enum for a method.
2396 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2397   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2398     if (Ctor->isDefaultConstructor())
2399       return Sema::CXXDefaultConstructor;
2400 
2401     if (Ctor->isCopyConstructor())
2402       return Sema::CXXCopyConstructor;
2403 
2404     if (Ctor->isMoveConstructor())
2405       return Sema::CXXMoveConstructor;
2406   } else if (isa<CXXDestructorDecl>(MD)) {
2407     return Sema::CXXDestructor;
2408   } else if (MD->isCopyAssignmentOperator()) {
2409     return Sema::CXXCopyAssignment;
2410   } else if (MD->isMoveAssignmentOperator()) {
2411     return Sema::CXXMoveAssignment;
2412   }
2413 
2414   return Sema::CXXInvalid;
2415 }
2416 
2417 // Determine whether the previous declaration was a definition, implicit
2418 // declaration, or a declaration.
2419 template <typename T>
2420 static std::pair<diag::kind, SourceLocation>
2421 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2422   diag::kind PrevDiag;
2423   SourceLocation OldLocation = Old->getLocation();
2424   if (Old->isThisDeclarationADefinition())
2425     PrevDiag = diag::note_previous_definition;
2426   else if (Old->isImplicit()) {
2427     PrevDiag = diag::note_previous_implicit_declaration;
2428     if (OldLocation.isInvalid())
2429       OldLocation = New->getLocation();
2430   } else
2431     PrevDiag = diag::note_previous_declaration;
2432   return std::make_pair(PrevDiag, OldLocation);
2433 }
2434 
2435 /// canRedefineFunction - checks if a function can be redefined. Currently,
2436 /// only extern inline functions can be redefined, and even then only in
2437 /// GNU89 mode.
2438 static bool canRedefineFunction(const FunctionDecl *FD,
2439                                 const LangOptions& LangOpts) {
2440   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2441           !LangOpts.CPlusPlus &&
2442           FD->isInlineSpecified() &&
2443           FD->getStorageClass() == SC_Extern);
2444 }
2445 
2446 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2447   const AttributedType *AT = T->getAs<AttributedType>();
2448   while (AT && !AT->isCallingConv())
2449     AT = AT->getModifiedType()->getAs<AttributedType>();
2450   return AT;
2451 }
2452 
2453 template <typename T>
2454 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2455   const DeclContext *DC = Old->getDeclContext();
2456   if (DC->isRecord())
2457     return false;
2458 
2459   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2460   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2461     return true;
2462   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2463     return true;
2464   return false;
2465 }
2466 
2467 /// MergeFunctionDecl - We just parsed a function 'New' from
2468 /// declarator D which has the same name and scope as a previous
2469 /// declaration 'Old'.  Figure out how to resolve this situation,
2470 /// merging decls or emitting diagnostics as appropriate.
2471 ///
2472 /// In C++, New and Old must be declarations that are not
2473 /// overloaded. Use IsOverload to determine whether New and Old are
2474 /// overloaded, and to select the Old declaration that New should be
2475 /// merged with.
2476 ///
2477 /// Returns true if there was an error, false otherwise.
2478 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2479                              Scope *S, bool MergeTypeWithOld) {
2480   // Verify the old decl was also a function.
2481   FunctionDecl *Old = OldD->getAsFunction();
2482   if (!Old) {
2483     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2484       if (New->getFriendObjectKind()) {
2485         Diag(New->getLocation(), diag::err_using_decl_friend);
2486         Diag(Shadow->getTargetDecl()->getLocation(),
2487              diag::note_using_decl_target);
2488         Diag(Shadow->getUsingDecl()->getLocation(),
2489              diag::note_using_decl) << 0;
2490         return true;
2491       }
2492 
2493       // C++11 [namespace.udecl]p14:
2494       //   If a function declaration in namespace scope or block scope has the
2495       //   same name and the same parameter-type-list as a function introduced
2496       //   by a using-declaration, and the declarations do not declare the same
2497       //   function, the program is ill-formed.
2498 
2499       // Check whether the two declarations might declare the same function.
2500       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2501       if (Old &&
2502           !Old->getDeclContext()->getRedeclContext()->Equals(
2503               New->getDeclContext()->getRedeclContext()) &&
2504           !(Old->isExternC() && New->isExternC()))
2505         Old = nullptr;
2506 
2507       if (!Old) {
2508         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2509         Diag(Shadow->getTargetDecl()->getLocation(),
2510              diag::note_using_decl_target);
2511         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2512         return true;
2513       }
2514       OldD = Old;
2515     } else {
2516       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2517         << New->getDeclName();
2518       Diag(OldD->getLocation(), diag::note_previous_definition);
2519       return true;
2520     }
2521   }
2522 
2523   // If the old declaration is invalid, just give up here.
2524   if (Old->isInvalidDecl())
2525     return true;
2526 
2527   diag::kind PrevDiag;
2528   SourceLocation OldLocation;
2529   std::tie(PrevDiag, OldLocation) =
2530       getNoteDiagForInvalidRedeclaration(Old, New);
2531 
2532   // Don't complain about this if we're in GNU89 mode and the old function
2533   // is an extern inline function.
2534   // Don't complain about specializations. They are not supposed to have
2535   // storage classes.
2536   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2537       New->getStorageClass() == SC_Static &&
2538       Old->hasExternalFormalLinkage() &&
2539       !New->getTemplateSpecializationInfo() &&
2540       !canRedefineFunction(Old, getLangOpts())) {
2541     if (getLangOpts().MicrosoftExt) {
2542       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2543       Diag(OldLocation, PrevDiag);
2544     } else {
2545       Diag(New->getLocation(), diag::err_static_non_static) << New;
2546       Diag(OldLocation, PrevDiag);
2547       return true;
2548     }
2549   }
2550 
2551 
2552   // If a function is first declared with a calling convention, but is later
2553   // declared or defined without one, all following decls assume the calling
2554   // convention of the first.
2555   //
2556   // It's OK if a function is first declared without a calling convention,
2557   // but is later declared or defined with the default calling convention.
2558   //
2559   // To test if either decl has an explicit calling convention, we look for
2560   // AttributedType sugar nodes on the type as written.  If they are missing or
2561   // were canonicalized away, we assume the calling convention was implicit.
2562   //
2563   // Note also that we DO NOT return at this point, because we still have
2564   // other tests to run.
2565   QualType OldQType = Context.getCanonicalType(Old->getType());
2566   QualType NewQType = Context.getCanonicalType(New->getType());
2567   const FunctionType *OldType = cast<FunctionType>(OldQType);
2568   const FunctionType *NewType = cast<FunctionType>(NewQType);
2569   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2570   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2571   bool RequiresAdjustment = false;
2572 
2573   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2574     FunctionDecl *First = Old->getFirstDecl();
2575     const FunctionType *FT =
2576         First->getType().getCanonicalType()->castAs<FunctionType>();
2577     FunctionType::ExtInfo FI = FT->getExtInfo();
2578     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2579     if (!NewCCExplicit) {
2580       // Inherit the CC from the previous declaration if it was specified
2581       // there but not here.
2582       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2583       RequiresAdjustment = true;
2584     } else {
2585       // Calling conventions aren't compatible, so complain.
2586       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2587       Diag(New->getLocation(), diag::err_cconv_change)
2588         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2589         << !FirstCCExplicit
2590         << (!FirstCCExplicit ? "" :
2591             FunctionType::getNameForCallConv(FI.getCC()));
2592 
2593       // Put the note on the first decl, since it is the one that matters.
2594       Diag(First->getLocation(), diag::note_previous_declaration);
2595       return true;
2596     }
2597   }
2598 
2599   // FIXME: diagnose the other way around?
2600   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2601     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2602     RequiresAdjustment = true;
2603   }
2604 
2605   // Merge regparm attribute.
2606   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2607       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2608     if (NewTypeInfo.getHasRegParm()) {
2609       Diag(New->getLocation(), diag::err_regparm_mismatch)
2610         << NewType->getRegParmType()
2611         << OldType->getRegParmType();
2612       Diag(OldLocation, diag::note_previous_declaration);
2613       return true;
2614     }
2615 
2616     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2617     RequiresAdjustment = true;
2618   }
2619 
2620   // Merge ns_returns_retained attribute.
2621   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2622     if (NewTypeInfo.getProducesResult()) {
2623       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2624       Diag(OldLocation, diag::note_previous_declaration);
2625       return true;
2626     }
2627 
2628     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2629     RequiresAdjustment = true;
2630   }
2631 
2632   if (RequiresAdjustment) {
2633     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2634     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2635     New->setType(QualType(AdjustedType, 0));
2636     NewQType = Context.getCanonicalType(New->getType());
2637     NewType = cast<FunctionType>(NewQType);
2638   }
2639 
2640   // If this redeclaration makes the function inline, we may need to add it to
2641   // UndefinedButUsed.
2642   if (!Old->isInlined() && New->isInlined() &&
2643       !New->hasAttr<GNUInlineAttr>() &&
2644       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2645       Old->isUsed(false) &&
2646       !Old->isDefined() && !New->isThisDeclarationADefinition())
2647     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2648                                            SourceLocation()));
2649 
2650   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2651   // about it.
2652   if (New->hasAttr<GNUInlineAttr>() &&
2653       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2654     UndefinedButUsed.erase(Old->getCanonicalDecl());
2655   }
2656 
2657   if (getLangOpts().CPlusPlus) {
2658     // (C++98 13.1p2):
2659     //   Certain function declarations cannot be overloaded:
2660     //     -- Function declarations that differ only in the return type
2661     //        cannot be overloaded.
2662 
2663     // Go back to the type source info to compare the declared return types,
2664     // per C++1y [dcl.type.auto]p13:
2665     //   Redeclarations or specializations of a function or function template
2666     //   with a declared return type that uses a placeholder type shall also
2667     //   use that placeholder, not a deduced type.
2668     QualType OldDeclaredReturnType =
2669         (Old->getTypeSourceInfo()
2670              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2671              : OldType)->getReturnType();
2672     QualType NewDeclaredReturnType =
2673         (New->getTypeSourceInfo()
2674              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2675              : NewType)->getReturnType();
2676     QualType ResQT;
2677     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2678         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2679           New->isLocalExternDecl())) {
2680       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2681           OldDeclaredReturnType->isObjCObjectPointerType())
2682         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2683       if (ResQT.isNull()) {
2684         if (New->isCXXClassMember() && New->isOutOfLine())
2685           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2686               << New << New->getReturnTypeSourceRange();
2687         else
2688           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2689               << New->getReturnTypeSourceRange();
2690         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2691                                     << Old->getReturnTypeSourceRange();
2692         return true;
2693       }
2694       else
2695         NewQType = ResQT;
2696     }
2697 
2698     QualType OldReturnType = OldType->getReturnType();
2699     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2700     if (OldReturnType != NewReturnType) {
2701       // If this function has a deduced return type and has already been
2702       // defined, copy the deduced value from the old declaration.
2703       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2704       if (OldAT && OldAT->isDeduced()) {
2705         New->setType(
2706             SubstAutoType(New->getType(),
2707                           OldAT->isDependentType() ? Context.DependentTy
2708                                                    : OldAT->getDeducedType()));
2709         NewQType = Context.getCanonicalType(
2710             SubstAutoType(NewQType,
2711                           OldAT->isDependentType() ? Context.DependentTy
2712                                                    : OldAT->getDeducedType()));
2713       }
2714     }
2715 
2716     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2717     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2718     if (OldMethod && NewMethod) {
2719       // Preserve triviality.
2720       NewMethod->setTrivial(OldMethod->isTrivial());
2721 
2722       // MSVC allows explicit template specialization at class scope:
2723       // 2 CXXMethodDecls referring to the same function will be injected.
2724       // We don't want a redeclaration error.
2725       bool IsClassScopeExplicitSpecialization =
2726                               OldMethod->isFunctionTemplateSpecialization() &&
2727                               NewMethod->isFunctionTemplateSpecialization();
2728       bool isFriend = NewMethod->getFriendObjectKind();
2729 
2730       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2731           !IsClassScopeExplicitSpecialization) {
2732         //    -- Member function declarations with the same name and the
2733         //       same parameter types cannot be overloaded if any of them
2734         //       is a static member function declaration.
2735         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2736           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2737           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2738           return true;
2739         }
2740 
2741         // C++ [class.mem]p1:
2742         //   [...] A member shall not be declared twice in the
2743         //   member-specification, except that a nested class or member
2744         //   class template can be declared and then later defined.
2745         if (ActiveTemplateInstantiations.empty()) {
2746           unsigned NewDiag;
2747           if (isa<CXXConstructorDecl>(OldMethod))
2748             NewDiag = diag::err_constructor_redeclared;
2749           else if (isa<CXXDestructorDecl>(NewMethod))
2750             NewDiag = diag::err_destructor_redeclared;
2751           else if (isa<CXXConversionDecl>(NewMethod))
2752             NewDiag = diag::err_conv_function_redeclared;
2753           else
2754             NewDiag = diag::err_member_redeclared;
2755 
2756           Diag(New->getLocation(), NewDiag);
2757         } else {
2758           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2759             << New << New->getType();
2760         }
2761         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2762 
2763       // Complain if this is an explicit declaration of a special
2764       // member that was initially declared implicitly.
2765       //
2766       // As an exception, it's okay to befriend such methods in order
2767       // to permit the implicit constructor/destructor/operator calls.
2768       } else if (OldMethod->isImplicit()) {
2769         if (isFriend) {
2770           NewMethod->setImplicit();
2771         } else {
2772           Diag(NewMethod->getLocation(),
2773                diag::err_definition_of_implicitly_declared_member)
2774             << New << getSpecialMember(OldMethod);
2775           return true;
2776         }
2777       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2778         Diag(NewMethod->getLocation(),
2779              diag::err_definition_of_explicitly_defaulted_member)
2780           << getSpecialMember(OldMethod);
2781         return true;
2782       }
2783     }
2784 
2785     // C++11 [dcl.attr.noreturn]p1:
2786     //   The first declaration of a function shall specify the noreturn
2787     //   attribute if any declaration of that function specifies the noreturn
2788     //   attribute.
2789     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2790     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2791       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2792       Diag(Old->getFirstDecl()->getLocation(),
2793            diag::note_noreturn_missing_first_decl);
2794     }
2795 
2796     // C++11 [dcl.attr.depend]p2:
2797     //   The first declaration of a function shall specify the
2798     //   carries_dependency attribute for its declarator-id if any declaration
2799     //   of the function specifies the carries_dependency attribute.
2800     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2801     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2802       Diag(CDA->getLocation(),
2803            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2804       Diag(Old->getFirstDecl()->getLocation(),
2805            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2806     }
2807 
2808     // (C++98 8.3.5p3):
2809     //   All declarations for a function shall agree exactly in both the
2810     //   return type and the parameter-type-list.
2811     // We also want to respect all the extended bits except noreturn.
2812 
2813     // noreturn should now match unless the old type info didn't have it.
2814     QualType OldQTypeForComparison = OldQType;
2815     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2816       assert(OldQType == QualType(OldType, 0));
2817       const FunctionType *OldTypeForComparison
2818         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2819       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2820       assert(OldQTypeForComparison.isCanonical());
2821     }
2822 
2823     if (haveIncompatibleLanguageLinkages(Old, New)) {
2824       // As a special case, retain the language linkage from previous
2825       // declarations of a friend function as an extension.
2826       //
2827       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2828       // and is useful because there's otherwise no way to specify language
2829       // linkage within class scope.
2830       //
2831       // Check cautiously as the friend object kind isn't yet complete.
2832       if (New->getFriendObjectKind() != Decl::FOK_None) {
2833         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2834         Diag(OldLocation, PrevDiag);
2835       } else {
2836         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2837         Diag(OldLocation, PrevDiag);
2838         return true;
2839       }
2840     }
2841 
2842     if (OldQTypeForComparison == NewQType)
2843       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2844 
2845     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2846         New->isLocalExternDecl()) {
2847       // It's OK if we couldn't merge types for a local function declaraton
2848       // if either the old or new type is dependent. We'll merge the types
2849       // when we instantiate the function.
2850       return false;
2851     }
2852 
2853     // Fall through for conflicting redeclarations and redefinitions.
2854   }
2855 
2856   // C: Function types need to be compatible, not identical. This handles
2857   // duplicate function decls like "void f(int); void f(enum X);" properly.
2858   if (!getLangOpts().CPlusPlus &&
2859       Context.typesAreCompatible(OldQType, NewQType)) {
2860     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2861     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2862     const FunctionProtoType *OldProto = nullptr;
2863     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2864         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2865       // The old declaration provided a function prototype, but the
2866       // new declaration does not. Merge in the prototype.
2867       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2868       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2869       NewQType =
2870           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2871                                   OldProto->getExtProtoInfo());
2872       New->setType(NewQType);
2873       New->setHasInheritedPrototype();
2874 
2875       // Synthesize parameters with the same types.
2876       SmallVector<ParmVarDecl*, 16> Params;
2877       for (const auto &ParamType : OldProto->param_types()) {
2878         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2879                                                  SourceLocation(), nullptr,
2880                                                  ParamType, /*TInfo=*/nullptr,
2881                                                  SC_None, nullptr);
2882         Param->setScopeInfo(0, Params.size());
2883         Param->setImplicit();
2884         Params.push_back(Param);
2885       }
2886 
2887       New->setParams(Params);
2888     }
2889 
2890     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2891   }
2892 
2893   // GNU C permits a K&R definition to follow a prototype declaration
2894   // if the declared types of the parameters in the K&R definition
2895   // match the types in the prototype declaration, even when the
2896   // promoted types of the parameters from the K&R definition differ
2897   // from the types in the prototype. GCC then keeps the types from
2898   // the prototype.
2899   //
2900   // If a variadic prototype is followed by a non-variadic K&R definition,
2901   // the K&R definition becomes variadic.  This is sort of an edge case, but
2902   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2903   // C99 6.9.1p8.
2904   if (!getLangOpts().CPlusPlus &&
2905       Old->hasPrototype() && !New->hasPrototype() &&
2906       New->getType()->getAs<FunctionProtoType>() &&
2907       Old->getNumParams() == New->getNumParams()) {
2908     SmallVector<QualType, 16> ArgTypes;
2909     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2910     const FunctionProtoType *OldProto
2911       = Old->getType()->getAs<FunctionProtoType>();
2912     const FunctionProtoType *NewProto
2913       = New->getType()->getAs<FunctionProtoType>();
2914 
2915     // Determine whether this is the GNU C extension.
2916     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2917                                                NewProto->getReturnType());
2918     bool LooseCompatible = !MergedReturn.isNull();
2919     for (unsigned Idx = 0, End = Old->getNumParams();
2920          LooseCompatible && Idx != End; ++Idx) {
2921       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2922       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2923       if (Context.typesAreCompatible(OldParm->getType(),
2924                                      NewProto->getParamType(Idx))) {
2925         ArgTypes.push_back(NewParm->getType());
2926       } else if (Context.typesAreCompatible(OldParm->getType(),
2927                                             NewParm->getType(),
2928                                             /*CompareUnqualified=*/true)) {
2929         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2930                                            NewProto->getParamType(Idx) };
2931         Warnings.push_back(Warn);
2932         ArgTypes.push_back(NewParm->getType());
2933       } else
2934         LooseCompatible = false;
2935     }
2936 
2937     if (LooseCompatible) {
2938       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2939         Diag(Warnings[Warn].NewParm->getLocation(),
2940              diag::ext_param_promoted_not_compatible_with_prototype)
2941           << Warnings[Warn].PromotedType
2942           << Warnings[Warn].OldParm->getType();
2943         if (Warnings[Warn].OldParm->getLocation().isValid())
2944           Diag(Warnings[Warn].OldParm->getLocation(),
2945                diag::note_previous_declaration);
2946       }
2947 
2948       if (MergeTypeWithOld)
2949         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2950                                              OldProto->getExtProtoInfo()));
2951       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2952     }
2953 
2954     // Fall through to diagnose conflicting types.
2955   }
2956 
2957   // A function that has already been declared has been redeclared or
2958   // defined with a different type; show an appropriate diagnostic.
2959 
2960   // If the previous declaration was an implicitly-generated builtin
2961   // declaration, then at the very least we should use a specialized note.
2962   unsigned BuiltinID;
2963   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2964     // If it's actually a library-defined builtin function like 'malloc'
2965     // or 'printf', just warn about the incompatible redeclaration.
2966     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2967       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2968       Diag(OldLocation, diag::note_previous_builtin_declaration)
2969         << Old << Old->getType();
2970 
2971       // If this is a global redeclaration, just forget hereafter
2972       // about the "builtin-ness" of the function.
2973       //
2974       // Doing this for local extern declarations is problematic.  If
2975       // the builtin declaration remains visible, a second invalid
2976       // local declaration will produce a hard error; if it doesn't
2977       // remain visible, a single bogus local redeclaration (which is
2978       // actually only a warning) could break all the downstream code.
2979       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2980         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2981 
2982       return false;
2983     }
2984 
2985     PrevDiag = diag::note_previous_builtin_declaration;
2986   }
2987 
2988   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2989   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2990   return true;
2991 }
2992 
2993 /// \brief Completes the merge of two function declarations that are
2994 /// known to be compatible.
2995 ///
2996 /// This routine handles the merging of attributes and other
2997 /// properties of function declarations from the old declaration to
2998 /// the new declaration, once we know that New is in fact a
2999 /// redeclaration of Old.
3000 ///
3001 /// \returns false
3002 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3003                                         Scope *S, bool MergeTypeWithOld) {
3004   // Merge the attributes
3005   mergeDeclAttributes(New, Old);
3006 
3007   // Merge "pure" flag.
3008   if (Old->isPure())
3009     New->setPure();
3010 
3011   // Merge "used" flag.
3012   if (Old->getMostRecentDecl()->isUsed(false))
3013     New->setIsUsed();
3014 
3015   // Merge attributes from the parameters.  These can mismatch with K&R
3016   // declarations.
3017   if (New->getNumParams() == Old->getNumParams())
3018     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
3019       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
3020                                *this);
3021 
3022   if (getLangOpts().CPlusPlus)
3023     return MergeCXXFunctionDecl(New, Old, S);
3024 
3025   // Merge the function types so the we get the composite types for the return
3026   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3027   // was visible.
3028   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3029   if (!Merged.isNull() && MergeTypeWithOld)
3030     New->setType(Merged);
3031 
3032   return false;
3033 }
3034 
3035 
3036 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3037                                 ObjCMethodDecl *oldMethod) {
3038 
3039   // Merge the attributes, including deprecated/unavailable
3040   AvailabilityMergeKind MergeKind =
3041     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3042                                                    : AMK_Override;
3043   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3044 
3045   // Merge attributes from the parameters.
3046   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3047                                        oe = oldMethod->param_end();
3048   for (ObjCMethodDecl::param_iterator
3049          ni = newMethod->param_begin(), ne = newMethod->param_end();
3050        ni != ne && oi != oe; ++ni, ++oi)
3051     mergeParamDeclAttributes(*ni, *oi, *this);
3052 
3053   CheckObjCMethodOverride(newMethod, oldMethod);
3054 }
3055 
3056 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3057 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3058 /// emitting diagnostics as appropriate.
3059 ///
3060 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3061 /// to here in AddInitializerToDecl. We can't check them before the initializer
3062 /// is attached.
3063 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3064                              bool MergeTypeWithOld) {
3065   if (New->isInvalidDecl() || Old->isInvalidDecl())
3066     return;
3067 
3068   QualType MergedT;
3069   if (getLangOpts().CPlusPlus) {
3070     if (New->getType()->isUndeducedType()) {
3071       // We don't know what the new type is until the initializer is attached.
3072       return;
3073     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3074       // These could still be something that needs exception specs checked.
3075       return MergeVarDeclExceptionSpecs(New, Old);
3076     }
3077     // C++ [basic.link]p10:
3078     //   [...] the types specified by all declarations referring to a given
3079     //   object or function shall be identical, except that declarations for an
3080     //   array object can specify array types that differ by the presence or
3081     //   absence of a major array bound (8.3.4).
3082     else if (Old->getType()->isIncompleteArrayType() &&
3083              New->getType()->isArrayType()) {
3084       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3085       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3086       if (Context.hasSameType(OldArray->getElementType(),
3087                               NewArray->getElementType()))
3088         MergedT = New->getType();
3089     } else if (Old->getType()->isArrayType() &&
3090                New->getType()->isIncompleteArrayType()) {
3091       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3092       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3093       if (Context.hasSameType(OldArray->getElementType(),
3094                               NewArray->getElementType()))
3095         MergedT = Old->getType();
3096     } else if (New->getType()->isObjCObjectPointerType() &&
3097                Old->getType()->isObjCObjectPointerType()) {
3098       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3099                                               Old->getType());
3100     }
3101   } else {
3102     // C 6.2.7p2:
3103     //   All declarations that refer to the same object or function shall have
3104     //   compatible type.
3105     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3106   }
3107   if (MergedT.isNull()) {
3108     // It's OK if we couldn't merge types if either type is dependent, for a
3109     // block-scope variable. In other cases (static data members of class
3110     // templates, variable templates, ...), we require the types to be
3111     // equivalent.
3112     // FIXME: The C++ standard doesn't say anything about this.
3113     if ((New->getType()->isDependentType() ||
3114          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3115       // If the old type was dependent, we can't merge with it, so the new type
3116       // becomes dependent for now. We'll reproduce the original type when we
3117       // instantiate the TypeSourceInfo for the variable.
3118       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3119         New->setType(Context.DependentTy);
3120       return;
3121     }
3122 
3123     // FIXME: Even if this merging succeeds, some other non-visible declaration
3124     // of this variable might have an incompatible type. For instance:
3125     //
3126     //   extern int arr[];
3127     //   void f() { extern int arr[2]; }
3128     //   void g() { extern int arr[3]; }
3129     //
3130     // Neither C nor C++ requires a diagnostic for this, but we should still try
3131     // to diagnose it.
3132     Diag(New->getLocation(), diag::err_redefinition_different_type)
3133       << New->getDeclName() << New->getType() << Old->getType();
3134     Diag(Old->getLocation(), diag::note_previous_definition);
3135     return New->setInvalidDecl();
3136   }
3137 
3138   // Don't actually update the type on the new declaration if the old
3139   // declaration was an extern declaration in a different scope.
3140   if (MergeTypeWithOld)
3141     New->setType(MergedT);
3142 }
3143 
3144 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3145                                   LookupResult &Previous) {
3146   // C11 6.2.7p4:
3147   //   For an identifier with internal or external linkage declared
3148   //   in a scope in which a prior declaration of that identifier is
3149   //   visible, if the prior declaration specifies internal or
3150   //   external linkage, the type of the identifier at the later
3151   //   declaration becomes the composite type.
3152   //
3153   // If the variable isn't visible, we do not merge with its type.
3154   if (Previous.isShadowed())
3155     return false;
3156 
3157   if (S.getLangOpts().CPlusPlus) {
3158     // C++11 [dcl.array]p3:
3159     //   If there is a preceding declaration of the entity in the same
3160     //   scope in which the bound was specified, an omitted array bound
3161     //   is taken to be the same as in that earlier declaration.
3162     return NewVD->isPreviousDeclInSameBlockScope() ||
3163            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3164             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3165   } else {
3166     // If the old declaration was function-local, don't merge with its
3167     // type unless we're in the same function.
3168     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3169            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3170   }
3171 }
3172 
3173 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3174 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3175 /// situation, merging decls or emitting diagnostics as appropriate.
3176 ///
3177 /// Tentative definition rules (C99 6.9.2p2) are checked by
3178 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3179 /// definitions here, since the initializer hasn't been attached.
3180 ///
3181 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3182   // If the new decl is already invalid, don't do any other checking.
3183   if (New->isInvalidDecl())
3184     return;
3185 
3186   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3187 
3188   // Verify the old decl was also a variable or variable template.
3189   VarDecl *Old = nullptr;
3190   VarTemplateDecl *OldTemplate = nullptr;
3191   if (Previous.isSingleResult()) {
3192     if (NewTemplate) {
3193       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3194       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3195     } else
3196       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3197   }
3198   if (!Old) {
3199     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3200       << New->getDeclName();
3201     Diag(Previous.getRepresentativeDecl()->getLocation(),
3202          diag::note_previous_definition);
3203     return New->setInvalidDecl();
3204   }
3205 
3206   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3207     return;
3208 
3209   // Ensure the template parameters are compatible.
3210   if (NewTemplate &&
3211       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3212                                       OldTemplate->getTemplateParameters(),
3213                                       /*Complain=*/true, TPL_TemplateMatch))
3214     return;
3215 
3216   // C++ [class.mem]p1:
3217   //   A member shall not be declared twice in the member-specification [...]
3218   //
3219   // Here, we need only consider static data members.
3220   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3221     Diag(New->getLocation(), diag::err_duplicate_member)
3222       << New->getIdentifier();
3223     Diag(Old->getLocation(), diag::note_previous_declaration);
3224     New->setInvalidDecl();
3225   }
3226 
3227   mergeDeclAttributes(New, Old);
3228   // Warn if an already-declared variable is made a weak_import in a subsequent
3229   // declaration
3230   if (New->hasAttr<WeakImportAttr>() &&
3231       Old->getStorageClass() == SC_None &&
3232       !Old->hasAttr<WeakImportAttr>()) {
3233     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3234     Diag(Old->getLocation(), diag::note_previous_definition);
3235     // Remove weak_import attribute on new declaration.
3236     New->dropAttr<WeakImportAttr>();
3237   }
3238 
3239   // Merge the types.
3240   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3241 
3242   if (New->isInvalidDecl())
3243     return;
3244 
3245   diag::kind PrevDiag;
3246   SourceLocation OldLocation;
3247   std::tie(PrevDiag, OldLocation) =
3248       getNoteDiagForInvalidRedeclaration(Old, New);
3249 
3250   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3251   if (New->getStorageClass() == SC_Static &&
3252       !New->isStaticDataMember() &&
3253       Old->hasExternalFormalLinkage()) {
3254     if (getLangOpts().MicrosoftExt) {
3255       Diag(New->getLocation(), diag::ext_static_non_static)
3256           << New->getDeclName();
3257       Diag(OldLocation, PrevDiag);
3258     } else {
3259       Diag(New->getLocation(), diag::err_static_non_static)
3260           << New->getDeclName();
3261       Diag(OldLocation, PrevDiag);
3262       return New->setInvalidDecl();
3263     }
3264   }
3265   // C99 6.2.2p4:
3266   //   For an identifier declared with the storage-class specifier
3267   //   extern in a scope in which a prior declaration of that
3268   //   identifier is visible,23) if the prior declaration specifies
3269   //   internal or external linkage, the linkage of the identifier at
3270   //   the later declaration is the same as the linkage specified at
3271   //   the prior declaration. If no prior declaration is visible, or
3272   //   if the prior declaration specifies no linkage, then the
3273   //   identifier has external linkage.
3274   if (New->hasExternalStorage() && Old->hasLinkage())
3275     /* Okay */;
3276   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3277            !New->isStaticDataMember() &&
3278            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3279     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3280     Diag(OldLocation, PrevDiag);
3281     return New->setInvalidDecl();
3282   }
3283 
3284   // Check if extern is followed by non-extern and vice-versa.
3285   if (New->hasExternalStorage() &&
3286       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3287     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3288     Diag(OldLocation, PrevDiag);
3289     return New->setInvalidDecl();
3290   }
3291   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3292       !New->hasExternalStorage()) {
3293     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3294     Diag(OldLocation, PrevDiag);
3295     return New->setInvalidDecl();
3296   }
3297 
3298   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3299 
3300   // FIXME: The test for external storage here seems wrong? We still
3301   // need to check for mismatches.
3302   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3303       // Don't complain about out-of-line definitions of static members.
3304       !(Old->getLexicalDeclContext()->isRecord() &&
3305         !New->getLexicalDeclContext()->isRecord())) {
3306     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3307     Diag(OldLocation, PrevDiag);
3308     return New->setInvalidDecl();
3309   }
3310 
3311   if (New->getTLSKind() != Old->getTLSKind()) {
3312     if (!Old->getTLSKind()) {
3313       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3314       Diag(OldLocation, PrevDiag);
3315     } else if (!New->getTLSKind()) {
3316       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3317       Diag(OldLocation, PrevDiag);
3318     } else {
3319       // Do not allow redeclaration to change the variable between requiring
3320       // static and dynamic initialization.
3321       // FIXME: GCC allows this, but uses the TLS keyword on the first
3322       // declaration to determine the kind. Do we need to be compatible here?
3323       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3324         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3325       Diag(OldLocation, PrevDiag);
3326     }
3327   }
3328 
3329   // C++ doesn't have tentative definitions, so go right ahead and check here.
3330   const VarDecl *Def;
3331   if (getLangOpts().CPlusPlus &&
3332       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3333       (Def = Old->getDefinition())) {
3334     Diag(New->getLocation(), diag::err_redefinition) << New;
3335     Diag(Def->getLocation(), diag::note_previous_definition);
3336     New->setInvalidDecl();
3337     return;
3338   }
3339 
3340   if (haveIncompatibleLanguageLinkages(Old, New)) {
3341     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3342     Diag(OldLocation, PrevDiag);
3343     New->setInvalidDecl();
3344     return;
3345   }
3346 
3347   // Merge "used" flag.
3348   if (Old->getMostRecentDecl()->isUsed(false))
3349     New->setIsUsed();
3350 
3351   // Keep a chain of previous declarations.
3352   New->setPreviousDecl(Old);
3353   if (NewTemplate)
3354     NewTemplate->setPreviousDecl(OldTemplate);
3355 
3356   // Inherit access appropriately.
3357   New->setAccess(Old->getAccess());
3358   if (NewTemplate)
3359     NewTemplate->setAccess(New->getAccess());
3360 }
3361 
3362 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3363 /// no declarator (e.g. "struct foo;") is parsed.
3364 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3365                                        DeclSpec &DS) {
3366   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3367 }
3368 
3369 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3370   if (!S.Context.getLangOpts().CPlusPlus)
3371     return;
3372 
3373   if (isa<CXXRecordDecl>(Tag->getParent())) {
3374     // If this tag is the direct child of a class, number it if
3375     // it is anonymous.
3376     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3377       return;
3378     MangleNumberingContext &MCtx =
3379         S.Context.getManglingNumberContext(Tag->getParent());
3380     S.Context.setManglingNumber(
3381         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3382     return;
3383   }
3384 
3385   // If this tag isn't a direct child of a class, number it if it is local.
3386   Decl *ManglingContextDecl;
3387   if (MangleNumberingContext *MCtx =
3388           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3389                                           ManglingContextDecl)) {
3390     S.Context.setManglingNumber(
3391         Tag,
3392         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3393   }
3394 }
3395 
3396 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3397 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3398 /// parameters to cope with template friend declarations.
3399 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3400                                        DeclSpec &DS,
3401                                        MultiTemplateParamsArg TemplateParams,
3402                                        bool IsExplicitInstantiation) {
3403   Decl *TagD = nullptr;
3404   TagDecl *Tag = nullptr;
3405   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3406       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3407       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3408       DS.getTypeSpecType() == DeclSpec::TST_union ||
3409       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3410     TagD = DS.getRepAsDecl();
3411 
3412     if (!TagD) // We probably had an error
3413       return nullptr;
3414 
3415     // Note that the above type specs guarantee that the
3416     // type rep is a Decl, whereas in many of the others
3417     // it's a Type.
3418     if (isa<TagDecl>(TagD))
3419       Tag = cast<TagDecl>(TagD);
3420     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3421       Tag = CTD->getTemplatedDecl();
3422   }
3423 
3424   if (Tag) {
3425     HandleTagNumbering(*this, Tag, S);
3426     Tag->setFreeStanding();
3427     if (Tag->isInvalidDecl())
3428       return Tag;
3429   }
3430 
3431   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3432     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3433     // or incomplete types shall not be restrict-qualified."
3434     if (TypeQuals & DeclSpec::TQ_restrict)
3435       Diag(DS.getRestrictSpecLoc(),
3436            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3437            << DS.getSourceRange();
3438   }
3439 
3440   if (DS.isConstexprSpecified()) {
3441     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3442     // and definitions of functions and variables.
3443     if (Tag)
3444       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3445         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3446             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3447             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3448             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3449     else
3450       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3451     // Don't emit warnings after this error.
3452     return TagD;
3453   }
3454 
3455   DiagnoseFunctionSpecifiers(DS);
3456 
3457   if (DS.isFriendSpecified()) {
3458     // If we're dealing with a decl but not a TagDecl, assume that
3459     // whatever routines created it handled the friendship aspect.
3460     if (TagD && !Tag)
3461       return nullptr;
3462     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3463   }
3464 
3465   CXXScopeSpec &SS = DS.getTypeSpecScope();
3466   bool IsExplicitSpecialization =
3467     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3468   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3469       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3470     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3471     // nested-name-specifier unless it is an explicit instantiation
3472     // or an explicit specialization.
3473     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3474     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3475       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3476           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3477           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3478           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3479       << SS.getRange();
3480     return nullptr;
3481   }
3482 
3483   // Track whether this decl-specifier declares anything.
3484   bool DeclaresAnything = true;
3485 
3486   // Handle anonymous struct definitions.
3487   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3488     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3489         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3490       if (getLangOpts().CPlusPlus ||
3491           Record->getDeclContext()->isRecord())
3492         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3493 
3494       DeclaresAnything = false;
3495     }
3496   }
3497 
3498   // C11 6.7.2.1p2:
3499   //   A struct-declaration that does not declare an anonymous structure or
3500   //   anonymous union shall contain a struct-declarator-list.
3501   //
3502   // This rule also existed in C89 and C99; the grammar for struct-declaration
3503   // did not permit a struct-declaration without a struct-declarator-list.
3504   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3505       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3506     // Check for Microsoft C extension: anonymous struct/union member.
3507     // Handle 2 kinds of anonymous struct/union:
3508     //   struct STRUCT;
3509     //   union UNION;
3510     // and
3511     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3512     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3513     if ((Tag && Tag->getDeclName()) ||
3514         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3515       RecordDecl *Record = nullptr;
3516       if (Tag)
3517         Record = dyn_cast<RecordDecl>(Tag);
3518       else if (const RecordType *RT =
3519                    DS.getRepAsType().get()->getAsStructureType())
3520         Record = RT->getDecl();
3521       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3522         Record = UT->getDecl();
3523 
3524       if (Record && getLangOpts().MicrosoftExt) {
3525         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3526           << Record->isUnion() << DS.getSourceRange();
3527         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3528       }
3529 
3530       DeclaresAnything = false;
3531     }
3532   }
3533 
3534   // Skip all the checks below if we have a type error.
3535   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3536       (TagD && TagD->isInvalidDecl()))
3537     return TagD;
3538 
3539   if (getLangOpts().CPlusPlus &&
3540       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3541     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3542       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3543           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3544         DeclaresAnything = false;
3545 
3546   if (!DS.isMissingDeclaratorOk()) {
3547     // Customize diagnostic for a typedef missing a name.
3548     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3549       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3550         << DS.getSourceRange();
3551     else
3552       DeclaresAnything = false;
3553   }
3554 
3555   if (DS.isModulePrivateSpecified() &&
3556       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3557     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3558       << Tag->getTagKind()
3559       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3560 
3561   ActOnDocumentableDecl(TagD);
3562 
3563   // C 6.7/2:
3564   //   A declaration [...] shall declare at least a declarator [...], a tag,
3565   //   or the members of an enumeration.
3566   // C++ [dcl.dcl]p3:
3567   //   [If there are no declarators], and except for the declaration of an
3568   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3569   //   names into the program, or shall redeclare a name introduced by a
3570   //   previous declaration.
3571   if (!DeclaresAnything) {
3572     // In C, we allow this as a (popular) extension / bug. Don't bother
3573     // producing further diagnostics for redundant qualifiers after this.
3574     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3575     return TagD;
3576   }
3577 
3578   // C++ [dcl.stc]p1:
3579   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3580   //   init-declarator-list of the declaration shall not be empty.
3581   // C++ [dcl.fct.spec]p1:
3582   //   If a cv-qualifier appears in a decl-specifier-seq, the
3583   //   init-declarator-list of the declaration shall not be empty.
3584   //
3585   // Spurious qualifiers here appear to be valid in C.
3586   unsigned DiagID = diag::warn_standalone_specifier;
3587   if (getLangOpts().CPlusPlus)
3588     DiagID = diag::ext_standalone_specifier;
3589 
3590   // Note that a linkage-specification sets a storage class, but
3591   // 'extern "C" struct foo;' is actually valid and not theoretically
3592   // useless.
3593   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3594     if (SCS == DeclSpec::SCS_mutable)
3595       // Since mutable is not a viable storage class specifier in C, there is
3596       // no reason to treat it as an extension. Instead, diagnose as an error.
3597       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3598     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3599       Diag(DS.getStorageClassSpecLoc(), DiagID)
3600         << DeclSpec::getSpecifierName(SCS);
3601   }
3602 
3603   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3604     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3605       << DeclSpec::getSpecifierName(TSCS);
3606   if (DS.getTypeQualifiers()) {
3607     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3608       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3609     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3610       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3611     // Restrict is covered above.
3612     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3613       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3614   }
3615 
3616   // Warn about ignored type attributes, for example:
3617   // __attribute__((aligned)) struct A;
3618   // Attributes should be placed after tag to apply to type declaration.
3619   if (!DS.getAttributes().empty()) {
3620     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3621     if (TypeSpecType == DeclSpec::TST_class ||
3622         TypeSpecType == DeclSpec::TST_struct ||
3623         TypeSpecType == DeclSpec::TST_interface ||
3624         TypeSpecType == DeclSpec::TST_union ||
3625         TypeSpecType == DeclSpec::TST_enum) {
3626       AttributeList* attrs = DS.getAttributes().getList();
3627       while (attrs) {
3628         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3629         << attrs->getName()
3630         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3631             TypeSpecType == DeclSpec::TST_struct ? 1 :
3632             TypeSpecType == DeclSpec::TST_union ? 2 :
3633             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3634         attrs = attrs->getNext();
3635       }
3636     }
3637   }
3638 
3639   return TagD;
3640 }
3641 
3642 /// We are trying to inject an anonymous member into the given scope;
3643 /// check if there's an existing declaration that can't be overloaded.
3644 ///
3645 /// \return true if this is a forbidden redeclaration
3646 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3647                                          Scope *S,
3648                                          DeclContext *Owner,
3649                                          DeclarationName Name,
3650                                          SourceLocation NameLoc,
3651                                          unsigned diagnostic) {
3652   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3653                  Sema::ForRedeclaration);
3654   if (!SemaRef.LookupName(R, S)) return false;
3655 
3656   if (R.getAsSingle<TagDecl>())
3657     return false;
3658 
3659   // Pick a representative declaration.
3660   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3661   assert(PrevDecl && "Expected a non-null Decl");
3662 
3663   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3664     return false;
3665 
3666   SemaRef.Diag(NameLoc, diagnostic) << Name;
3667   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3668 
3669   return true;
3670 }
3671 
3672 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3673 /// anonymous struct or union AnonRecord into the owning context Owner
3674 /// and scope S. This routine will be invoked just after we realize
3675 /// that an unnamed union or struct is actually an anonymous union or
3676 /// struct, e.g.,
3677 ///
3678 /// @code
3679 /// union {
3680 ///   int i;
3681 ///   float f;
3682 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3683 ///    // f into the surrounding scope.x
3684 /// @endcode
3685 ///
3686 /// This routine is recursive, injecting the names of nested anonymous
3687 /// structs/unions into the owning context and scope as well.
3688 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3689                                          DeclContext *Owner,
3690                                          RecordDecl *AnonRecord,
3691                                          AccessSpecifier AS,
3692                                          SmallVectorImpl<NamedDecl *> &Chaining,
3693                                          bool MSAnonStruct) {
3694   unsigned diagKind
3695     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3696                             : diag::err_anonymous_struct_member_redecl;
3697 
3698   bool Invalid = false;
3699 
3700   // Look every FieldDecl and IndirectFieldDecl with a name.
3701   for (auto *D : AnonRecord->decls()) {
3702     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3703         cast<NamedDecl>(D)->getDeclName()) {
3704       ValueDecl *VD = cast<ValueDecl>(D);
3705       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3706                                        VD->getLocation(), diagKind)) {
3707         // C++ [class.union]p2:
3708         //   The names of the members of an anonymous union shall be
3709         //   distinct from the names of any other entity in the
3710         //   scope in which the anonymous union is declared.
3711         Invalid = true;
3712       } else {
3713         // C++ [class.union]p2:
3714         //   For the purpose of name lookup, after the anonymous union
3715         //   definition, the members of the anonymous union are
3716         //   considered to have been defined in the scope in which the
3717         //   anonymous union is declared.
3718         unsigned OldChainingSize = Chaining.size();
3719         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3720           for (auto *PI : IF->chain())
3721             Chaining.push_back(PI);
3722         else
3723           Chaining.push_back(VD);
3724 
3725         assert(Chaining.size() >= 2);
3726         NamedDecl **NamedChain =
3727           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3728         for (unsigned i = 0; i < Chaining.size(); i++)
3729           NamedChain[i] = Chaining[i];
3730 
3731         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3732             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3733             VD->getType(), NamedChain, Chaining.size());
3734 
3735         for (const auto *Attr : VD->attrs())
3736           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3737 
3738         IndirectField->setAccess(AS);
3739         IndirectField->setImplicit();
3740         SemaRef.PushOnScopeChains(IndirectField, S);
3741 
3742         // That includes picking up the appropriate access specifier.
3743         if (AS != AS_none) IndirectField->setAccess(AS);
3744 
3745         Chaining.resize(OldChainingSize);
3746       }
3747     }
3748   }
3749 
3750   return Invalid;
3751 }
3752 
3753 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3754 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3755 /// illegal input values are mapped to SC_None.
3756 static StorageClass
3757 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3758   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3759   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3760          "Parser allowed 'typedef' as storage class VarDecl.");
3761   switch (StorageClassSpec) {
3762   case DeclSpec::SCS_unspecified:    return SC_None;
3763   case DeclSpec::SCS_extern:
3764     if (DS.isExternInLinkageSpec())
3765       return SC_None;
3766     return SC_Extern;
3767   case DeclSpec::SCS_static:         return SC_Static;
3768   case DeclSpec::SCS_auto:           return SC_Auto;
3769   case DeclSpec::SCS_register:       return SC_Register;
3770   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3771     // Illegal SCSs map to None: error reporting is up to the caller.
3772   case DeclSpec::SCS_mutable:        // Fall through.
3773   case DeclSpec::SCS_typedef:        return SC_None;
3774   }
3775   llvm_unreachable("unknown storage class specifier");
3776 }
3777 
3778 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3779   assert(Record->hasInClassInitializer());
3780 
3781   for (const auto *I : Record->decls()) {
3782     const auto *FD = dyn_cast<FieldDecl>(I);
3783     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3784       FD = IFD->getAnonField();
3785     if (FD && FD->hasInClassInitializer())
3786       return FD->getLocation();
3787   }
3788 
3789   llvm_unreachable("couldn't find in-class initializer");
3790 }
3791 
3792 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3793                                       SourceLocation DefaultInitLoc) {
3794   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3795     return;
3796 
3797   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3798   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3799 }
3800 
3801 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3802                                       CXXRecordDecl *AnonUnion) {
3803   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3804     return;
3805 
3806   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3807 }
3808 
3809 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3810 /// anonymous structure or union. Anonymous unions are a C++ feature
3811 /// (C++ [class.union]) and a C11 feature; anonymous structures
3812 /// are a C11 feature and GNU C++ extension.
3813 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3814                                         AccessSpecifier AS,
3815                                         RecordDecl *Record,
3816                                         const PrintingPolicy &Policy) {
3817   DeclContext *Owner = Record->getDeclContext();
3818 
3819   // Diagnose whether this anonymous struct/union is an extension.
3820   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3821     Diag(Record->getLocation(), diag::ext_anonymous_union);
3822   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3823     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3824   else if (!Record->isUnion() && !getLangOpts().C11)
3825     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3826 
3827   // C and C++ require different kinds of checks for anonymous
3828   // structs/unions.
3829   bool Invalid = false;
3830   if (getLangOpts().CPlusPlus) {
3831     const char *PrevSpec = nullptr;
3832     unsigned DiagID;
3833     if (Record->isUnion()) {
3834       // C++ [class.union]p6:
3835       //   Anonymous unions declared in a named namespace or in the
3836       //   global namespace shall be declared static.
3837       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3838           (isa<TranslationUnitDecl>(Owner) ||
3839            (isa<NamespaceDecl>(Owner) &&
3840             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3841         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3842           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3843 
3844         // Recover by adding 'static'.
3845         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3846                                PrevSpec, DiagID, Policy);
3847       }
3848       // C++ [class.union]p6:
3849       //   A storage class is not allowed in a declaration of an
3850       //   anonymous union in a class scope.
3851       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3852                isa<RecordDecl>(Owner)) {
3853         Diag(DS.getStorageClassSpecLoc(),
3854              diag::err_anonymous_union_with_storage_spec)
3855           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3856 
3857         // Recover by removing the storage specifier.
3858         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3859                                SourceLocation(),
3860                                PrevSpec, DiagID, Context.getPrintingPolicy());
3861       }
3862     }
3863 
3864     // Ignore const/volatile/restrict qualifiers.
3865     if (DS.getTypeQualifiers()) {
3866       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3867         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3868           << Record->isUnion() << "const"
3869           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3870       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3871         Diag(DS.getVolatileSpecLoc(),
3872              diag::ext_anonymous_struct_union_qualified)
3873           << Record->isUnion() << "volatile"
3874           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3875       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3876         Diag(DS.getRestrictSpecLoc(),
3877              diag::ext_anonymous_struct_union_qualified)
3878           << Record->isUnion() << "restrict"
3879           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3880       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3881         Diag(DS.getAtomicSpecLoc(),
3882              diag::ext_anonymous_struct_union_qualified)
3883           << Record->isUnion() << "_Atomic"
3884           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3885 
3886       DS.ClearTypeQualifiers();
3887     }
3888 
3889     // C++ [class.union]p2:
3890     //   The member-specification of an anonymous union shall only
3891     //   define non-static data members. [Note: nested types and
3892     //   functions cannot be declared within an anonymous union. ]
3893     for (auto *Mem : Record->decls()) {
3894       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3895         // C++ [class.union]p3:
3896         //   An anonymous union shall not have private or protected
3897         //   members (clause 11).
3898         assert(FD->getAccess() != AS_none);
3899         if (FD->getAccess() != AS_public) {
3900           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3901             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3902           Invalid = true;
3903         }
3904 
3905         // C++ [class.union]p1
3906         //   An object of a class with a non-trivial constructor, a non-trivial
3907         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3908         //   assignment operator cannot be a member of a union, nor can an
3909         //   array of such objects.
3910         if (CheckNontrivialField(FD))
3911           Invalid = true;
3912       } else if (Mem->isImplicit()) {
3913         // Any implicit members are fine.
3914       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3915         // This is a type that showed up in an
3916         // elaborated-type-specifier inside the anonymous struct or
3917         // union, but which actually declares a type outside of the
3918         // anonymous struct or union. It's okay.
3919       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3920         if (!MemRecord->isAnonymousStructOrUnion() &&
3921             MemRecord->getDeclName()) {
3922           // Visual C++ allows type definition in anonymous struct or union.
3923           if (getLangOpts().MicrosoftExt)
3924             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3925               << (int)Record->isUnion();
3926           else {
3927             // This is a nested type declaration.
3928             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3929               << (int)Record->isUnion();
3930             Invalid = true;
3931           }
3932         } else {
3933           // This is an anonymous type definition within another anonymous type.
3934           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3935           // not part of standard C++.
3936           Diag(MemRecord->getLocation(),
3937                diag::ext_anonymous_record_with_anonymous_type)
3938             << (int)Record->isUnion();
3939         }
3940       } else if (isa<AccessSpecDecl>(Mem)) {
3941         // Any access specifier is fine.
3942       } else if (isa<StaticAssertDecl>(Mem)) {
3943         // In C++1z, static_assert declarations are also fine.
3944       } else {
3945         // We have something that isn't a non-static data
3946         // member. Complain about it.
3947         unsigned DK = diag::err_anonymous_record_bad_member;
3948         if (isa<TypeDecl>(Mem))
3949           DK = diag::err_anonymous_record_with_type;
3950         else if (isa<FunctionDecl>(Mem))
3951           DK = diag::err_anonymous_record_with_function;
3952         else if (isa<VarDecl>(Mem))
3953           DK = diag::err_anonymous_record_with_static;
3954 
3955         // Visual C++ allows type definition in anonymous struct or union.
3956         if (getLangOpts().MicrosoftExt &&
3957             DK == diag::err_anonymous_record_with_type)
3958           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3959             << (int)Record->isUnion();
3960         else {
3961           Diag(Mem->getLocation(), DK)
3962               << (int)Record->isUnion();
3963           Invalid = true;
3964         }
3965       }
3966     }
3967 
3968     // C++11 [class.union]p8 (DR1460):
3969     //   At most one variant member of a union may have a
3970     //   brace-or-equal-initializer.
3971     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3972         Owner->isRecord())
3973       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3974                                 cast<CXXRecordDecl>(Record));
3975   }
3976 
3977   if (!Record->isUnion() && !Owner->isRecord()) {
3978     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3979       << (int)getLangOpts().CPlusPlus;
3980     Invalid = true;
3981   }
3982 
3983   // Mock up a declarator.
3984   Declarator Dc(DS, Declarator::MemberContext);
3985   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3986   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3987 
3988   // Create a declaration for this anonymous struct/union.
3989   NamedDecl *Anon = nullptr;
3990   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3991     Anon = FieldDecl::Create(Context, OwningClass,
3992                              DS.getLocStart(),
3993                              Record->getLocation(),
3994                              /*IdentifierInfo=*/nullptr,
3995                              Context.getTypeDeclType(Record),
3996                              TInfo,
3997                              /*BitWidth=*/nullptr, /*Mutable=*/false,
3998                              /*InitStyle=*/ICIS_NoInit);
3999     Anon->setAccess(AS);
4000     if (getLangOpts().CPlusPlus)
4001       FieldCollector->Add(cast<FieldDecl>(Anon));
4002   } else {
4003     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4004     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4005     if (SCSpec == DeclSpec::SCS_mutable) {
4006       // mutable can only appear on non-static class members, so it's always
4007       // an error here
4008       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4009       Invalid = true;
4010       SC = SC_None;
4011     }
4012 
4013     Anon = VarDecl::Create(Context, Owner,
4014                            DS.getLocStart(),
4015                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4016                            Context.getTypeDeclType(Record),
4017                            TInfo, SC);
4018 
4019     // Default-initialize the implicit variable. This initialization will be
4020     // trivial in almost all cases, except if a union member has an in-class
4021     // initializer:
4022     //   union { int n = 0; };
4023     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4024   }
4025   Anon->setImplicit();
4026 
4027   // Mark this as an anonymous struct/union type.
4028   Record->setAnonymousStructOrUnion(true);
4029 
4030   // Add the anonymous struct/union object to the current
4031   // context. We'll be referencing this object when we refer to one of
4032   // its members.
4033   Owner->addDecl(Anon);
4034 
4035   // Inject the members of the anonymous struct/union into the owning
4036   // context and into the identifier resolver chain for name lookup
4037   // purposes.
4038   SmallVector<NamedDecl*, 2> Chain;
4039   Chain.push_back(Anon);
4040 
4041   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4042                                           Chain, false))
4043     Invalid = true;
4044 
4045   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4046     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4047       Decl *ManglingContextDecl;
4048       if (MangleNumberingContext *MCtx =
4049               getCurrentMangleNumberContext(NewVD->getDeclContext(),
4050                                             ManglingContextDecl)) {
4051         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
4052         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4053       }
4054     }
4055   }
4056 
4057   if (Invalid)
4058     Anon->setInvalidDecl();
4059 
4060   return Anon;
4061 }
4062 
4063 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4064 /// Microsoft C anonymous structure.
4065 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4066 /// Example:
4067 ///
4068 /// struct A { int a; };
4069 /// struct B { struct A; int b; };
4070 ///
4071 /// void foo() {
4072 ///   B var;
4073 ///   var.a = 3;
4074 /// }
4075 ///
4076 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4077                                            RecordDecl *Record) {
4078   assert(Record && "expected a record!");
4079 
4080   // Mock up a declarator.
4081   Declarator Dc(DS, Declarator::TypeNameContext);
4082   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4083   assert(TInfo && "couldn't build declarator info for anonymous struct");
4084 
4085   auto *ParentDecl = cast<RecordDecl>(CurContext);
4086   QualType RecTy = Context.getTypeDeclType(Record);
4087 
4088   // Create a declaration for this anonymous struct.
4089   NamedDecl *Anon = FieldDecl::Create(Context,
4090                              ParentDecl,
4091                              DS.getLocStart(),
4092                              DS.getLocStart(),
4093                              /*IdentifierInfo=*/nullptr,
4094                              RecTy,
4095                              TInfo,
4096                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4097                              /*InitStyle=*/ICIS_NoInit);
4098   Anon->setImplicit();
4099 
4100   // Add the anonymous struct object to the current context.
4101   CurContext->addDecl(Anon);
4102 
4103   // Inject the members of the anonymous struct into the current
4104   // context and into the identifier resolver chain for name lookup
4105   // purposes.
4106   SmallVector<NamedDecl*, 2> Chain;
4107   Chain.push_back(Anon);
4108 
4109   RecordDecl *RecordDef = Record->getDefinition();
4110   if (RequireCompleteType(Anon->getLocation(), RecTy,
4111                           diag::err_field_incomplete) ||
4112       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4113                                           AS_none, Chain, true)) {
4114     Anon->setInvalidDecl();
4115     ParentDecl->setInvalidDecl();
4116   }
4117 
4118   return Anon;
4119 }
4120 
4121 /// GetNameForDeclarator - Determine the full declaration name for the
4122 /// given Declarator.
4123 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4124   return GetNameFromUnqualifiedId(D.getName());
4125 }
4126 
4127 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4128 DeclarationNameInfo
4129 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4130   DeclarationNameInfo NameInfo;
4131   NameInfo.setLoc(Name.StartLocation);
4132 
4133   switch (Name.getKind()) {
4134 
4135   case UnqualifiedId::IK_ImplicitSelfParam:
4136   case UnqualifiedId::IK_Identifier:
4137     NameInfo.setName(Name.Identifier);
4138     NameInfo.setLoc(Name.StartLocation);
4139     return NameInfo;
4140 
4141   case UnqualifiedId::IK_OperatorFunctionId:
4142     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4143                                            Name.OperatorFunctionId.Operator));
4144     NameInfo.setLoc(Name.StartLocation);
4145     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4146       = Name.OperatorFunctionId.SymbolLocations[0];
4147     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4148       = Name.EndLocation.getRawEncoding();
4149     return NameInfo;
4150 
4151   case UnqualifiedId::IK_LiteralOperatorId:
4152     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4153                                                            Name.Identifier));
4154     NameInfo.setLoc(Name.StartLocation);
4155     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4156     return NameInfo;
4157 
4158   case UnqualifiedId::IK_ConversionFunctionId: {
4159     TypeSourceInfo *TInfo;
4160     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4161     if (Ty.isNull())
4162       return DeclarationNameInfo();
4163     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4164                                                Context.getCanonicalType(Ty)));
4165     NameInfo.setLoc(Name.StartLocation);
4166     NameInfo.setNamedTypeInfo(TInfo);
4167     return NameInfo;
4168   }
4169 
4170   case UnqualifiedId::IK_ConstructorName: {
4171     TypeSourceInfo *TInfo;
4172     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4173     if (Ty.isNull())
4174       return DeclarationNameInfo();
4175     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4176                                               Context.getCanonicalType(Ty)));
4177     NameInfo.setLoc(Name.StartLocation);
4178     NameInfo.setNamedTypeInfo(TInfo);
4179     return NameInfo;
4180   }
4181 
4182   case UnqualifiedId::IK_ConstructorTemplateId: {
4183     // In well-formed code, we can only have a constructor
4184     // template-id that refers to the current context, so go there
4185     // to find the actual type being constructed.
4186     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4187     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4188       return DeclarationNameInfo();
4189 
4190     // Determine the type of the class being constructed.
4191     QualType CurClassType = Context.getTypeDeclType(CurClass);
4192 
4193     // FIXME: Check two things: that the template-id names the same type as
4194     // CurClassType, and that the template-id does not occur when the name
4195     // was qualified.
4196 
4197     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4198                                     Context.getCanonicalType(CurClassType)));
4199     NameInfo.setLoc(Name.StartLocation);
4200     // FIXME: should we retrieve TypeSourceInfo?
4201     NameInfo.setNamedTypeInfo(nullptr);
4202     return NameInfo;
4203   }
4204 
4205   case UnqualifiedId::IK_DestructorName: {
4206     TypeSourceInfo *TInfo;
4207     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4208     if (Ty.isNull())
4209       return DeclarationNameInfo();
4210     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4211                                               Context.getCanonicalType(Ty)));
4212     NameInfo.setLoc(Name.StartLocation);
4213     NameInfo.setNamedTypeInfo(TInfo);
4214     return NameInfo;
4215   }
4216 
4217   case UnqualifiedId::IK_TemplateId: {
4218     TemplateName TName = Name.TemplateId->Template.get();
4219     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4220     return Context.getNameForTemplate(TName, TNameLoc);
4221   }
4222 
4223   } // switch (Name.getKind())
4224 
4225   llvm_unreachable("Unknown name kind");
4226 }
4227 
4228 static QualType getCoreType(QualType Ty) {
4229   do {
4230     if (Ty->isPointerType() || Ty->isReferenceType())
4231       Ty = Ty->getPointeeType();
4232     else if (Ty->isArrayType())
4233       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4234     else
4235       return Ty.withoutLocalFastQualifiers();
4236   } while (true);
4237 }
4238 
4239 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4240 /// and Definition have "nearly" matching parameters. This heuristic is
4241 /// used to improve diagnostics in the case where an out-of-line function
4242 /// definition doesn't match any declaration within the class or namespace.
4243 /// Also sets Params to the list of indices to the parameters that differ
4244 /// between the declaration and the definition. If hasSimilarParameters
4245 /// returns true and Params is empty, then all of the parameters match.
4246 static bool hasSimilarParameters(ASTContext &Context,
4247                                      FunctionDecl *Declaration,
4248                                      FunctionDecl *Definition,
4249                                      SmallVectorImpl<unsigned> &Params) {
4250   Params.clear();
4251   if (Declaration->param_size() != Definition->param_size())
4252     return false;
4253   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4254     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4255     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4256 
4257     // The parameter types are identical
4258     if (Context.hasSameType(DefParamTy, DeclParamTy))
4259       continue;
4260 
4261     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4262     QualType DefParamBaseTy = getCoreType(DefParamTy);
4263     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4264     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4265 
4266     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4267         (DeclTyName && DeclTyName == DefTyName))
4268       Params.push_back(Idx);
4269     else  // The two parameters aren't even close
4270       return false;
4271   }
4272 
4273   return true;
4274 }
4275 
4276 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4277 /// declarator needs to be rebuilt in the current instantiation.
4278 /// Any bits of declarator which appear before the name are valid for
4279 /// consideration here.  That's specifically the type in the decl spec
4280 /// and the base type in any member-pointer chunks.
4281 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4282                                                     DeclarationName Name) {
4283   // The types we specifically need to rebuild are:
4284   //   - typenames, typeofs, and decltypes
4285   //   - types which will become injected class names
4286   // Of course, we also need to rebuild any type referencing such a
4287   // type.  It's safest to just say "dependent", but we call out a
4288   // few cases here.
4289 
4290   DeclSpec &DS = D.getMutableDeclSpec();
4291   switch (DS.getTypeSpecType()) {
4292   case DeclSpec::TST_typename:
4293   case DeclSpec::TST_typeofType:
4294   case DeclSpec::TST_underlyingType:
4295   case DeclSpec::TST_atomic: {
4296     // Grab the type from the parser.
4297     TypeSourceInfo *TSI = nullptr;
4298     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4299     if (T.isNull() || !T->isDependentType()) break;
4300 
4301     // Make sure there's a type source info.  This isn't really much
4302     // of a waste; most dependent types should have type source info
4303     // attached already.
4304     if (!TSI)
4305       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4306 
4307     // Rebuild the type in the current instantiation.
4308     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4309     if (!TSI) return true;
4310 
4311     // Store the new type back in the decl spec.
4312     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4313     DS.UpdateTypeRep(LocType);
4314     break;
4315   }
4316 
4317   case DeclSpec::TST_decltype:
4318   case DeclSpec::TST_typeofExpr: {
4319     Expr *E = DS.getRepAsExpr();
4320     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4321     if (Result.isInvalid()) return true;
4322     DS.UpdateExprRep(Result.get());
4323     break;
4324   }
4325 
4326   default:
4327     // Nothing to do for these decl specs.
4328     break;
4329   }
4330 
4331   // It doesn't matter what order we do this in.
4332   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4333     DeclaratorChunk &Chunk = D.getTypeObject(I);
4334 
4335     // The only type information in the declarator which can come
4336     // before the declaration name is the base type of a member
4337     // pointer.
4338     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4339       continue;
4340 
4341     // Rebuild the scope specifier in-place.
4342     CXXScopeSpec &SS = Chunk.Mem.Scope();
4343     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4344       return true;
4345   }
4346 
4347   return false;
4348 }
4349 
4350 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4351   D.setFunctionDefinitionKind(FDK_Declaration);
4352   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4353 
4354   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4355       Dcl && Dcl->getDeclContext()->isFileContext())
4356     Dcl->setTopLevelDeclInObjCContainer();
4357 
4358   return Dcl;
4359 }
4360 
4361 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4362 ///   If T is the name of a class, then each of the following shall have a
4363 ///   name different from T:
4364 ///     - every static data member of class T;
4365 ///     - every member function of class T
4366 ///     - every member of class T that is itself a type;
4367 /// \returns true if the declaration name violates these rules.
4368 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4369                                    DeclarationNameInfo NameInfo) {
4370   DeclarationName Name = NameInfo.getName();
4371 
4372   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4373     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4374       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4375       return true;
4376     }
4377 
4378   return false;
4379 }
4380 
4381 /// \brief Diagnose a declaration whose declarator-id has the given
4382 /// nested-name-specifier.
4383 ///
4384 /// \param SS The nested-name-specifier of the declarator-id.
4385 ///
4386 /// \param DC The declaration context to which the nested-name-specifier
4387 /// resolves.
4388 ///
4389 /// \param Name The name of the entity being declared.
4390 ///
4391 /// \param Loc The location of the name of the entity being declared.
4392 ///
4393 /// \returns true if we cannot safely recover from this error, false otherwise.
4394 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4395                                         DeclarationName Name,
4396                                         SourceLocation Loc) {
4397   DeclContext *Cur = CurContext;
4398   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4399     Cur = Cur->getParent();
4400 
4401   // If the user provided a superfluous scope specifier that refers back to the
4402   // class in which the entity is already declared, diagnose and ignore it.
4403   //
4404   // class X {
4405   //   void X::f();
4406   // };
4407   //
4408   // Note, it was once ill-formed to give redundant qualification in all
4409   // contexts, but that rule was removed by DR482.
4410   if (Cur->Equals(DC)) {
4411     if (Cur->isRecord()) {
4412       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4413                                       : diag::err_member_extra_qualification)
4414         << Name << FixItHint::CreateRemoval(SS.getRange());
4415       SS.clear();
4416     } else {
4417       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4418     }
4419     return false;
4420   }
4421 
4422   // Check whether the qualifying scope encloses the scope of the original
4423   // declaration.
4424   if (!Cur->Encloses(DC)) {
4425     if (Cur->isRecord())
4426       Diag(Loc, diag::err_member_qualification)
4427         << Name << SS.getRange();
4428     else if (isa<TranslationUnitDecl>(DC))
4429       Diag(Loc, diag::err_invalid_declarator_global_scope)
4430         << Name << SS.getRange();
4431     else if (isa<FunctionDecl>(Cur))
4432       Diag(Loc, diag::err_invalid_declarator_in_function)
4433         << Name << SS.getRange();
4434     else if (isa<BlockDecl>(Cur))
4435       Diag(Loc, diag::err_invalid_declarator_in_block)
4436         << Name << SS.getRange();
4437     else
4438       Diag(Loc, diag::err_invalid_declarator_scope)
4439       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4440 
4441     return true;
4442   }
4443 
4444   if (Cur->isRecord()) {
4445     // Cannot qualify members within a class.
4446     Diag(Loc, diag::err_member_qualification)
4447       << Name << SS.getRange();
4448     SS.clear();
4449 
4450     // C++ constructors and destructors with incorrect scopes can break
4451     // our AST invariants by having the wrong underlying types. If
4452     // that's the case, then drop this declaration entirely.
4453     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4454          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4455         !Context.hasSameType(Name.getCXXNameType(),
4456                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4457       return true;
4458 
4459     return false;
4460   }
4461 
4462   // C++11 [dcl.meaning]p1:
4463   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4464   //   not begin with a decltype-specifer"
4465   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4466   while (SpecLoc.getPrefix())
4467     SpecLoc = SpecLoc.getPrefix();
4468   if (dyn_cast_or_null<DecltypeType>(
4469         SpecLoc.getNestedNameSpecifier()->getAsType()))
4470     Diag(Loc, diag::err_decltype_in_declarator)
4471       << SpecLoc.getTypeLoc().getSourceRange();
4472 
4473   return false;
4474 }
4475 
4476 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4477                                   MultiTemplateParamsArg TemplateParamLists) {
4478   // TODO: consider using NameInfo for diagnostic.
4479   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4480   DeclarationName Name = NameInfo.getName();
4481 
4482   // All of these full declarators require an identifier.  If it doesn't have
4483   // one, the ParsedFreeStandingDeclSpec action should be used.
4484   if (!Name) {
4485     if (!D.isInvalidType())  // Reject this if we think it is valid.
4486       Diag(D.getDeclSpec().getLocStart(),
4487            diag::err_declarator_need_ident)
4488         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4489     return nullptr;
4490   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4491     return nullptr;
4492 
4493   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4494   // we find one that is.
4495   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4496          (S->getFlags() & Scope::TemplateParamScope) != 0)
4497     S = S->getParent();
4498 
4499   DeclContext *DC = CurContext;
4500   if (D.getCXXScopeSpec().isInvalid())
4501     D.setInvalidType();
4502   else if (D.getCXXScopeSpec().isSet()) {
4503     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4504                                         UPPC_DeclarationQualifier))
4505       return nullptr;
4506 
4507     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4508     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4509     if (!DC || isa<EnumDecl>(DC)) {
4510       // If we could not compute the declaration context, it's because the
4511       // declaration context is dependent but does not refer to a class,
4512       // class template, or class template partial specialization. Complain
4513       // and return early, to avoid the coming semantic disaster.
4514       Diag(D.getIdentifierLoc(),
4515            diag::err_template_qualified_declarator_no_match)
4516         << D.getCXXScopeSpec().getScopeRep()
4517         << D.getCXXScopeSpec().getRange();
4518       return nullptr;
4519     }
4520     bool IsDependentContext = DC->isDependentContext();
4521 
4522     if (!IsDependentContext &&
4523         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4524       return nullptr;
4525 
4526     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4527       Diag(D.getIdentifierLoc(),
4528            diag::err_member_def_undefined_record)
4529         << Name << DC << D.getCXXScopeSpec().getRange();
4530       D.setInvalidType();
4531     } else if (!D.getDeclSpec().isFriendSpecified()) {
4532       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4533                                       Name, D.getIdentifierLoc())) {
4534         if (DC->isRecord())
4535           return nullptr;
4536 
4537         D.setInvalidType();
4538       }
4539     }
4540 
4541     // Check whether we need to rebuild the type of the given
4542     // declaration in the current instantiation.
4543     if (EnteringContext && IsDependentContext &&
4544         TemplateParamLists.size() != 0) {
4545       ContextRAII SavedContext(*this, DC);
4546       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4547         D.setInvalidType();
4548     }
4549   }
4550 
4551   if (DiagnoseClassNameShadow(DC, NameInfo))
4552     // If this is a typedef, we'll end up spewing multiple diagnostics.
4553     // Just return early; it's safer.
4554     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4555       return nullptr;
4556 
4557   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4558   QualType R = TInfo->getType();
4559 
4560   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4561                                       UPPC_DeclarationType))
4562     D.setInvalidType();
4563 
4564   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4565                         ForRedeclaration);
4566 
4567   // See if this is a redefinition of a variable in the same scope.
4568   if (!D.getCXXScopeSpec().isSet()) {
4569     bool IsLinkageLookup = false;
4570     bool CreateBuiltins = false;
4571 
4572     // If the declaration we're planning to build will be a function
4573     // or object with linkage, then look for another declaration with
4574     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4575     //
4576     // If the declaration we're planning to build will be declared with
4577     // external linkage in the translation unit, create any builtin with
4578     // the same name.
4579     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4580       /* Do nothing*/;
4581     else if (CurContext->isFunctionOrMethod() &&
4582              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4583               R->isFunctionType())) {
4584       IsLinkageLookup = true;
4585       CreateBuiltins =
4586           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4587     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4588                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4589       CreateBuiltins = true;
4590 
4591     if (IsLinkageLookup)
4592       Previous.clear(LookupRedeclarationWithLinkage);
4593 
4594     LookupName(Previous, S, CreateBuiltins);
4595   } else { // Something like "int foo::x;"
4596     LookupQualifiedName(Previous, DC);
4597 
4598     // C++ [dcl.meaning]p1:
4599     //   When the declarator-id is qualified, the declaration shall refer to a
4600     //  previously declared member of the class or namespace to which the
4601     //  qualifier refers (or, in the case of a namespace, of an element of the
4602     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4603     //  thereof; [...]
4604     //
4605     // Note that we already checked the context above, and that we do not have
4606     // enough information to make sure that Previous contains the declaration
4607     // we want to match. For example, given:
4608     //
4609     //   class X {
4610     //     void f();
4611     //     void f(float);
4612     //   };
4613     //
4614     //   void X::f(int) { } // ill-formed
4615     //
4616     // In this case, Previous will point to the overload set
4617     // containing the two f's declared in X, but neither of them
4618     // matches.
4619 
4620     // C++ [dcl.meaning]p1:
4621     //   [...] the member shall not merely have been introduced by a
4622     //   using-declaration in the scope of the class or namespace nominated by
4623     //   the nested-name-specifier of the declarator-id.
4624     RemoveUsingDecls(Previous);
4625   }
4626 
4627   if (Previous.isSingleResult() &&
4628       Previous.getFoundDecl()->isTemplateParameter()) {
4629     // Maybe we will complain about the shadowed template parameter.
4630     if (!D.isInvalidType())
4631       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4632                                       Previous.getFoundDecl());
4633 
4634     // Just pretend that we didn't see the previous declaration.
4635     Previous.clear();
4636   }
4637 
4638   // In C++, the previous declaration we find might be a tag type
4639   // (class or enum). In this case, the new declaration will hide the
4640   // tag type. Note that this does does not apply if we're declaring a
4641   // typedef (C++ [dcl.typedef]p4).
4642   if (Previous.isSingleTagDecl() &&
4643       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4644     Previous.clear();
4645 
4646   // Check that there are no default arguments other than in the parameters
4647   // of a function declaration (C++ only).
4648   if (getLangOpts().CPlusPlus)
4649     CheckExtraCXXDefaultArguments(D);
4650 
4651   NamedDecl *New;
4652 
4653   bool AddToScope = true;
4654   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4655     if (TemplateParamLists.size()) {
4656       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4657       return nullptr;
4658     }
4659 
4660     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4661   } else if (R->isFunctionType()) {
4662     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4663                                   TemplateParamLists,
4664                                   AddToScope);
4665   } else {
4666     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4667                                   AddToScope);
4668   }
4669 
4670   if (!New)
4671     return nullptr;
4672 
4673   // If this has an identifier and is not an invalid redeclaration or
4674   // function template specialization, add it to the scope stack.
4675   if (New->getDeclName() && AddToScope &&
4676        !(D.isRedeclaration() && New->isInvalidDecl())) {
4677     // Only make a locally-scoped extern declaration visible if it is the first
4678     // declaration of this entity. Qualified lookup for such an entity should
4679     // only find this declaration if there is no visible declaration of it.
4680     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4681     PushOnScopeChains(New, S, AddToContext);
4682     if (!AddToContext)
4683       CurContext->addHiddenDecl(New);
4684   }
4685 
4686   return New;
4687 }
4688 
4689 /// Helper method to turn variable array types into constant array
4690 /// types in certain situations which would otherwise be errors (for
4691 /// GCC compatibility).
4692 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4693                                                     ASTContext &Context,
4694                                                     bool &SizeIsNegative,
4695                                                     llvm::APSInt &Oversized) {
4696   // This method tries to turn a variable array into a constant
4697   // array even when the size isn't an ICE.  This is necessary
4698   // for compatibility with code that depends on gcc's buggy
4699   // constant expression folding, like struct {char x[(int)(char*)2];}
4700   SizeIsNegative = false;
4701   Oversized = 0;
4702 
4703   if (T->isDependentType())
4704     return QualType();
4705 
4706   QualifierCollector Qs;
4707   const Type *Ty = Qs.strip(T);
4708 
4709   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4710     QualType Pointee = PTy->getPointeeType();
4711     QualType FixedType =
4712         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4713                                             Oversized);
4714     if (FixedType.isNull()) return FixedType;
4715     FixedType = Context.getPointerType(FixedType);
4716     return Qs.apply(Context, FixedType);
4717   }
4718   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4719     QualType Inner = PTy->getInnerType();
4720     QualType FixedType =
4721         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4722                                             Oversized);
4723     if (FixedType.isNull()) return FixedType;
4724     FixedType = Context.getParenType(FixedType);
4725     return Qs.apply(Context, FixedType);
4726   }
4727 
4728   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4729   if (!VLATy)
4730     return QualType();
4731   // FIXME: We should probably handle this case
4732   if (VLATy->getElementType()->isVariablyModifiedType())
4733     return QualType();
4734 
4735   llvm::APSInt Res;
4736   if (!VLATy->getSizeExpr() ||
4737       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4738     return QualType();
4739 
4740   // Check whether the array size is negative.
4741   if (Res.isSigned() && Res.isNegative()) {
4742     SizeIsNegative = true;
4743     return QualType();
4744   }
4745 
4746   // Check whether the array is too large to be addressed.
4747   unsigned ActiveSizeBits
4748     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4749                                               Res);
4750   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4751     Oversized = Res;
4752     return QualType();
4753   }
4754 
4755   return Context.getConstantArrayType(VLATy->getElementType(),
4756                                       Res, ArrayType::Normal, 0);
4757 }
4758 
4759 static void
4760 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4761   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4762     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4763     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4764                                       DstPTL.getPointeeLoc());
4765     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4766     return;
4767   }
4768   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4769     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4770     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4771                                       DstPTL.getInnerLoc());
4772     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4773     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4774     return;
4775   }
4776   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4777   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4778   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4779   TypeLoc DstElemTL = DstATL.getElementLoc();
4780   DstElemTL.initializeFullCopy(SrcElemTL);
4781   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4782   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4783   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4784 }
4785 
4786 /// Helper method to turn variable array types into constant array
4787 /// types in certain situations which would otherwise be errors (for
4788 /// GCC compatibility).
4789 static TypeSourceInfo*
4790 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4791                                               ASTContext &Context,
4792                                               bool &SizeIsNegative,
4793                                               llvm::APSInt &Oversized) {
4794   QualType FixedTy
4795     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4796                                           SizeIsNegative, Oversized);
4797   if (FixedTy.isNull())
4798     return nullptr;
4799   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4800   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4801                                     FixedTInfo->getTypeLoc());
4802   return FixedTInfo;
4803 }
4804 
4805 /// \brief Register the given locally-scoped extern "C" declaration so
4806 /// that it can be found later for redeclarations. We include any extern "C"
4807 /// declaration that is not visible in the translation unit here, not just
4808 /// function-scope declarations.
4809 void
4810 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4811   if (!getLangOpts().CPlusPlus &&
4812       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4813     // Don't need to track declarations in the TU in C.
4814     return;
4815 
4816   // Note that we have a locally-scoped external with this name.
4817   // FIXME: There can be multiple such declarations if they are functions marked
4818   // __attribute__((overloadable)) declared in function scope in C.
4819   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4820 }
4821 
4822 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4823   if (ExternalSource) {
4824     // Load locally-scoped external decls from the external source.
4825     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4826     SmallVector<NamedDecl *, 4> Decls;
4827     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4828     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4829       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4830         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4831       if (Pos == LocallyScopedExternCDecls.end())
4832         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4833     }
4834   }
4835 
4836   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4837   return D ? D->getMostRecentDecl() : nullptr;
4838 }
4839 
4840 /// \brief Diagnose function specifiers on a declaration of an identifier that
4841 /// does not identify a function.
4842 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4843   // FIXME: We should probably indicate the identifier in question to avoid
4844   // confusion for constructs like "inline int a(), b;"
4845   if (DS.isInlineSpecified())
4846     Diag(DS.getInlineSpecLoc(),
4847          diag::err_inline_non_function);
4848 
4849   if (DS.isVirtualSpecified())
4850     Diag(DS.getVirtualSpecLoc(),
4851          diag::err_virtual_non_function);
4852 
4853   if (DS.isExplicitSpecified())
4854     Diag(DS.getExplicitSpecLoc(),
4855          diag::err_explicit_non_function);
4856 
4857   if (DS.isNoreturnSpecified())
4858     Diag(DS.getNoreturnSpecLoc(),
4859          diag::err_noreturn_non_function);
4860 }
4861 
4862 NamedDecl*
4863 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4864                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4865   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4866   if (D.getCXXScopeSpec().isSet()) {
4867     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4868       << D.getCXXScopeSpec().getRange();
4869     D.setInvalidType();
4870     // Pretend we didn't see the scope specifier.
4871     DC = CurContext;
4872     Previous.clear();
4873   }
4874 
4875   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4876 
4877   if (D.getDeclSpec().isConstexprSpecified())
4878     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4879       << 1;
4880 
4881   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4882     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4883       << D.getName().getSourceRange();
4884     return nullptr;
4885   }
4886 
4887   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4888   if (!NewTD) return nullptr;
4889 
4890   // Handle attributes prior to checking for duplicates in MergeVarDecl
4891   ProcessDeclAttributes(S, NewTD, D);
4892 
4893   CheckTypedefForVariablyModifiedType(S, NewTD);
4894 
4895   bool Redeclaration = D.isRedeclaration();
4896   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4897   D.setRedeclaration(Redeclaration);
4898   return ND;
4899 }
4900 
4901 void
4902 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4903   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4904   // then it shall have block scope.
4905   // Note that variably modified types must be fixed before merging the decl so
4906   // that redeclarations will match.
4907   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4908   QualType T = TInfo->getType();
4909   if (T->isVariablyModifiedType()) {
4910     getCurFunction()->setHasBranchProtectedScope();
4911 
4912     if (S->getFnParent() == nullptr) {
4913       bool SizeIsNegative;
4914       llvm::APSInt Oversized;
4915       TypeSourceInfo *FixedTInfo =
4916         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4917                                                       SizeIsNegative,
4918                                                       Oversized);
4919       if (FixedTInfo) {
4920         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4921         NewTD->setTypeSourceInfo(FixedTInfo);
4922       } else {
4923         if (SizeIsNegative)
4924           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4925         else if (T->isVariableArrayType())
4926           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4927         else if (Oversized.getBoolValue())
4928           Diag(NewTD->getLocation(), diag::err_array_too_large)
4929             << Oversized.toString(10);
4930         else
4931           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4932         NewTD->setInvalidDecl();
4933       }
4934     }
4935   }
4936 }
4937 
4938 
4939 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4940 /// declares a typedef-name, either using the 'typedef' type specifier or via
4941 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4942 NamedDecl*
4943 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4944                            LookupResult &Previous, bool &Redeclaration) {
4945   // Merge the decl with the existing one if appropriate. If the decl is
4946   // in an outer scope, it isn't the same thing.
4947   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4948                        /*AllowInlineNamespace*/false);
4949   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
4950   if (!Previous.empty()) {
4951     Redeclaration = true;
4952     MergeTypedefNameDecl(NewTD, Previous);
4953   }
4954 
4955   // If this is the C FILE type, notify the AST context.
4956   if (IdentifierInfo *II = NewTD->getIdentifier())
4957     if (!NewTD->isInvalidDecl() &&
4958         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4959       if (II->isStr("FILE"))
4960         Context.setFILEDecl(NewTD);
4961       else if (II->isStr("jmp_buf"))
4962         Context.setjmp_bufDecl(NewTD);
4963       else if (II->isStr("sigjmp_buf"))
4964         Context.setsigjmp_bufDecl(NewTD);
4965       else if (II->isStr("ucontext_t"))
4966         Context.setucontext_tDecl(NewTD);
4967     }
4968 
4969   return NewTD;
4970 }
4971 
4972 /// \brief Determines whether the given declaration is an out-of-scope
4973 /// previous declaration.
4974 ///
4975 /// This routine should be invoked when name lookup has found a
4976 /// previous declaration (PrevDecl) that is not in the scope where a
4977 /// new declaration by the same name is being introduced. If the new
4978 /// declaration occurs in a local scope, previous declarations with
4979 /// linkage may still be considered previous declarations (C99
4980 /// 6.2.2p4-5, C++ [basic.link]p6).
4981 ///
4982 /// \param PrevDecl the previous declaration found by name
4983 /// lookup
4984 ///
4985 /// \param DC the context in which the new declaration is being
4986 /// declared.
4987 ///
4988 /// \returns true if PrevDecl is an out-of-scope previous declaration
4989 /// for a new delcaration with the same name.
4990 static bool
4991 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4992                                 ASTContext &Context) {
4993   if (!PrevDecl)
4994     return false;
4995 
4996   if (!PrevDecl->hasLinkage())
4997     return false;
4998 
4999   if (Context.getLangOpts().CPlusPlus) {
5000     // C++ [basic.link]p6:
5001     //   If there is a visible declaration of an entity with linkage
5002     //   having the same name and type, ignoring entities declared
5003     //   outside the innermost enclosing namespace scope, the block
5004     //   scope declaration declares that same entity and receives the
5005     //   linkage of the previous declaration.
5006     DeclContext *OuterContext = DC->getRedeclContext();
5007     if (!OuterContext->isFunctionOrMethod())
5008       // This rule only applies to block-scope declarations.
5009       return false;
5010 
5011     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5012     if (PrevOuterContext->isRecord())
5013       // We found a member function: ignore it.
5014       return false;
5015 
5016     // Find the innermost enclosing namespace for the new and
5017     // previous declarations.
5018     OuterContext = OuterContext->getEnclosingNamespaceContext();
5019     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5020 
5021     // The previous declaration is in a different namespace, so it
5022     // isn't the same function.
5023     if (!OuterContext->Equals(PrevOuterContext))
5024       return false;
5025   }
5026 
5027   return true;
5028 }
5029 
5030 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5031   CXXScopeSpec &SS = D.getCXXScopeSpec();
5032   if (!SS.isSet()) return;
5033   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5034 }
5035 
5036 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5037   QualType type = decl->getType();
5038   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5039   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5040     // Various kinds of declaration aren't allowed to be __autoreleasing.
5041     unsigned kind = -1U;
5042     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5043       if (var->hasAttr<BlocksAttr>())
5044         kind = 0; // __block
5045       else if (!var->hasLocalStorage())
5046         kind = 1; // global
5047     } else if (isa<ObjCIvarDecl>(decl)) {
5048       kind = 3; // ivar
5049     } else if (isa<FieldDecl>(decl)) {
5050       kind = 2; // field
5051     }
5052 
5053     if (kind != -1U) {
5054       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5055         << kind;
5056     }
5057   } else if (lifetime == Qualifiers::OCL_None) {
5058     // Try to infer lifetime.
5059     if (!type->isObjCLifetimeType())
5060       return false;
5061 
5062     lifetime = type->getObjCARCImplicitLifetime();
5063     type = Context.getLifetimeQualifiedType(type, lifetime);
5064     decl->setType(type);
5065   }
5066 
5067   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5068     // Thread-local variables cannot have lifetime.
5069     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5070         var->getTLSKind()) {
5071       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5072         << var->getType();
5073       return true;
5074     }
5075   }
5076 
5077   return false;
5078 }
5079 
5080 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5081   // Ensure that an auto decl is deduced otherwise the checks below might cache
5082   // the wrong linkage.
5083   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5084 
5085   // 'weak' only applies to declarations with external linkage.
5086   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5087     if (!ND.isExternallyVisible()) {
5088       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5089       ND.dropAttr<WeakAttr>();
5090     }
5091   }
5092   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5093     if (ND.isExternallyVisible()) {
5094       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5095       ND.dropAttr<WeakRefAttr>();
5096     }
5097   }
5098 
5099   // 'selectany' only applies to externally visible varable declarations.
5100   // It does not apply to functions.
5101   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5102     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5103       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5104       ND.dropAttr<SelectAnyAttr>();
5105     }
5106   }
5107 
5108   // dll attributes require external linkage.
5109   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5110     if (!ND.isExternallyVisible()) {
5111       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5112         << &ND << Attr;
5113       ND.setInvalidDecl();
5114     }
5115   }
5116 }
5117 
5118 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5119                                            NamedDecl *NewDecl,
5120                                            bool IsSpecialization) {
5121   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5122     OldDecl = OldTD->getTemplatedDecl();
5123   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5124     NewDecl = NewTD->getTemplatedDecl();
5125 
5126   if (!OldDecl || !NewDecl)
5127     return;
5128 
5129   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5130   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5131   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5132   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5133 
5134   // dllimport and dllexport are inheritable attributes so we have to exclude
5135   // inherited attribute instances.
5136   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5137                     (NewExportAttr && !NewExportAttr->isInherited());
5138 
5139   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5140   // the only exception being explicit specializations.
5141   // Implicitly generated declarations are also excluded for now because there
5142   // is no other way to switch these to use dllimport or dllexport.
5143   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5144 
5145   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5146     // If the declaration hasn't been used yet, allow with a warning for
5147     // free functions and global variables.
5148     bool JustWarn = false;
5149     if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) {
5150       auto *VD = dyn_cast<VarDecl>(OldDecl);
5151       if (VD && !VD->getDescribedVarTemplate())
5152         JustWarn = true;
5153       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5154       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5155         JustWarn = true;
5156     }
5157 
5158     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5159                                : diag::err_attribute_dll_redeclaration;
5160     S.Diag(NewDecl->getLocation(), DiagID)
5161         << NewDecl
5162         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5163     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5164     if (!JustWarn) {
5165       NewDecl->setInvalidDecl();
5166       return;
5167     }
5168   }
5169 
5170   // A redeclaration is not allowed to drop a dllimport attribute, the only
5171   // exceptions being inline function definitions, local extern declarations,
5172   // and qualified friend declarations.
5173   // NB: MSVC converts such a declaration to dllexport.
5174   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5175   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5176     // Ignore static data because out-of-line definitions are diagnosed
5177     // separately.
5178     IsStaticDataMember = VD->isStaticDataMember();
5179   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5180     IsInline = FD->isInlined();
5181     IsQualifiedFriend = FD->getQualifier() &&
5182                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5183   }
5184 
5185   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5186       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5187     S.Diag(NewDecl->getLocation(),
5188            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5189       << NewDecl << OldImportAttr;
5190     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5191     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5192     OldDecl->dropAttr<DLLImportAttr>();
5193     NewDecl->dropAttr<DLLImportAttr>();
5194   } else if (IsInline && OldImportAttr &&
5195              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5196     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5197     OldDecl->dropAttr<DLLImportAttr>();
5198     NewDecl->dropAttr<DLLImportAttr>();
5199     S.Diag(NewDecl->getLocation(),
5200            diag::warn_dllimport_dropped_from_inline_function)
5201         << NewDecl << OldImportAttr;
5202   }
5203 }
5204 
5205 /// Given that we are within the definition of the given function,
5206 /// will that definition behave like C99's 'inline', where the
5207 /// definition is discarded except for optimization purposes?
5208 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5209   // Try to avoid calling GetGVALinkageForFunction.
5210 
5211   // All cases of this require the 'inline' keyword.
5212   if (!FD->isInlined()) return false;
5213 
5214   // This is only possible in C++ with the gnu_inline attribute.
5215   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5216     return false;
5217 
5218   // Okay, go ahead and call the relatively-more-expensive function.
5219 
5220 #ifndef NDEBUG
5221   // AST quite reasonably asserts that it's working on a function
5222   // definition.  We don't really have a way to tell it that we're
5223   // currently defining the function, so just lie to it in +Asserts
5224   // builds.  This is an awful hack.
5225   FD->setLazyBody(1);
5226 #endif
5227 
5228   bool isC99Inline =
5229       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5230 
5231 #ifndef NDEBUG
5232   FD->setLazyBody(0);
5233 #endif
5234 
5235   return isC99Inline;
5236 }
5237 
5238 /// Determine whether a variable is extern "C" prior to attaching
5239 /// an initializer. We can't just call isExternC() here, because that
5240 /// will also compute and cache whether the declaration is externally
5241 /// visible, which might change when we attach the initializer.
5242 ///
5243 /// This can only be used if the declaration is known to not be a
5244 /// redeclaration of an internal linkage declaration.
5245 ///
5246 /// For instance:
5247 ///
5248 ///   auto x = []{};
5249 ///
5250 /// Attaching the initializer here makes this declaration not externally
5251 /// visible, because its type has internal linkage.
5252 ///
5253 /// FIXME: This is a hack.
5254 template<typename T>
5255 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5256   if (S.getLangOpts().CPlusPlus) {
5257     // In C++, the overloadable attribute negates the effects of extern "C".
5258     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5259       return false;
5260   }
5261   return D->isExternC();
5262 }
5263 
5264 static bool shouldConsiderLinkage(const VarDecl *VD) {
5265   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5266   if (DC->isFunctionOrMethod())
5267     return VD->hasExternalStorage();
5268   if (DC->isFileContext())
5269     return true;
5270   if (DC->isRecord())
5271     return false;
5272   llvm_unreachable("Unexpected context");
5273 }
5274 
5275 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5276   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5277   if (DC->isFileContext() || DC->isFunctionOrMethod())
5278     return true;
5279   if (DC->isRecord())
5280     return false;
5281   llvm_unreachable("Unexpected context");
5282 }
5283 
5284 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5285                           AttributeList::Kind Kind) {
5286   for (const AttributeList *L = AttrList; L; L = L->getNext())
5287     if (L->getKind() == Kind)
5288       return true;
5289   return false;
5290 }
5291 
5292 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5293                           AttributeList::Kind Kind) {
5294   // Check decl attributes on the DeclSpec.
5295   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5296     return true;
5297 
5298   // Walk the declarator structure, checking decl attributes that were in a type
5299   // position to the decl itself.
5300   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5301     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5302       return true;
5303   }
5304 
5305   // Finally, check attributes on the decl itself.
5306   return hasParsedAttr(S, PD.getAttributes(), Kind);
5307 }
5308 
5309 /// Adjust the \c DeclContext for a function or variable that might be a
5310 /// function-local external declaration.
5311 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5312   if (!DC->isFunctionOrMethod())
5313     return false;
5314 
5315   // If this is a local extern function or variable declared within a function
5316   // template, don't add it into the enclosing namespace scope until it is
5317   // instantiated; it might have a dependent type right now.
5318   if (DC->isDependentContext())
5319     return true;
5320 
5321   // C++11 [basic.link]p7:
5322   //   When a block scope declaration of an entity with linkage is not found to
5323   //   refer to some other declaration, then that entity is a member of the
5324   //   innermost enclosing namespace.
5325   //
5326   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5327   // semantically-enclosing namespace, not a lexically-enclosing one.
5328   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5329     DC = DC->getParent();
5330   return true;
5331 }
5332 
5333 NamedDecl *
5334 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5335                               TypeSourceInfo *TInfo, LookupResult &Previous,
5336                               MultiTemplateParamsArg TemplateParamLists,
5337                               bool &AddToScope) {
5338   QualType R = TInfo->getType();
5339   DeclarationName Name = GetNameForDeclarator(D).getName();
5340 
5341   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5342   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5343 
5344   // dllimport globals without explicit storage class are treated as extern. We
5345   // have to change the storage class this early to get the right DeclContext.
5346   if (SC == SC_None && !DC->isRecord() &&
5347       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5348       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5349     SC = SC_Extern;
5350 
5351   DeclContext *OriginalDC = DC;
5352   bool IsLocalExternDecl = SC == SC_Extern &&
5353                            adjustContextForLocalExternDecl(DC);
5354 
5355   if (getLangOpts().OpenCL) {
5356     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5357     QualType NR = R;
5358     while (NR->isPointerType()) {
5359       if (NR->isFunctionPointerType()) {
5360         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5361         D.setInvalidType();
5362         break;
5363       }
5364       NR = NR->getPointeeType();
5365     }
5366 
5367     if (!getOpenCLOptions().cl_khr_fp16) {
5368       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5369       // half array type (unless the cl_khr_fp16 extension is enabled).
5370       if (Context.getBaseElementType(R)->isHalfType()) {
5371         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5372         D.setInvalidType();
5373       }
5374     }
5375   }
5376 
5377   if (SCSpec == DeclSpec::SCS_mutable) {
5378     // mutable can only appear on non-static class members, so it's always
5379     // an error here
5380     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5381     D.setInvalidType();
5382     SC = SC_None;
5383   }
5384 
5385   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5386       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5387                               D.getDeclSpec().getStorageClassSpecLoc())) {
5388     // In C++11, the 'register' storage class specifier is deprecated.
5389     // Suppress the warning in system macros, it's used in macros in some
5390     // popular C system headers, such as in glibc's htonl() macro.
5391     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5392          diag::warn_deprecated_register)
5393       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5394   }
5395 
5396   IdentifierInfo *II = Name.getAsIdentifierInfo();
5397   if (!II) {
5398     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5399       << Name;
5400     return nullptr;
5401   }
5402 
5403   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5404 
5405   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5406     // C99 6.9p2: The storage-class specifiers auto and register shall not
5407     // appear in the declaration specifiers in an external declaration.
5408     // Global Register+Asm is a GNU extension we support.
5409     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5410       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5411       D.setInvalidType();
5412     }
5413   }
5414 
5415   if (getLangOpts().OpenCL) {
5416     // Set up the special work-group-local storage class for variables in the
5417     // OpenCL __local address space.
5418     if (R.getAddressSpace() == LangAS::opencl_local) {
5419       SC = SC_OpenCLWorkGroupLocal;
5420     }
5421 
5422     // OpenCL v1.2 s6.9.b p4:
5423     // The sampler type cannot be used with the __local and __global address
5424     // space qualifiers.
5425     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5426       R.getAddressSpace() == LangAS::opencl_global)) {
5427       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5428     }
5429 
5430     // OpenCL 1.2 spec, p6.9 r:
5431     // The event type cannot be used to declare a program scope variable.
5432     // The event type cannot be used with the __local, __constant and __global
5433     // address space qualifiers.
5434     if (R->isEventT()) {
5435       if (S->getParent() == nullptr) {
5436         Diag(D.getLocStart(), diag::err_event_t_global_var);
5437         D.setInvalidType();
5438       }
5439 
5440       if (R.getAddressSpace()) {
5441         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5442         D.setInvalidType();
5443       }
5444     }
5445   }
5446 
5447   bool IsExplicitSpecialization = false;
5448   bool IsVariableTemplateSpecialization = false;
5449   bool IsPartialSpecialization = false;
5450   bool IsVariableTemplate = false;
5451   VarDecl *NewVD = nullptr;
5452   VarTemplateDecl *NewTemplate = nullptr;
5453   TemplateParameterList *TemplateParams = nullptr;
5454   if (!getLangOpts().CPlusPlus) {
5455     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5456                             D.getIdentifierLoc(), II,
5457                             R, TInfo, SC);
5458 
5459     if (D.isInvalidType())
5460       NewVD->setInvalidDecl();
5461   } else {
5462     bool Invalid = false;
5463 
5464     if (DC->isRecord() && !CurContext->isRecord()) {
5465       // This is an out-of-line definition of a static data member.
5466       switch (SC) {
5467       case SC_None:
5468         break;
5469       case SC_Static:
5470         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5471              diag::err_static_out_of_line)
5472           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5473         break;
5474       case SC_Auto:
5475       case SC_Register:
5476       case SC_Extern:
5477         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5478         // to names of variables declared in a block or to function parameters.
5479         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5480         // of class members
5481 
5482         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5483              diag::err_storage_class_for_static_member)
5484           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5485         break;
5486       case SC_PrivateExtern:
5487         llvm_unreachable("C storage class in c++!");
5488       case SC_OpenCLWorkGroupLocal:
5489         llvm_unreachable("OpenCL storage class in c++!");
5490       }
5491     }
5492 
5493     if (SC == SC_Static && CurContext->isRecord()) {
5494       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5495         if (RD->isLocalClass())
5496           Diag(D.getIdentifierLoc(),
5497                diag::err_static_data_member_not_allowed_in_local_class)
5498             << Name << RD->getDeclName();
5499 
5500         // C++98 [class.union]p1: If a union contains a static data member,
5501         // the program is ill-formed. C++11 drops this restriction.
5502         if (RD->isUnion())
5503           Diag(D.getIdentifierLoc(),
5504                getLangOpts().CPlusPlus11
5505                  ? diag::warn_cxx98_compat_static_data_member_in_union
5506                  : diag::ext_static_data_member_in_union) << Name;
5507         // We conservatively disallow static data members in anonymous structs.
5508         else if (!RD->getDeclName())
5509           Diag(D.getIdentifierLoc(),
5510                diag::err_static_data_member_not_allowed_in_anon_struct)
5511             << Name << RD->isUnion();
5512       }
5513     }
5514 
5515     // Match up the template parameter lists with the scope specifier, then
5516     // determine whether we have a template or a template specialization.
5517     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5518         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5519         D.getCXXScopeSpec(),
5520         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5521             ? D.getName().TemplateId
5522             : nullptr,
5523         TemplateParamLists,
5524         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5525 
5526     if (TemplateParams) {
5527       if (!TemplateParams->size() &&
5528           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5529         // There is an extraneous 'template<>' for this variable. Complain
5530         // about it, but allow the declaration of the variable.
5531         Diag(TemplateParams->getTemplateLoc(),
5532              diag::err_template_variable_noparams)
5533           << II
5534           << SourceRange(TemplateParams->getTemplateLoc(),
5535                          TemplateParams->getRAngleLoc());
5536         TemplateParams = nullptr;
5537       } else {
5538         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5539           // This is an explicit specialization or a partial specialization.
5540           // FIXME: Check that we can declare a specialization here.
5541           IsVariableTemplateSpecialization = true;
5542           IsPartialSpecialization = TemplateParams->size() > 0;
5543         } else { // if (TemplateParams->size() > 0)
5544           // This is a template declaration.
5545           IsVariableTemplate = true;
5546 
5547           // Check that we can declare a template here.
5548           if (CheckTemplateDeclScope(S, TemplateParams))
5549             return nullptr;
5550 
5551           // Only C++1y supports variable templates (N3651).
5552           Diag(D.getIdentifierLoc(),
5553                getLangOpts().CPlusPlus14
5554                    ? diag::warn_cxx11_compat_variable_template
5555                    : diag::ext_variable_template);
5556         }
5557       }
5558     } else {
5559       assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5560              "should have a 'template<>' for this decl");
5561     }
5562 
5563     if (IsVariableTemplateSpecialization) {
5564       SourceLocation TemplateKWLoc =
5565           TemplateParamLists.size() > 0
5566               ? TemplateParamLists[0]->getTemplateLoc()
5567               : SourceLocation();
5568       DeclResult Res = ActOnVarTemplateSpecialization(
5569           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5570           IsPartialSpecialization);
5571       if (Res.isInvalid())
5572         return nullptr;
5573       NewVD = cast<VarDecl>(Res.get());
5574       AddToScope = false;
5575     } else
5576       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5577                               D.getIdentifierLoc(), II, R, TInfo, SC);
5578 
5579     // If this is supposed to be a variable template, create it as such.
5580     if (IsVariableTemplate) {
5581       NewTemplate =
5582           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5583                                   TemplateParams, NewVD);
5584       NewVD->setDescribedVarTemplate(NewTemplate);
5585     }
5586 
5587     // If this decl has an auto type in need of deduction, make a note of the
5588     // Decl so we can diagnose uses of it in its own initializer.
5589     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5590       ParsingInitForAutoVars.insert(NewVD);
5591 
5592     if (D.isInvalidType() || Invalid) {
5593       NewVD->setInvalidDecl();
5594       if (NewTemplate)
5595         NewTemplate->setInvalidDecl();
5596     }
5597 
5598     SetNestedNameSpecifier(NewVD, D);
5599 
5600     // If we have any template parameter lists that don't directly belong to
5601     // the variable (matching the scope specifier), store them.
5602     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5603     if (TemplateParamLists.size() > VDTemplateParamLists)
5604       NewVD->setTemplateParameterListsInfo(
5605           Context, TemplateParamLists.size() - VDTemplateParamLists,
5606           TemplateParamLists.data());
5607 
5608     if (D.getDeclSpec().isConstexprSpecified())
5609       NewVD->setConstexpr(true);
5610   }
5611 
5612   // Set the lexical context. If the declarator has a C++ scope specifier, the
5613   // lexical context will be different from the semantic context.
5614   NewVD->setLexicalDeclContext(CurContext);
5615   if (NewTemplate)
5616     NewTemplate->setLexicalDeclContext(CurContext);
5617 
5618   if (IsLocalExternDecl)
5619     NewVD->setLocalExternDecl();
5620 
5621   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5622     // C++11 [dcl.stc]p4:
5623     //   When thread_local is applied to a variable of block scope the
5624     //   storage-class-specifier static is implied if it does not appear
5625     //   explicitly.
5626     // Core issue: 'static' is not implied if the variable is declared
5627     //   'extern'.
5628     if (NewVD->hasLocalStorage() &&
5629         (SCSpec != DeclSpec::SCS_unspecified ||
5630          TSCS != DeclSpec::TSCS_thread_local ||
5631          !DC->isFunctionOrMethod()))
5632       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5633            diag::err_thread_non_global)
5634         << DeclSpec::getSpecifierName(TSCS);
5635     else if (!Context.getTargetInfo().isTLSSupported())
5636       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5637            diag::err_thread_unsupported);
5638     else
5639       NewVD->setTSCSpec(TSCS);
5640   }
5641 
5642   // C99 6.7.4p3
5643   //   An inline definition of a function with external linkage shall
5644   //   not contain a definition of a modifiable object with static or
5645   //   thread storage duration...
5646   // We only apply this when the function is required to be defined
5647   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5648   // that a local variable with thread storage duration still has to
5649   // be marked 'static'.  Also note that it's possible to get these
5650   // semantics in C++ using __attribute__((gnu_inline)).
5651   if (SC == SC_Static && S->getFnParent() != nullptr &&
5652       !NewVD->getType().isConstQualified()) {
5653     FunctionDecl *CurFD = getCurFunctionDecl();
5654     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5655       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5656            diag::warn_static_local_in_extern_inline);
5657       MaybeSuggestAddingStaticToDecl(CurFD);
5658     }
5659   }
5660 
5661   if (D.getDeclSpec().isModulePrivateSpecified()) {
5662     if (IsVariableTemplateSpecialization)
5663       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5664           << (IsPartialSpecialization ? 1 : 0)
5665           << FixItHint::CreateRemoval(
5666                  D.getDeclSpec().getModulePrivateSpecLoc());
5667     else if (IsExplicitSpecialization)
5668       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5669         << 2
5670         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5671     else if (NewVD->hasLocalStorage())
5672       Diag(NewVD->getLocation(), diag::err_module_private_local)
5673         << 0 << NewVD->getDeclName()
5674         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5675         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5676     else {
5677       NewVD->setModulePrivate();
5678       if (NewTemplate)
5679         NewTemplate->setModulePrivate();
5680     }
5681   }
5682 
5683   // Handle attributes prior to checking for duplicates in MergeVarDecl
5684   ProcessDeclAttributes(S, NewVD, D);
5685 
5686   if (getLangOpts().CUDA) {
5687     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5688     // storage [duration]."
5689     if (SC == SC_None && S->getFnParent() != nullptr &&
5690         (NewVD->hasAttr<CUDASharedAttr>() ||
5691          NewVD->hasAttr<CUDAConstantAttr>())) {
5692       NewVD->setStorageClass(SC_Static);
5693     }
5694   }
5695 
5696   // Ensure that dllimport globals without explicit storage class are treated as
5697   // extern. The storage class is set above using parsed attributes. Now we can
5698   // check the VarDecl itself.
5699   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5700          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5701          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5702 
5703   // In auto-retain/release, infer strong retension for variables of
5704   // retainable type.
5705   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5706     NewVD->setInvalidDecl();
5707 
5708   // Handle GNU asm-label extension (encoded as an attribute).
5709   if (Expr *E = (Expr*)D.getAsmLabel()) {
5710     // The parser guarantees this is a string.
5711     StringLiteral *SE = cast<StringLiteral>(E);
5712     StringRef Label = SE->getString();
5713     if (S->getFnParent() != nullptr) {
5714       switch (SC) {
5715       case SC_None:
5716       case SC_Auto:
5717         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5718         break;
5719       case SC_Register:
5720         // Local Named register
5721         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5722           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5723         break;
5724       case SC_Static:
5725       case SC_Extern:
5726       case SC_PrivateExtern:
5727       case SC_OpenCLWorkGroupLocal:
5728         break;
5729       }
5730     } else if (SC == SC_Register) {
5731       // Global Named register
5732       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5733         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5734       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5735         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5736         NewVD->setInvalidDecl(true);
5737       }
5738     }
5739 
5740     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5741                                                 Context, Label, 0));
5742   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5743     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5744       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5745     if (I != ExtnameUndeclaredIdentifiers.end()) {
5746       NewVD->addAttr(I->second);
5747       ExtnameUndeclaredIdentifiers.erase(I);
5748     }
5749   }
5750 
5751   // Diagnose shadowed variables before filtering for scope.
5752   if (D.getCXXScopeSpec().isEmpty())
5753     CheckShadow(S, NewVD, Previous);
5754 
5755   // Don't consider existing declarations that are in a different
5756   // scope and are out-of-semantic-context declarations (if the new
5757   // declaration has linkage).
5758   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5759                        D.getCXXScopeSpec().isNotEmpty() ||
5760                        IsExplicitSpecialization ||
5761                        IsVariableTemplateSpecialization);
5762 
5763   // Check whether the previous declaration is in the same block scope. This
5764   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5765   if (getLangOpts().CPlusPlus &&
5766       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5767     NewVD->setPreviousDeclInSameBlockScope(
5768         Previous.isSingleResult() && !Previous.isShadowed() &&
5769         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5770 
5771   if (!getLangOpts().CPlusPlus) {
5772     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5773   } else {
5774     // If this is an explicit specialization of a static data member, check it.
5775     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5776         CheckMemberSpecialization(NewVD, Previous))
5777       NewVD->setInvalidDecl();
5778 
5779     // Merge the decl with the existing one if appropriate.
5780     if (!Previous.empty()) {
5781       if (Previous.isSingleResult() &&
5782           isa<FieldDecl>(Previous.getFoundDecl()) &&
5783           D.getCXXScopeSpec().isSet()) {
5784         // The user tried to define a non-static data member
5785         // out-of-line (C++ [dcl.meaning]p1).
5786         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5787           << D.getCXXScopeSpec().getRange();
5788         Previous.clear();
5789         NewVD->setInvalidDecl();
5790       }
5791     } else if (D.getCXXScopeSpec().isSet()) {
5792       // No previous declaration in the qualifying scope.
5793       Diag(D.getIdentifierLoc(), diag::err_no_member)
5794         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5795         << D.getCXXScopeSpec().getRange();
5796       NewVD->setInvalidDecl();
5797     }
5798 
5799     if (!IsVariableTemplateSpecialization)
5800       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5801 
5802     if (NewTemplate) {
5803       VarTemplateDecl *PrevVarTemplate =
5804           NewVD->getPreviousDecl()
5805               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5806               : nullptr;
5807 
5808       // Check the template parameter list of this declaration, possibly
5809       // merging in the template parameter list from the previous variable
5810       // template declaration.
5811       if (CheckTemplateParameterList(
5812               TemplateParams,
5813               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5814                               : nullptr,
5815               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5816                DC->isDependentContext())
5817                   ? TPC_ClassTemplateMember
5818                   : TPC_VarTemplate))
5819         NewVD->setInvalidDecl();
5820 
5821       // If we are providing an explicit specialization of a static variable
5822       // template, make a note of that.
5823       if (PrevVarTemplate &&
5824           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5825         PrevVarTemplate->setMemberSpecialization();
5826     }
5827   }
5828 
5829   ProcessPragmaWeak(S, NewVD);
5830 
5831   // If this is the first declaration of an extern C variable, update
5832   // the map of such variables.
5833   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5834       isIncompleteDeclExternC(*this, NewVD))
5835     RegisterLocallyScopedExternCDecl(NewVD, S);
5836 
5837   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5838     Decl *ManglingContextDecl;
5839     if (MangleNumberingContext *MCtx =
5840             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5841                                           ManglingContextDecl)) {
5842       Context.setManglingNumber(
5843           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5844       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5845     }
5846   }
5847 
5848   if (D.isRedeclaration() && !Previous.empty()) {
5849     checkDLLAttributeRedeclaration(
5850         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5851         IsExplicitSpecialization);
5852   }
5853 
5854   if (NewTemplate) {
5855     if (NewVD->isInvalidDecl())
5856       NewTemplate->setInvalidDecl();
5857     ActOnDocumentableDecl(NewTemplate);
5858     return NewTemplate;
5859   }
5860 
5861   return NewVD;
5862 }
5863 
5864 /// \brief Diagnose variable or built-in function shadowing.  Implements
5865 /// -Wshadow.
5866 ///
5867 /// This method is called whenever a VarDecl is added to a "useful"
5868 /// scope.
5869 ///
5870 /// \param S the scope in which the shadowing name is being declared
5871 /// \param R the lookup of the name
5872 ///
5873 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5874   // Return if warning is ignored.
5875   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5876     return;
5877 
5878   // Don't diagnose declarations at file scope.
5879   if (D->hasGlobalStorage())
5880     return;
5881 
5882   DeclContext *NewDC = D->getDeclContext();
5883 
5884   // Only diagnose if we're shadowing an unambiguous field or variable.
5885   if (R.getResultKind() != LookupResult::Found)
5886     return;
5887 
5888   NamedDecl* ShadowedDecl = R.getFoundDecl();
5889   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5890     return;
5891 
5892   // Fields are not shadowed by variables in C++ static methods.
5893   if (isa<FieldDecl>(ShadowedDecl))
5894     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5895       if (MD->isStatic())
5896         return;
5897 
5898   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5899     if (shadowedVar->isExternC()) {
5900       // For shadowing external vars, make sure that we point to the global
5901       // declaration, not a locally scoped extern declaration.
5902       for (auto I : shadowedVar->redecls())
5903         if (I->isFileVarDecl()) {
5904           ShadowedDecl = I;
5905           break;
5906         }
5907     }
5908 
5909   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5910 
5911   // Only warn about certain kinds of shadowing for class members.
5912   if (NewDC && NewDC->isRecord()) {
5913     // In particular, don't warn about shadowing non-class members.
5914     if (!OldDC->isRecord())
5915       return;
5916 
5917     // TODO: should we warn about static data members shadowing
5918     // static data members from base classes?
5919 
5920     // TODO: don't diagnose for inaccessible shadowed members.
5921     // This is hard to do perfectly because we might friend the
5922     // shadowing context, but that's just a false negative.
5923   }
5924 
5925   // Determine what kind of declaration we're shadowing.
5926   unsigned Kind;
5927   if (isa<RecordDecl>(OldDC)) {
5928     if (isa<FieldDecl>(ShadowedDecl))
5929       Kind = 3; // field
5930     else
5931       Kind = 2; // static data member
5932   } else if (OldDC->isFileContext())
5933     Kind = 1; // global
5934   else
5935     Kind = 0; // local
5936 
5937   DeclarationName Name = R.getLookupName();
5938 
5939   // Emit warning and note.
5940   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5941     return;
5942   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5943   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5944 }
5945 
5946 /// \brief Check -Wshadow without the advantage of a previous lookup.
5947 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5948   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5949     return;
5950 
5951   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5952                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5953   LookupName(R, S);
5954   CheckShadow(S, D, R);
5955 }
5956 
5957 /// Check for conflict between this global or extern "C" declaration and
5958 /// previous global or extern "C" declarations. This is only used in C++.
5959 template<typename T>
5960 static bool checkGlobalOrExternCConflict(
5961     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5962   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5963   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5964 
5965   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5966     // The common case: this global doesn't conflict with any extern "C"
5967     // declaration.
5968     return false;
5969   }
5970 
5971   if (Prev) {
5972     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5973       // Both the old and new declarations have C language linkage. This is a
5974       // redeclaration.
5975       Previous.clear();
5976       Previous.addDecl(Prev);
5977       return true;
5978     }
5979 
5980     // This is a global, non-extern "C" declaration, and there is a previous
5981     // non-global extern "C" declaration. Diagnose if this is a variable
5982     // declaration.
5983     if (!isa<VarDecl>(ND))
5984       return false;
5985   } else {
5986     // The declaration is extern "C". Check for any declaration in the
5987     // translation unit which might conflict.
5988     if (IsGlobal) {
5989       // We have already performed the lookup into the translation unit.
5990       IsGlobal = false;
5991       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5992            I != E; ++I) {
5993         if (isa<VarDecl>(*I)) {
5994           Prev = *I;
5995           break;
5996         }
5997       }
5998     } else {
5999       DeclContext::lookup_result R =
6000           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6001       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6002            I != E; ++I) {
6003         if (isa<VarDecl>(*I)) {
6004           Prev = *I;
6005           break;
6006         }
6007         // FIXME: If we have any other entity with this name in global scope,
6008         // the declaration is ill-formed, but that is a defect: it breaks the
6009         // 'stat' hack, for instance. Only variables can have mangled name
6010         // clashes with extern "C" declarations, so only they deserve a
6011         // diagnostic.
6012       }
6013     }
6014 
6015     if (!Prev)
6016       return false;
6017   }
6018 
6019   // Use the first declaration's location to ensure we point at something which
6020   // is lexically inside an extern "C" linkage-spec.
6021   assert(Prev && "should have found a previous declaration to diagnose");
6022   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6023     Prev = FD->getFirstDecl();
6024   else
6025     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6026 
6027   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6028     << IsGlobal << ND;
6029   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6030     << IsGlobal;
6031   return false;
6032 }
6033 
6034 /// Apply special rules for handling extern "C" declarations. Returns \c true
6035 /// if we have found that this is a redeclaration of some prior entity.
6036 ///
6037 /// Per C++ [dcl.link]p6:
6038 ///   Two declarations [for a function or variable] with C language linkage
6039 ///   with the same name that appear in different scopes refer to the same
6040 ///   [entity]. An entity with C language linkage shall not be declared with
6041 ///   the same name as an entity in global scope.
6042 template<typename T>
6043 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6044                                                   LookupResult &Previous) {
6045   if (!S.getLangOpts().CPlusPlus) {
6046     // In C, when declaring a global variable, look for a corresponding 'extern'
6047     // variable declared in function scope. We don't need this in C++, because
6048     // we find local extern decls in the surrounding file-scope DeclContext.
6049     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6050       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6051         Previous.clear();
6052         Previous.addDecl(Prev);
6053         return true;
6054       }
6055     }
6056     return false;
6057   }
6058 
6059   // A declaration in the translation unit can conflict with an extern "C"
6060   // declaration.
6061   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6062     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6063 
6064   // An extern "C" declaration can conflict with a declaration in the
6065   // translation unit or can be a redeclaration of an extern "C" declaration
6066   // in another scope.
6067   if (isIncompleteDeclExternC(S,ND))
6068     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6069 
6070   // Neither global nor extern "C": nothing to do.
6071   return false;
6072 }
6073 
6074 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6075   // If the decl is already known invalid, don't check it.
6076   if (NewVD->isInvalidDecl())
6077     return;
6078 
6079   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6080   QualType T = TInfo->getType();
6081 
6082   // Defer checking an 'auto' type until its initializer is attached.
6083   if (T->isUndeducedType())
6084     return;
6085 
6086   if (NewVD->hasAttrs())
6087     CheckAlignasUnderalignment(NewVD);
6088 
6089   if (T->isObjCObjectType()) {
6090     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6091       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6092     T = Context.getObjCObjectPointerType(T);
6093     NewVD->setType(T);
6094   }
6095 
6096   // Emit an error if an address space was applied to decl with local storage.
6097   // This includes arrays of objects with address space qualifiers, but not
6098   // automatic variables that point to other address spaces.
6099   // ISO/IEC TR 18037 S5.1.2
6100   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6101     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6102     NewVD->setInvalidDecl();
6103     return;
6104   }
6105 
6106   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6107   // __constant address space.
6108   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6109       && T.getAddressSpace() != LangAS::opencl_constant
6110       && !T->isSamplerT()){
6111     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6112     NewVD->setInvalidDecl();
6113     return;
6114   }
6115 
6116   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6117   // scope.
6118   if ((getLangOpts().OpenCLVersion >= 120)
6119       && NewVD->isStaticLocal()) {
6120     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6121     NewVD->setInvalidDecl();
6122     return;
6123   }
6124 
6125   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6126       && !NewVD->hasAttr<BlocksAttr>()) {
6127     if (getLangOpts().getGC() != LangOptions::NonGC)
6128       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6129     else {
6130       assert(!getLangOpts().ObjCAutoRefCount);
6131       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6132     }
6133   }
6134 
6135   bool isVM = T->isVariablyModifiedType();
6136   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6137       NewVD->hasAttr<BlocksAttr>())
6138     getCurFunction()->setHasBranchProtectedScope();
6139 
6140   if ((isVM && NewVD->hasLinkage()) ||
6141       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6142     bool SizeIsNegative;
6143     llvm::APSInt Oversized;
6144     TypeSourceInfo *FixedTInfo =
6145       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6146                                                     SizeIsNegative, Oversized);
6147     if (!FixedTInfo && T->isVariableArrayType()) {
6148       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6149       // FIXME: This won't give the correct result for
6150       // int a[10][n];
6151       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6152 
6153       if (NewVD->isFileVarDecl())
6154         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6155         << SizeRange;
6156       else if (NewVD->isStaticLocal())
6157         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6158         << SizeRange;
6159       else
6160         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6161         << SizeRange;
6162       NewVD->setInvalidDecl();
6163       return;
6164     }
6165 
6166     if (!FixedTInfo) {
6167       if (NewVD->isFileVarDecl())
6168         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6169       else
6170         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6171       NewVD->setInvalidDecl();
6172       return;
6173     }
6174 
6175     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6176     NewVD->setType(FixedTInfo->getType());
6177     NewVD->setTypeSourceInfo(FixedTInfo);
6178   }
6179 
6180   if (T->isVoidType()) {
6181     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6182     //                    of objects and functions.
6183     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6184       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6185         << T;
6186       NewVD->setInvalidDecl();
6187       return;
6188     }
6189   }
6190 
6191   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6192     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6193     NewVD->setInvalidDecl();
6194     return;
6195   }
6196 
6197   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6198     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6199     NewVD->setInvalidDecl();
6200     return;
6201   }
6202 
6203   if (NewVD->isConstexpr() && !T->isDependentType() &&
6204       RequireLiteralType(NewVD->getLocation(), T,
6205                          diag::err_constexpr_var_non_literal)) {
6206     NewVD->setInvalidDecl();
6207     return;
6208   }
6209 }
6210 
6211 /// \brief Perform semantic checking on a newly-created variable
6212 /// declaration.
6213 ///
6214 /// This routine performs all of the type-checking required for a
6215 /// variable declaration once it has been built. It is used both to
6216 /// check variables after they have been parsed and their declarators
6217 /// have been translated into a declaration, and to check variables
6218 /// that have been instantiated from a template.
6219 ///
6220 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6221 ///
6222 /// Returns true if the variable declaration is a redeclaration.
6223 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6224   CheckVariableDeclarationType(NewVD);
6225 
6226   // If the decl is already known invalid, don't check it.
6227   if (NewVD->isInvalidDecl())
6228     return false;
6229 
6230   // If we did not find anything by this name, look for a non-visible
6231   // extern "C" declaration with the same name.
6232   if (Previous.empty() &&
6233       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6234     Previous.setShadowed();
6235 
6236   // Filter out any non-conflicting previous declarations.
6237   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6238 
6239   if (!Previous.empty()) {
6240     MergeVarDecl(NewVD, Previous);
6241     return true;
6242   }
6243   return false;
6244 }
6245 
6246 /// \brief Data used with FindOverriddenMethod
6247 struct FindOverriddenMethodData {
6248   Sema *S;
6249   CXXMethodDecl *Method;
6250 };
6251 
6252 /// \brief Member lookup function that determines whether a given C++
6253 /// method overrides a method in a base class, to be used with
6254 /// CXXRecordDecl::lookupInBases().
6255 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6256                                  CXXBasePath &Path,
6257                                  void *UserData) {
6258   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6259 
6260   FindOverriddenMethodData *Data
6261     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6262 
6263   DeclarationName Name = Data->Method->getDeclName();
6264 
6265   // FIXME: Do we care about other names here too?
6266   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6267     // We really want to find the base class destructor here.
6268     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6269     CanQualType CT = Data->S->Context.getCanonicalType(T);
6270 
6271     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6272   }
6273 
6274   for (Path.Decls = BaseRecord->lookup(Name);
6275        !Path.Decls.empty();
6276        Path.Decls = Path.Decls.slice(1)) {
6277     NamedDecl *D = Path.Decls.front();
6278     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6279       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6280         return true;
6281     }
6282   }
6283 
6284   return false;
6285 }
6286 
6287 namespace {
6288   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6289 }
6290 /// \brief Report an error regarding overriding, along with any relevant
6291 /// overriden methods.
6292 ///
6293 /// \param DiagID the primary error to report.
6294 /// \param MD the overriding method.
6295 /// \param OEK which overrides to include as notes.
6296 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6297                             OverrideErrorKind OEK = OEK_All) {
6298   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6299   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6300                                       E = MD->end_overridden_methods();
6301        I != E; ++I) {
6302     // This check (& the OEK parameter) could be replaced by a predicate, but
6303     // without lambdas that would be overkill. This is still nicer than writing
6304     // out the diag loop 3 times.
6305     if ((OEK == OEK_All) ||
6306         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6307         (OEK == OEK_Deleted && (*I)->isDeleted()))
6308       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6309   }
6310 }
6311 
6312 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6313 /// and if so, check that it's a valid override and remember it.
6314 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6315   // Look for methods in base classes that this method might override.
6316   CXXBasePaths Paths;
6317   FindOverriddenMethodData Data;
6318   Data.Method = MD;
6319   Data.S = this;
6320   bool hasDeletedOverridenMethods = false;
6321   bool hasNonDeletedOverridenMethods = false;
6322   bool AddedAny = false;
6323   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6324     for (auto *I : Paths.found_decls()) {
6325       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6326         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6327         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6328             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6329             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6330             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6331           hasDeletedOverridenMethods |= OldMD->isDeleted();
6332           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6333           AddedAny = true;
6334         }
6335       }
6336     }
6337   }
6338 
6339   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6340     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6341   }
6342   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6343     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6344   }
6345 
6346   return AddedAny;
6347 }
6348 
6349 namespace {
6350   // Struct for holding all of the extra arguments needed by
6351   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6352   struct ActOnFDArgs {
6353     Scope *S;
6354     Declarator &D;
6355     MultiTemplateParamsArg TemplateParamLists;
6356     bool AddToScope;
6357   };
6358 }
6359 
6360 namespace {
6361 
6362 // Callback to only accept typo corrections that have a non-zero edit distance.
6363 // Also only accept corrections that have the same parent decl.
6364 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6365  public:
6366   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6367                             CXXRecordDecl *Parent)
6368       : Context(Context), OriginalFD(TypoFD),
6369         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6370 
6371   bool ValidateCandidate(const TypoCorrection &candidate) override {
6372     if (candidate.getEditDistance() == 0)
6373       return false;
6374 
6375     SmallVector<unsigned, 1> MismatchedParams;
6376     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6377                                           CDeclEnd = candidate.end();
6378          CDecl != CDeclEnd; ++CDecl) {
6379       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6380 
6381       if (FD && !FD->hasBody() &&
6382           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6383         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6384           CXXRecordDecl *Parent = MD->getParent();
6385           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6386             return true;
6387         } else if (!ExpectedParent) {
6388           return true;
6389         }
6390       }
6391     }
6392 
6393     return false;
6394   }
6395 
6396  private:
6397   ASTContext &Context;
6398   FunctionDecl *OriginalFD;
6399   CXXRecordDecl *ExpectedParent;
6400 };
6401 
6402 }
6403 
6404 /// \brief Generate diagnostics for an invalid function redeclaration.
6405 ///
6406 /// This routine handles generating the diagnostic messages for an invalid
6407 /// function redeclaration, including finding possible similar declarations
6408 /// or performing typo correction if there are no previous declarations with
6409 /// the same name.
6410 ///
6411 /// Returns a NamedDecl iff typo correction was performed and substituting in
6412 /// the new declaration name does not cause new errors.
6413 static NamedDecl *DiagnoseInvalidRedeclaration(
6414     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6415     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6416   DeclarationName Name = NewFD->getDeclName();
6417   DeclContext *NewDC = NewFD->getDeclContext();
6418   SmallVector<unsigned, 1> MismatchedParams;
6419   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6420   TypoCorrection Correction;
6421   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6422   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6423                                    : diag::err_member_decl_does_not_match;
6424   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6425                     IsLocalFriend ? Sema::LookupLocalFriendName
6426                                   : Sema::LookupOrdinaryName,
6427                     Sema::ForRedeclaration);
6428 
6429   NewFD->setInvalidDecl();
6430   if (IsLocalFriend)
6431     SemaRef.LookupName(Prev, S);
6432   else
6433     SemaRef.LookupQualifiedName(Prev, NewDC);
6434   assert(!Prev.isAmbiguous() &&
6435          "Cannot have an ambiguity in previous-declaration lookup");
6436   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6437   if (!Prev.empty()) {
6438     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6439          Func != FuncEnd; ++Func) {
6440       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6441       if (FD &&
6442           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6443         // Add 1 to the index so that 0 can mean the mismatch didn't
6444         // involve a parameter
6445         unsigned ParamNum =
6446             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6447         NearMatches.push_back(std::make_pair(FD, ParamNum));
6448       }
6449     }
6450   // If the qualified name lookup yielded nothing, try typo correction
6451   } else if ((Correction = SemaRef.CorrectTypo(
6452                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6453                   &ExtraArgs.D.getCXXScopeSpec(),
6454                   llvm::make_unique<DifferentNameValidatorCCC>(
6455                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6456                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6457     // Set up everything for the call to ActOnFunctionDeclarator
6458     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6459                               ExtraArgs.D.getIdentifierLoc());
6460     Previous.clear();
6461     Previous.setLookupName(Correction.getCorrection());
6462     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6463                                     CDeclEnd = Correction.end();
6464          CDecl != CDeclEnd; ++CDecl) {
6465       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6466       if (FD && !FD->hasBody() &&
6467           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6468         Previous.addDecl(FD);
6469       }
6470     }
6471     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6472 
6473     NamedDecl *Result;
6474     // Retry building the function declaration with the new previous
6475     // declarations, and with errors suppressed.
6476     {
6477       // Trap errors.
6478       Sema::SFINAETrap Trap(SemaRef);
6479 
6480       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6481       // pieces need to verify the typo-corrected C++ declaration and hopefully
6482       // eliminate the need for the parameter pack ExtraArgs.
6483       Result = SemaRef.ActOnFunctionDeclarator(
6484           ExtraArgs.S, ExtraArgs.D,
6485           Correction.getCorrectionDecl()->getDeclContext(),
6486           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6487           ExtraArgs.AddToScope);
6488 
6489       if (Trap.hasErrorOccurred())
6490         Result = nullptr;
6491     }
6492 
6493     if (Result) {
6494       // Determine which correction we picked.
6495       Decl *Canonical = Result->getCanonicalDecl();
6496       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6497            I != E; ++I)
6498         if ((*I)->getCanonicalDecl() == Canonical)
6499           Correction.setCorrectionDecl(*I);
6500 
6501       SemaRef.diagnoseTypo(
6502           Correction,
6503           SemaRef.PDiag(IsLocalFriend
6504                           ? diag::err_no_matching_local_friend_suggest
6505                           : diag::err_member_decl_does_not_match_suggest)
6506             << Name << NewDC << IsDefinition);
6507       return Result;
6508     }
6509 
6510     // Pretend the typo correction never occurred
6511     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6512                               ExtraArgs.D.getIdentifierLoc());
6513     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6514     Previous.clear();
6515     Previous.setLookupName(Name);
6516   }
6517 
6518   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6519       << Name << NewDC << IsDefinition << NewFD->getLocation();
6520 
6521   bool NewFDisConst = false;
6522   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6523     NewFDisConst = NewMD->isConst();
6524 
6525   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6526        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6527        NearMatch != NearMatchEnd; ++NearMatch) {
6528     FunctionDecl *FD = NearMatch->first;
6529     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6530     bool FDisConst = MD && MD->isConst();
6531     bool IsMember = MD || !IsLocalFriend;
6532 
6533     // FIXME: These notes are poorly worded for the local friend case.
6534     if (unsigned Idx = NearMatch->second) {
6535       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6536       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6537       if (Loc.isInvalid()) Loc = FD->getLocation();
6538       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6539                                  : diag::note_local_decl_close_param_match)
6540         << Idx << FDParam->getType()
6541         << NewFD->getParamDecl(Idx - 1)->getType();
6542     } else if (FDisConst != NewFDisConst) {
6543       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6544           << NewFDisConst << FD->getSourceRange().getEnd();
6545     } else
6546       SemaRef.Diag(FD->getLocation(),
6547                    IsMember ? diag::note_member_def_close_match
6548                             : diag::note_local_decl_close_match);
6549   }
6550   return nullptr;
6551 }
6552 
6553 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6554   switch (D.getDeclSpec().getStorageClassSpec()) {
6555   default: llvm_unreachable("Unknown storage class!");
6556   case DeclSpec::SCS_auto:
6557   case DeclSpec::SCS_register:
6558   case DeclSpec::SCS_mutable:
6559     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6560                  diag::err_typecheck_sclass_func);
6561     D.setInvalidType();
6562     break;
6563   case DeclSpec::SCS_unspecified: break;
6564   case DeclSpec::SCS_extern:
6565     if (D.getDeclSpec().isExternInLinkageSpec())
6566       return SC_None;
6567     return SC_Extern;
6568   case DeclSpec::SCS_static: {
6569     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6570       // C99 6.7.1p5:
6571       //   The declaration of an identifier for a function that has
6572       //   block scope shall have no explicit storage-class specifier
6573       //   other than extern
6574       // See also (C++ [dcl.stc]p4).
6575       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6576                    diag::err_static_block_func);
6577       break;
6578     } else
6579       return SC_Static;
6580   }
6581   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6582   }
6583 
6584   // No explicit storage class has already been returned
6585   return SC_None;
6586 }
6587 
6588 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6589                                            DeclContext *DC, QualType &R,
6590                                            TypeSourceInfo *TInfo,
6591                                            StorageClass SC,
6592                                            bool &IsVirtualOkay) {
6593   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6594   DeclarationName Name = NameInfo.getName();
6595 
6596   FunctionDecl *NewFD = nullptr;
6597   bool isInline = D.getDeclSpec().isInlineSpecified();
6598 
6599   if (!SemaRef.getLangOpts().CPlusPlus) {
6600     // Determine whether the function was written with a
6601     // prototype. This true when:
6602     //   - there is a prototype in the declarator, or
6603     //   - the type R of the function is some kind of typedef or other reference
6604     //     to a type name (which eventually refers to a function type).
6605     bool HasPrototype =
6606       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6607       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6608 
6609     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6610                                  D.getLocStart(), NameInfo, R,
6611                                  TInfo, SC, isInline,
6612                                  HasPrototype, false);
6613     if (D.isInvalidType())
6614       NewFD->setInvalidDecl();
6615 
6616     // Set the lexical context.
6617     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6618 
6619     return NewFD;
6620   }
6621 
6622   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6623   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6624 
6625   // Check that the return type is not an abstract class type.
6626   // For record types, this is done by the AbstractClassUsageDiagnoser once
6627   // the class has been completely parsed.
6628   if (!DC->isRecord() &&
6629       SemaRef.RequireNonAbstractType(
6630           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6631           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6632     D.setInvalidType();
6633 
6634   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6635     // This is a C++ constructor declaration.
6636     assert(DC->isRecord() &&
6637            "Constructors can only be declared in a member context");
6638 
6639     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6640     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6641                                       D.getLocStart(), NameInfo,
6642                                       R, TInfo, isExplicit, isInline,
6643                                       /*isImplicitlyDeclared=*/false,
6644                                       isConstexpr);
6645 
6646   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6647     // This is a C++ destructor declaration.
6648     if (DC->isRecord()) {
6649       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6650       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6651       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6652                                         SemaRef.Context, Record,
6653                                         D.getLocStart(),
6654                                         NameInfo, R, TInfo, isInline,
6655                                         /*isImplicitlyDeclared=*/false);
6656 
6657       // If the class is complete, then we now create the implicit exception
6658       // specification. If the class is incomplete or dependent, we can't do
6659       // it yet.
6660       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6661           Record->getDefinition() && !Record->isBeingDefined() &&
6662           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6663         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6664       }
6665 
6666       IsVirtualOkay = true;
6667       return NewDD;
6668 
6669     } else {
6670       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6671       D.setInvalidType();
6672 
6673       // Create a FunctionDecl to satisfy the function definition parsing
6674       // code path.
6675       return FunctionDecl::Create(SemaRef.Context, DC,
6676                                   D.getLocStart(),
6677                                   D.getIdentifierLoc(), Name, R, TInfo,
6678                                   SC, isInline,
6679                                   /*hasPrototype=*/true, isConstexpr);
6680     }
6681 
6682   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6683     if (!DC->isRecord()) {
6684       SemaRef.Diag(D.getIdentifierLoc(),
6685            diag::err_conv_function_not_member);
6686       return nullptr;
6687     }
6688 
6689     SemaRef.CheckConversionDeclarator(D, R, SC);
6690     IsVirtualOkay = true;
6691     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6692                                      D.getLocStart(), NameInfo,
6693                                      R, TInfo, isInline, isExplicit,
6694                                      isConstexpr, SourceLocation());
6695 
6696   } else if (DC->isRecord()) {
6697     // If the name of the function is the same as the name of the record,
6698     // then this must be an invalid constructor that has a return type.
6699     // (The parser checks for a return type and makes the declarator a
6700     // constructor if it has no return type).
6701     if (Name.getAsIdentifierInfo() &&
6702         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6703       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6704         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6705         << SourceRange(D.getIdentifierLoc());
6706       return nullptr;
6707     }
6708 
6709     // This is a C++ method declaration.
6710     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6711                                                cast<CXXRecordDecl>(DC),
6712                                                D.getLocStart(), NameInfo, R,
6713                                                TInfo, SC, isInline,
6714                                                isConstexpr, SourceLocation());
6715     IsVirtualOkay = !Ret->isStatic();
6716     return Ret;
6717   } else {
6718     // Determine whether the function was written with a
6719     // prototype. This true when:
6720     //   - we're in C++ (where every function has a prototype),
6721     return FunctionDecl::Create(SemaRef.Context, DC,
6722                                 D.getLocStart(),
6723                                 NameInfo, R, TInfo, SC, isInline,
6724                                 true/*HasPrototype*/, isConstexpr);
6725   }
6726 }
6727 
6728 enum OpenCLParamType {
6729   ValidKernelParam,
6730   PtrPtrKernelParam,
6731   PtrKernelParam,
6732   PrivatePtrKernelParam,
6733   InvalidKernelParam,
6734   RecordKernelParam
6735 };
6736 
6737 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6738   if (PT->isPointerType()) {
6739     QualType PointeeType = PT->getPointeeType();
6740     if (PointeeType->isPointerType())
6741       return PtrPtrKernelParam;
6742     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6743                                               : PtrKernelParam;
6744   }
6745 
6746   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6747   // be used as builtin types.
6748 
6749   if (PT->isImageType())
6750     return PtrKernelParam;
6751 
6752   if (PT->isBooleanType())
6753     return InvalidKernelParam;
6754 
6755   if (PT->isEventT())
6756     return InvalidKernelParam;
6757 
6758   if (PT->isHalfType())
6759     return InvalidKernelParam;
6760 
6761   if (PT->isRecordType())
6762     return RecordKernelParam;
6763 
6764   return ValidKernelParam;
6765 }
6766 
6767 static void checkIsValidOpenCLKernelParameter(
6768   Sema &S,
6769   Declarator &D,
6770   ParmVarDecl *Param,
6771   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6772   QualType PT = Param->getType();
6773 
6774   // Cache the valid types we encounter to avoid rechecking structs that are
6775   // used again
6776   if (ValidTypes.count(PT.getTypePtr()))
6777     return;
6778 
6779   switch (getOpenCLKernelParameterType(PT)) {
6780   case PtrPtrKernelParam:
6781     // OpenCL v1.2 s6.9.a:
6782     // A kernel function argument cannot be declared as a
6783     // pointer to a pointer type.
6784     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6785     D.setInvalidType();
6786     return;
6787 
6788   case PrivatePtrKernelParam:
6789     // OpenCL v1.2 s6.9.a:
6790     // A kernel function argument cannot be declared as a
6791     // pointer to the private address space.
6792     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6793     D.setInvalidType();
6794     return;
6795 
6796     // OpenCL v1.2 s6.9.k:
6797     // Arguments to kernel functions in a program cannot be declared with the
6798     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6799     // uintptr_t or a struct and/or union that contain fields declared to be
6800     // one of these built-in scalar types.
6801 
6802   case InvalidKernelParam:
6803     // OpenCL v1.2 s6.8 n:
6804     // A kernel function argument cannot be declared
6805     // of event_t type.
6806     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6807     D.setInvalidType();
6808     return;
6809 
6810   case PtrKernelParam:
6811   case ValidKernelParam:
6812     ValidTypes.insert(PT.getTypePtr());
6813     return;
6814 
6815   case RecordKernelParam:
6816     break;
6817   }
6818 
6819   // Track nested structs we will inspect
6820   SmallVector<const Decl *, 4> VisitStack;
6821 
6822   // Track where we are in the nested structs. Items will migrate from
6823   // VisitStack to HistoryStack as we do the DFS for bad field.
6824   SmallVector<const FieldDecl *, 4> HistoryStack;
6825   HistoryStack.push_back(nullptr);
6826 
6827   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6828   VisitStack.push_back(PD);
6829 
6830   assert(VisitStack.back() && "First decl null?");
6831 
6832   do {
6833     const Decl *Next = VisitStack.pop_back_val();
6834     if (!Next) {
6835       assert(!HistoryStack.empty());
6836       // Found a marker, we have gone up a level
6837       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6838         ValidTypes.insert(Hist->getType().getTypePtr());
6839 
6840       continue;
6841     }
6842 
6843     // Adds everything except the original parameter declaration (which is not a
6844     // field itself) to the history stack.
6845     const RecordDecl *RD;
6846     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6847       HistoryStack.push_back(Field);
6848       RD = Field->getType()->castAs<RecordType>()->getDecl();
6849     } else {
6850       RD = cast<RecordDecl>(Next);
6851     }
6852 
6853     // Add a null marker so we know when we've gone back up a level
6854     VisitStack.push_back(nullptr);
6855 
6856     for (const auto *FD : RD->fields()) {
6857       QualType QT = FD->getType();
6858 
6859       if (ValidTypes.count(QT.getTypePtr()))
6860         continue;
6861 
6862       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6863       if (ParamType == ValidKernelParam)
6864         continue;
6865 
6866       if (ParamType == RecordKernelParam) {
6867         VisitStack.push_back(FD);
6868         continue;
6869       }
6870 
6871       // OpenCL v1.2 s6.9.p:
6872       // Arguments to kernel functions that are declared to be a struct or union
6873       // do not allow OpenCL objects to be passed as elements of the struct or
6874       // union.
6875       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6876           ParamType == PrivatePtrKernelParam) {
6877         S.Diag(Param->getLocation(),
6878                diag::err_record_with_pointers_kernel_param)
6879           << PT->isUnionType()
6880           << PT;
6881       } else {
6882         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6883       }
6884 
6885       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6886         << PD->getDeclName();
6887 
6888       // We have an error, now let's go back up through history and show where
6889       // the offending field came from
6890       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6891              E = HistoryStack.end(); I != E; ++I) {
6892         const FieldDecl *OuterField = *I;
6893         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6894           << OuterField->getType();
6895       }
6896 
6897       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6898         << QT->isPointerType()
6899         << QT;
6900       D.setInvalidType();
6901       return;
6902     }
6903   } while (!VisitStack.empty());
6904 }
6905 
6906 NamedDecl*
6907 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6908                               TypeSourceInfo *TInfo, LookupResult &Previous,
6909                               MultiTemplateParamsArg TemplateParamLists,
6910                               bool &AddToScope) {
6911   QualType R = TInfo->getType();
6912 
6913   assert(R.getTypePtr()->isFunctionType());
6914 
6915   // TODO: consider using NameInfo for diagnostic.
6916   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6917   DeclarationName Name = NameInfo.getName();
6918   StorageClass SC = getFunctionStorageClass(*this, D);
6919 
6920   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6921     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6922          diag::err_invalid_thread)
6923       << DeclSpec::getSpecifierName(TSCS);
6924 
6925   if (D.isFirstDeclarationOfMember())
6926     adjustMemberFunctionCC(R, D.isStaticMember());
6927 
6928   bool isFriend = false;
6929   FunctionTemplateDecl *FunctionTemplate = nullptr;
6930   bool isExplicitSpecialization = false;
6931   bool isFunctionTemplateSpecialization = false;
6932 
6933   bool isDependentClassScopeExplicitSpecialization = false;
6934   bool HasExplicitTemplateArgs = false;
6935   TemplateArgumentListInfo TemplateArgs;
6936 
6937   bool isVirtualOkay = false;
6938 
6939   DeclContext *OriginalDC = DC;
6940   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6941 
6942   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6943                                               isVirtualOkay);
6944   if (!NewFD) return nullptr;
6945 
6946   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6947     NewFD->setTopLevelDeclInObjCContainer();
6948 
6949   // Set the lexical context. If this is a function-scope declaration, or has a
6950   // C++ scope specifier, or is the object of a friend declaration, the lexical
6951   // context will be different from the semantic context.
6952   NewFD->setLexicalDeclContext(CurContext);
6953 
6954   if (IsLocalExternDecl)
6955     NewFD->setLocalExternDecl();
6956 
6957   if (getLangOpts().CPlusPlus) {
6958     bool isInline = D.getDeclSpec().isInlineSpecified();
6959     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6960     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6961     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6962     isFriend = D.getDeclSpec().isFriendSpecified();
6963     if (isFriend && !isInline && D.isFunctionDefinition()) {
6964       // C++ [class.friend]p5
6965       //   A function can be defined in a friend declaration of a
6966       //   class . . . . Such a function is implicitly inline.
6967       NewFD->setImplicitlyInline();
6968     }
6969 
6970     // If this is a method defined in an __interface, and is not a constructor
6971     // or an overloaded operator, then set the pure flag (isVirtual will already
6972     // return true).
6973     if (const CXXRecordDecl *Parent =
6974           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6975       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6976         NewFD->setPure(true);
6977     }
6978 
6979     SetNestedNameSpecifier(NewFD, D);
6980     isExplicitSpecialization = false;
6981     isFunctionTemplateSpecialization = false;
6982     if (D.isInvalidType())
6983       NewFD->setInvalidDecl();
6984 
6985     // Match up the template parameter lists with the scope specifier, then
6986     // determine whether we have a template or a template specialization.
6987     bool Invalid = false;
6988     if (TemplateParameterList *TemplateParams =
6989             MatchTemplateParametersToScopeSpecifier(
6990                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6991                 D.getCXXScopeSpec(),
6992                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6993                     ? D.getName().TemplateId
6994                     : nullptr,
6995                 TemplateParamLists, isFriend, isExplicitSpecialization,
6996                 Invalid)) {
6997       if (TemplateParams->size() > 0) {
6998         // This is a function template
6999 
7000         // Check that we can declare a template here.
7001         if (CheckTemplateDeclScope(S, TemplateParams))
7002           return nullptr;
7003 
7004         // A destructor cannot be a template.
7005         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7006           Diag(NewFD->getLocation(), diag::err_destructor_template);
7007           return nullptr;
7008         }
7009 
7010         // If we're adding a template to a dependent context, we may need to
7011         // rebuilding some of the types used within the template parameter list,
7012         // now that we know what the current instantiation is.
7013         if (DC->isDependentContext()) {
7014           ContextRAII SavedContext(*this, DC);
7015           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7016             Invalid = true;
7017         }
7018 
7019 
7020         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7021                                                         NewFD->getLocation(),
7022                                                         Name, TemplateParams,
7023                                                         NewFD);
7024         FunctionTemplate->setLexicalDeclContext(CurContext);
7025         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7026 
7027         // For source fidelity, store the other template param lists.
7028         if (TemplateParamLists.size() > 1) {
7029           NewFD->setTemplateParameterListsInfo(Context,
7030                                                TemplateParamLists.size() - 1,
7031                                                TemplateParamLists.data());
7032         }
7033       } else {
7034         // This is a function template specialization.
7035         isFunctionTemplateSpecialization = true;
7036         // For source fidelity, store all the template param lists.
7037         if (TemplateParamLists.size() > 0)
7038           NewFD->setTemplateParameterListsInfo(Context,
7039                                                TemplateParamLists.size(),
7040                                                TemplateParamLists.data());
7041 
7042         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7043         if (isFriend) {
7044           // We want to remove the "template<>", found here.
7045           SourceRange RemoveRange = TemplateParams->getSourceRange();
7046 
7047           // If we remove the template<> and the name is not a
7048           // template-id, we're actually silently creating a problem:
7049           // the friend declaration will refer to an untemplated decl,
7050           // and clearly the user wants a template specialization.  So
7051           // we need to insert '<>' after the name.
7052           SourceLocation InsertLoc;
7053           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7054             InsertLoc = D.getName().getSourceRange().getEnd();
7055             InsertLoc = getLocForEndOfToken(InsertLoc);
7056           }
7057 
7058           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7059             << Name << RemoveRange
7060             << FixItHint::CreateRemoval(RemoveRange)
7061             << FixItHint::CreateInsertion(InsertLoc, "<>");
7062         }
7063       }
7064     }
7065     else {
7066       // All template param lists were matched against the scope specifier:
7067       // this is NOT (an explicit specialization of) a template.
7068       if (TemplateParamLists.size() > 0)
7069         // For source fidelity, store all the template param lists.
7070         NewFD->setTemplateParameterListsInfo(Context,
7071                                              TemplateParamLists.size(),
7072                                              TemplateParamLists.data());
7073     }
7074 
7075     if (Invalid) {
7076       NewFD->setInvalidDecl();
7077       if (FunctionTemplate)
7078         FunctionTemplate->setInvalidDecl();
7079     }
7080 
7081     // C++ [dcl.fct.spec]p5:
7082     //   The virtual specifier shall only be used in declarations of
7083     //   nonstatic class member functions that appear within a
7084     //   member-specification of a class declaration; see 10.3.
7085     //
7086     if (isVirtual && !NewFD->isInvalidDecl()) {
7087       if (!isVirtualOkay) {
7088         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7089              diag::err_virtual_non_function);
7090       } else if (!CurContext->isRecord()) {
7091         // 'virtual' was specified outside of the class.
7092         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7093              diag::err_virtual_out_of_class)
7094           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7095       } else if (NewFD->getDescribedFunctionTemplate()) {
7096         // C++ [temp.mem]p3:
7097         //  A member function template shall not be virtual.
7098         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7099              diag::err_virtual_member_function_template)
7100           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7101       } else {
7102         // Okay: Add virtual to the method.
7103         NewFD->setVirtualAsWritten(true);
7104       }
7105 
7106       if (getLangOpts().CPlusPlus14 &&
7107           NewFD->getReturnType()->isUndeducedType())
7108         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7109     }
7110 
7111     if (getLangOpts().CPlusPlus14 &&
7112         (NewFD->isDependentContext() ||
7113          (isFriend && CurContext->isDependentContext())) &&
7114         NewFD->getReturnType()->isUndeducedType()) {
7115       // If the function template is referenced directly (for instance, as a
7116       // member of the current instantiation), pretend it has a dependent type.
7117       // This is not really justified by the standard, but is the only sane
7118       // thing to do.
7119       // FIXME: For a friend function, we have not marked the function as being
7120       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7121       const FunctionProtoType *FPT =
7122           NewFD->getType()->castAs<FunctionProtoType>();
7123       QualType Result =
7124           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7125       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7126                                              FPT->getExtProtoInfo()));
7127     }
7128 
7129     // C++ [dcl.fct.spec]p3:
7130     //  The inline specifier shall not appear on a block scope function
7131     //  declaration.
7132     if (isInline && !NewFD->isInvalidDecl()) {
7133       if (CurContext->isFunctionOrMethod()) {
7134         // 'inline' is not allowed on block scope function declaration.
7135         Diag(D.getDeclSpec().getInlineSpecLoc(),
7136              diag::err_inline_declaration_block_scope) << Name
7137           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7138       }
7139     }
7140 
7141     // C++ [dcl.fct.spec]p6:
7142     //  The explicit specifier shall be used only in the declaration of a
7143     //  constructor or conversion function within its class definition;
7144     //  see 12.3.1 and 12.3.2.
7145     if (isExplicit && !NewFD->isInvalidDecl()) {
7146       if (!CurContext->isRecord()) {
7147         // 'explicit' was specified outside of the class.
7148         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7149              diag::err_explicit_out_of_class)
7150           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7151       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7152                  !isa<CXXConversionDecl>(NewFD)) {
7153         // 'explicit' was specified on a function that wasn't a constructor
7154         // or conversion function.
7155         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7156              diag::err_explicit_non_ctor_or_conv_function)
7157           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7158       }
7159     }
7160 
7161     if (isConstexpr) {
7162       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7163       // are implicitly inline.
7164       NewFD->setImplicitlyInline();
7165 
7166       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7167       // be either constructors or to return a literal type. Therefore,
7168       // destructors cannot be declared constexpr.
7169       if (isa<CXXDestructorDecl>(NewFD))
7170         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7171     }
7172 
7173     // If __module_private__ was specified, mark the function accordingly.
7174     if (D.getDeclSpec().isModulePrivateSpecified()) {
7175       if (isFunctionTemplateSpecialization) {
7176         SourceLocation ModulePrivateLoc
7177           = D.getDeclSpec().getModulePrivateSpecLoc();
7178         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7179           << 0
7180           << FixItHint::CreateRemoval(ModulePrivateLoc);
7181       } else {
7182         NewFD->setModulePrivate();
7183         if (FunctionTemplate)
7184           FunctionTemplate->setModulePrivate();
7185       }
7186     }
7187 
7188     if (isFriend) {
7189       if (FunctionTemplate) {
7190         FunctionTemplate->setObjectOfFriendDecl();
7191         FunctionTemplate->setAccess(AS_public);
7192       }
7193       NewFD->setObjectOfFriendDecl();
7194       NewFD->setAccess(AS_public);
7195     }
7196 
7197     // If a function is defined as defaulted or deleted, mark it as such now.
7198     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7199     // definition kind to FDK_Definition.
7200     switch (D.getFunctionDefinitionKind()) {
7201       case FDK_Declaration:
7202       case FDK_Definition:
7203         break;
7204 
7205       case FDK_Defaulted:
7206         NewFD->setDefaulted();
7207         break;
7208 
7209       case FDK_Deleted:
7210         NewFD->setDeletedAsWritten();
7211         break;
7212     }
7213 
7214     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7215         D.isFunctionDefinition()) {
7216       // C++ [class.mfct]p2:
7217       //   A member function may be defined (8.4) in its class definition, in
7218       //   which case it is an inline member function (7.1.2)
7219       NewFD->setImplicitlyInline();
7220     }
7221 
7222     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7223         !CurContext->isRecord()) {
7224       // C++ [class.static]p1:
7225       //   A data or function member of a class may be declared static
7226       //   in a class definition, in which case it is a static member of
7227       //   the class.
7228 
7229       // Complain about the 'static' specifier if it's on an out-of-line
7230       // member function definition.
7231       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7232            diag::err_static_out_of_line)
7233         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7234     }
7235 
7236     // C++11 [except.spec]p15:
7237     //   A deallocation function with no exception-specification is treated
7238     //   as if it were specified with noexcept(true).
7239     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7240     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7241          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7242         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7243       NewFD->setType(Context.getFunctionType(
7244           FPT->getReturnType(), FPT->getParamTypes(),
7245           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7246   }
7247 
7248   // Filter out previous declarations that don't match the scope.
7249   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7250                        D.getCXXScopeSpec().isNotEmpty() ||
7251                        isExplicitSpecialization ||
7252                        isFunctionTemplateSpecialization);
7253 
7254   // Handle GNU asm-label extension (encoded as an attribute).
7255   if (Expr *E = (Expr*) D.getAsmLabel()) {
7256     // The parser guarantees this is a string.
7257     StringLiteral *SE = cast<StringLiteral>(E);
7258     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7259                                                 SE->getString(), 0));
7260   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7261     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7262       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7263     if (I != ExtnameUndeclaredIdentifiers.end()) {
7264       NewFD->addAttr(I->second);
7265       ExtnameUndeclaredIdentifiers.erase(I);
7266     }
7267   }
7268 
7269   // Copy the parameter declarations from the declarator D to the function
7270   // declaration NewFD, if they are available.  First scavenge them into Params.
7271   SmallVector<ParmVarDecl*, 16> Params;
7272   if (D.isFunctionDeclarator()) {
7273     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7274 
7275     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7276     // function that takes no arguments, not a function that takes a
7277     // single void argument.
7278     // We let through "const void" here because Sema::GetTypeForDeclarator
7279     // already checks for that case.
7280     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7281       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7282         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7283         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7284         Param->setDeclContext(NewFD);
7285         Params.push_back(Param);
7286 
7287         if (Param->isInvalidDecl())
7288           NewFD->setInvalidDecl();
7289       }
7290     }
7291 
7292   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7293     // When we're declaring a function with a typedef, typeof, etc as in the
7294     // following example, we'll need to synthesize (unnamed)
7295     // parameters for use in the declaration.
7296     //
7297     // @code
7298     // typedef void fn(int);
7299     // fn f;
7300     // @endcode
7301 
7302     // Synthesize a parameter for each argument type.
7303     for (const auto &AI : FT->param_types()) {
7304       ParmVarDecl *Param =
7305           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7306       Param->setScopeInfo(0, Params.size());
7307       Params.push_back(Param);
7308     }
7309   } else {
7310     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7311            "Should not need args for typedef of non-prototype fn");
7312   }
7313 
7314   // Finally, we know we have the right number of parameters, install them.
7315   NewFD->setParams(Params);
7316 
7317   // Find all anonymous symbols defined during the declaration of this function
7318   // and add to NewFD. This lets us track decls such 'enum Y' in:
7319   //
7320   //   void f(enum Y {AA} x) {}
7321   //
7322   // which would otherwise incorrectly end up in the translation unit scope.
7323   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7324   DeclsInPrototypeScope.clear();
7325 
7326   if (D.getDeclSpec().isNoreturnSpecified())
7327     NewFD->addAttr(
7328         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7329                                        Context, 0));
7330 
7331   // Functions returning a variably modified type violate C99 6.7.5.2p2
7332   // because all functions have linkage.
7333   if (!NewFD->isInvalidDecl() &&
7334       NewFD->getReturnType()->isVariablyModifiedType()) {
7335     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7336     NewFD->setInvalidDecl();
7337   }
7338 
7339   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7340       !NewFD->hasAttr<SectionAttr>()) {
7341     NewFD->addAttr(
7342         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7343                                     CodeSegStack.CurrentValue->getString(),
7344                                     CodeSegStack.CurrentPragmaLocation));
7345     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7346                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7347                          ASTContext::PSF_Read,
7348                      NewFD))
7349       NewFD->dropAttr<SectionAttr>();
7350   }
7351 
7352   // Handle attributes.
7353   ProcessDeclAttributes(S, NewFD, D);
7354 
7355   QualType RetType = NewFD->getReturnType();
7356   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7357       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7358   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7359       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7360     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7361     // Attach WarnUnusedResult to functions returning types with that attribute.
7362     // Don't apply the attribute to that type's own non-static member functions
7363     // (to avoid warning on things like assignment operators)
7364     if (!MD || MD->getParent() != Ret)
7365       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7366   }
7367 
7368   if (getLangOpts().OpenCL) {
7369     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7370     // type declaration will generate a compilation error.
7371     unsigned AddressSpace = RetType.getAddressSpace();
7372     if (AddressSpace == LangAS::opencl_local ||
7373         AddressSpace == LangAS::opencl_global ||
7374         AddressSpace == LangAS::opencl_constant) {
7375       Diag(NewFD->getLocation(),
7376            diag::err_opencl_return_value_with_address_space);
7377       NewFD->setInvalidDecl();
7378     }
7379   }
7380 
7381   if (!getLangOpts().CPlusPlus) {
7382     // Perform semantic checking on the function declaration.
7383     bool isExplicitSpecialization=false;
7384     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7385       CheckMain(NewFD, D.getDeclSpec());
7386 
7387     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7388       CheckMSVCRTEntryPoint(NewFD);
7389 
7390     if (!NewFD->isInvalidDecl())
7391       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7392                                                   isExplicitSpecialization));
7393     else if (!Previous.empty())
7394       // Make graceful recovery from an invalid redeclaration.
7395       D.setRedeclaration(true);
7396     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7397             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7398            "previous declaration set still overloaded");
7399 
7400     // Diagnose no-prototype function declarations with calling conventions that
7401     // don't support variadic calls. Only do this in C and do it after merging
7402     // possibly prototyped redeclarations.
7403     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7404     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7405       CallingConv CC = FT->getExtInfo().getCC();
7406       if (!supportsVariadicCall(CC)) {
7407         // Windows system headers sometimes accidentally use stdcall without
7408         // (void) parameters, so we relax this to a warning.
7409         int DiagID =
7410             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7411         Diag(NewFD->getLocation(), DiagID)
7412             << FunctionType::getNameForCallConv(CC);
7413       }
7414     }
7415   } else {
7416     // C++11 [replacement.functions]p3:
7417     //  The program's definitions shall not be specified as inline.
7418     //
7419     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7420     //
7421     // Suppress the diagnostic if the function is __attribute__((used)), since
7422     // that forces an external definition to be emitted.
7423     if (D.getDeclSpec().isInlineSpecified() &&
7424         NewFD->isReplaceableGlobalAllocationFunction() &&
7425         !NewFD->hasAttr<UsedAttr>())
7426       Diag(D.getDeclSpec().getInlineSpecLoc(),
7427            diag::ext_operator_new_delete_declared_inline)
7428         << NewFD->getDeclName();
7429 
7430     // If the declarator is a template-id, translate the parser's template
7431     // argument list into our AST format.
7432     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7433       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7434       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7435       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7436       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7437                                          TemplateId->NumArgs);
7438       translateTemplateArguments(TemplateArgsPtr,
7439                                  TemplateArgs);
7440 
7441       HasExplicitTemplateArgs = true;
7442 
7443       if (NewFD->isInvalidDecl()) {
7444         HasExplicitTemplateArgs = false;
7445       } else if (FunctionTemplate) {
7446         // Function template with explicit template arguments.
7447         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7448           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7449 
7450         HasExplicitTemplateArgs = false;
7451       } else {
7452         assert((isFunctionTemplateSpecialization ||
7453                 D.getDeclSpec().isFriendSpecified()) &&
7454                "should have a 'template<>' for this decl");
7455         // "friend void foo<>(int);" is an implicit specialization decl.
7456         isFunctionTemplateSpecialization = true;
7457       }
7458     } else if (isFriend && isFunctionTemplateSpecialization) {
7459       // This combination is only possible in a recovery case;  the user
7460       // wrote something like:
7461       //   template <> friend void foo(int);
7462       // which we're recovering from as if the user had written:
7463       //   friend void foo<>(int);
7464       // Go ahead and fake up a template id.
7465       HasExplicitTemplateArgs = true;
7466       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7467       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7468     }
7469 
7470     // If it's a friend (and only if it's a friend), it's possible
7471     // that either the specialized function type or the specialized
7472     // template is dependent, and therefore matching will fail.  In
7473     // this case, don't check the specialization yet.
7474     bool InstantiationDependent = false;
7475     if (isFunctionTemplateSpecialization && isFriend &&
7476         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7477          TemplateSpecializationType::anyDependentTemplateArguments(
7478             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7479             InstantiationDependent))) {
7480       assert(HasExplicitTemplateArgs &&
7481              "friend function specialization without template args");
7482       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7483                                                        Previous))
7484         NewFD->setInvalidDecl();
7485     } else if (isFunctionTemplateSpecialization) {
7486       if (CurContext->isDependentContext() && CurContext->isRecord()
7487           && !isFriend) {
7488         isDependentClassScopeExplicitSpecialization = true;
7489         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7490           diag::ext_function_specialization_in_class :
7491           diag::err_function_specialization_in_class)
7492           << NewFD->getDeclName();
7493       } else if (CheckFunctionTemplateSpecialization(NewFD,
7494                                   (HasExplicitTemplateArgs ? &TemplateArgs
7495                                                            : nullptr),
7496                                                      Previous))
7497         NewFD->setInvalidDecl();
7498 
7499       // C++ [dcl.stc]p1:
7500       //   A storage-class-specifier shall not be specified in an explicit
7501       //   specialization (14.7.3)
7502       FunctionTemplateSpecializationInfo *Info =
7503           NewFD->getTemplateSpecializationInfo();
7504       if (Info && SC != SC_None) {
7505         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7506           Diag(NewFD->getLocation(),
7507                diag::err_explicit_specialization_inconsistent_storage_class)
7508             << SC
7509             << FixItHint::CreateRemoval(
7510                                       D.getDeclSpec().getStorageClassSpecLoc());
7511 
7512         else
7513           Diag(NewFD->getLocation(),
7514                diag::ext_explicit_specialization_storage_class)
7515             << FixItHint::CreateRemoval(
7516                                       D.getDeclSpec().getStorageClassSpecLoc());
7517       }
7518 
7519     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7520       if (CheckMemberSpecialization(NewFD, Previous))
7521           NewFD->setInvalidDecl();
7522     }
7523 
7524     // Perform semantic checking on the function declaration.
7525     if (!isDependentClassScopeExplicitSpecialization) {
7526       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7527         CheckMain(NewFD, D.getDeclSpec());
7528 
7529       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7530         CheckMSVCRTEntryPoint(NewFD);
7531 
7532       if (!NewFD->isInvalidDecl())
7533         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7534                                                     isExplicitSpecialization));
7535     }
7536 
7537     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7538             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7539            "previous declaration set still overloaded");
7540 
7541     NamedDecl *PrincipalDecl = (FunctionTemplate
7542                                 ? cast<NamedDecl>(FunctionTemplate)
7543                                 : NewFD);
7544 
7545     if (isFriend && D.isRedeclaration()) {
7546       AccessSpecifier Access = AS_public;
7547       if (!NewFD->isInvalidDecl())
7548         Access = NewFD->getPreviousDecl()->getAccess();
7549 
7550       NewFD->setAccess(Access);
7551       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7552     }
7553 
7554     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7555         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7556       PrincipalDecl->setNonMemberOperator();
7557 
7558     // If we have a function template, check the template parameter
7559     // list. This will check and merge default template arguments.
7560     if (FunctionTemplate) {
7561       FunctionTemplateDecl *PrevTemplate =
7562                                      FunctionTemplate->getPreviousDecl();
7563       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7564                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7565                                     : nullptr,
7566                             D.getDeclSpec().isFriendSpecified()
7567                               ? (D.isFunctionDefinition()
7568                                    ? TPC_FriendFunctionTemplateDefinition
7569                                    : TPC_FriendFunctionTemplate)
7570                               : (D.getCXXScopeSpec().isSet() &&
7571                                  DC && DC->isRecord() &&
7572                                  DC->isDependentContext())
7573                                   ? TPC_ClassTemplateMember
7574                                   : TPC_FunctionTemplate);
7575     }
7576 
7577     if (NewFD->isInvalidDecl()) {
7578       // Ignore all the rest of this.
7579     } else if (!D.isRedeclaration()) {
7580       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7581                                        AddToScope };
7582       // Fake up an access specifier if it's supposed to be a class member.
7583       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7584         NewFD->setAccess(AS_public);
7585 
7586       // Qualified decls generally require a previous declaration.
7587       if (D.getCXXScopeSpec().isSet()) {
7588         // ...with the major exception of templated-scope or
7589         // dependent-scope friend declarations.
7590 
7591         // TODO: we currently also suppress this check in dependent
7592         // contexts because (1) the parameter depth will be off when
7593         // matching friend templates and (2) we might actually be
7594         // selecting a friend based on a dependent factor.  But there
7595         // are situations where these conditions don't apply and we
7596         // can actually do this check immediately.
7597         if (isFriend &&
7598             (TemplateParamLists.size() ||
7599              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7600              CurContext->isDependentContext())) {
7601           // ignore these
7602         } else {
7603           // The user tried to provide an out-of-line definition for a
7604           // function that is a member of a class or namespace, but there
7605           // was no such member function declared (C++ [class.mfct]p2,
7606           // C++ [namespace.memdef]p2). For example:
7607           //
7608           // class X {
7609           //   void f() const;
7610           // };
7611           //
7612           // void X::f() { } // ill-formed
7613           //
7614           // Complain about this problem, and attempt to suggest close
7615           // matches (e.g., those that differ only in cv-qualifiers and
7616           // whether the parameter types are references).
7617 
7618           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7619                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7620             AddToScope = ExtraArgs.AddToScope;
7621             return Result;
7622           }
7623         }
7624 
7625         // Unqualified local friend declarations are required to resolve
7626         // to something.
7627       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7628         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7629                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7630           AddToScope = ExtraArgs.AddToScope;
7631           return Result;
7632         }
7633       }
7634 
7635     } else if (!D.isFunctionDefinition() &&
7636                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7637                !isFriend && !isFunctionTemplateSpecialization &&
7638                !isExplicitSpecialization) {
7639       // An out-of-line member function declaration must also be a
7640       // definition (C++ [class.mfct]p2).
7641       // Note that this is not the case for explicit specializations of
7642       // function templates or member functions of class templates, per
7643       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7644       // extension for compatibility with old SWIG code which likes to
7645       // generate them.
7646       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7647         << D.getCXXScopeSpec().getRange();
7648     }
7649   }
7650 
7651   ProcessPragmaWeak(S, NewFD);
7652   checkAttributesAfterMerging(*this, *NewFD);
7653 
7654   AddKnownFunctionAttributes(NewFD);
7655 
7656   if (NewFD->hasAttr<OverloadableAttr>() &&
7657       !NewFD->getType()->getAs<FunctionProtoType>()) {
7658     Diag(NewFD->getLocation(),
7659          diag::err_attribute_overloadable_no_prototype)
7660       << NewFD;
7661 
7662     // Turn this into a variadic function with no parameters.
7663     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7664     FunctionProtoType::ExtProtoInfo EPI(
7665         Context.getDefaultCallingConvention(true, false));
7666     EPI.Variadic = true;
7667     EPI.ExtInfo = FT->getExtInfo();
7668 
7669     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7670     NewFD->setType(R);
7671   }
7672 
7673   // If there's a #pragma GCC visibility in scope, and this isn't a class
7674   // member, set the visibility of this function.
7675   if (!DC->isRecord() && NewFD->isExternallyVisible())
7676     AddPushedVisibilityAttribute(NewFD);
7677 
7678   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7679   // marking the function.
7680   AddCFAuditedAttribute(NewFD);
7681 
7682   // If this is a function definition, check if we have to apply optnone due to
7683   // a pragma.
7684   if(D.isFunctionDefinition())
7685     AddRangeBasedOptnone(NewFD);
7686 
7687   // If this is the first declaration of an extern C variable, update
7688   // the map of such variables.
7689   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7690       isIncompleteDeclExternC(*this, NewFD))
7691     RegisterLocallyScopedExternCDecl(NewFD, S);
7692 
7693   // Set this FunctionDecl's range up to the right paren.
7694   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7695 
7696   if (D.isRedeclaration() && !Previous.empty()) {
7697     checkDLLAttributeRedeclaration(
7698         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7699         isExplicitSpecialization || isFunctionTemplateSpecialization);
7700   }
7701 
7702   if (getLangOpts().CPlusPlus) {
7703     if (FunctionTemplate) {
7704       if (NewFD->isInvalidDecl())
7705         FunctionTemplate->setInvalidDecl();
7706       return FunctionTemplate;
7707     }
7708   }
7709 
7710   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7711     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7712     if ((getLangOpts().OpenCLVersion >= 120)
7713         && (SC == SC_Static)) {
7714       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7715       D.setInvalidType();
7716     }
7717 
7718     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7719     if (!NewFD->getReturnType()->isVoidType()) {
7720       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7721       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7722           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7723                                 : FixItHint());
7724       D.setInvalidType();
7725     }
7726 
7727     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7728     for (auto Param : NewFD->params())
7729       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7730   }
7731 
7732   MarkUnusedFileScopedDecl(NewFD);
7733 
7734   if (getLangOpts().CUDA)
7735     if (IdentifierInfo *II = NewFD->getIdentifier())
7736       if (!NewFD->isInvalidDecl() &&
7737           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7738         if (II->isStr("cudaConfigureCall")) {
7739           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7740             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7741 
7742           Context.setcudaConfigureCallDecl(NewFD);
7743         }
7744       }
7745 
7746   // Here we have an function template explicit specialization at class scope.
7747   // The actually specialization will be postponed to template instatiation
7748   // time via the ClassScopeFunctionSpecializationDecl node.
7749   if (isDependentClassScopeExplicitSpecialization) {
7750     ClassScopeFunctionSpecializationDecl *NewSpec =
7751                          ClassScopeFunctionSpecializationDecl::Create(
7752                                 Context, CurContext, SourceLocation(),
7753                                 cast<CXXMethodDecl>(NewFD),
7754                                 HasExplicitTemplateArgs, TemplateArgs);
7755     CurContext->addDecl(NewSpec);
7756     AddToScope = false;
7757   }
7758 
7759   return NewFD;
7760 }
7761 
7762 /// \brief Perform semantic checking of a new function declaration.
7763 ///
7764 /// Performs semantic analysis of the new function declaration
7765 /// NewFD. This routine performs all semantic checking that does not
7766 /// require the actual declarator involved in the declaration, and is
7767 /// used both for the declaration of functions as they are parsed
7768 /// (called via ActOnDeclarator) and for the declaration of functions
7769 /// that have been instantiated via C++ template instantiation (called
7770 /// via InstantiateDecl).
7771 ///
7772 /// \param IsExplicitSpecialization whether this new function declaration is
7773 /// an explicit specialization of the previous declaration.
7774 ///
7775 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7776 ///
7777 /// \returns true if the function declaration is a redeclaration.
7778 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7779                                     LookupResult &Previous,
7780                                     bool IsExplicitSpecialization) {
7781   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7782          "Variably modified return types are not handled here");
7783 
7784   // Determine whether the type of this function should be merged with
7785   // a previous visible declaration. This never happens for functions in C++,
7786   // and always happens in C if the previous declaration was visible.
7787   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7788                                !Previous.isShadowed();
7789 
7790   // Filter out any non-conflicting previous declarations.
7791   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7792 
7793   bool Redeclaration = false;
7794   NamedDecl *OldDecl = nullptr;
7795 
7796   // Merge or overload the declaration with an existing declaration of
7797   // the same name, if appropriate.
7798   if (!Previous.empty()) {
7799     // Determine whether NewFD is an overload of PrevDecl or
7800     // a declaration that requires merging. If it's an overload,
7801     // there's no more work to do here; we'll just add the new
7802     // function to the scope.
7803     if (!AllowOverloadingOfFunction(Previous, Context)) {
7804       NamedDecl *Candidate = Previous.getFoundDecl();
7805       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7806         Redeclaration = true;
7807         OldDecl = Candidate;
7808       }
7809     } else {
7810       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7811                             /*NewIsUsingDecl*/ false)) {
7812       case Ovl_Match:
7813         Redeclaration = true;
7814         break;
7815 
7816       case Ovl_NonFunction:
7817         Redeclaration = true;
7818         break;
7819 
7820       case Ovl_Overload:
7821         Redeclaration = false;
7822         break;
7823       }
7824 
7825       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7826         // If a function name is overloadable in C, then every function
7827         // with that name must be marked "overloadable".
7828         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7829           << Redeclaration << NewFD;
7830         NamedDecl *OverloadedDecl = nullptr;
7831         if (Redeclaration)
7832           OverloadedDecl = OldDecl;
7833         else if (!Previous.empty())
7834           OverloadedDecl = Previous.getRepresentativeDecl();
7835         if (OverloadedDecl)
7836           Diag(OverloadedDecl->getLocation(),
7837                diag::note_attribute_overloadable_prev_overload);
7838         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7839       }
7840     }
7841   }
7842 
7843   // Check for a previous extern "C" declaration with this name.
7844   if (!Redeclaration &&
7845       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7846     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7847     if (!Previous.empty()) {
7848       // This is an extern "C" declaration with the same name as a previous
7849       // declaration, and thus redeclares that entity...
7850       Redeclaration = true;
7851       OldDecl = Previous.getFoundDecl();
7852       MergeTypeWithPrevious = false;
7853 
7854       // ... except in the presence of __attribute__((overloadable)).
7855       if (OldDecl->hasAttr<OverloadableAttr>()) {
7856         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7857           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7858             << Redeclaration << NewFD;
7859           Diag(Previous.getFoundDecl()->getLocation(),
7860                diag::note_attribute_overloadable_prev_overload);
7861           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7862         }
7863         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7864           Redeclaration = false;
7865           OldDecl = nullptr;
7866         }
7867       }
7868     }
7869   }
7870 
7871   // C++11 [dcl.constexpr]p8:
7872   //   A constexpr specifier for a non-static member function that is not
7873   //   a constructor declares that member function to be const.
7874   //
7875   // This needs to be delayed until we know whether this is an out-of-line
7876   // definition of a static member function.
7877   //
7878   // This rule is not present in C++1y, so we produce a backwards
7879   // compatibility warning whenever it happens in C++11.
7880   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7881   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7882       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7883       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7884     CXXMethodDecl *OldMD = nullptr;
7885     if (OldDecl)
7886       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
7887     if (!OldMD || !OldMD->isStatic()) {
7888       const FunctionProtoType *FPT =
7889         MD->getType()->castAs<FunctionProtoType>();
7890       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7891       EPI.TypeQuals |= Qualifiers::Const;
7892       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7893                                           FPT->getParamTypes(), EPI));
7894 
7895       // Warn that we did this, if we're not performing template instantiation.
7896       // In that case, we'll have warned already when the template was defined.
7897       if (ActiveTemplateInstantiations.empty()) {
7898         SourceLocation AddConstLoc;
7899         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7900                 .IgnoreParens().getAs<FunctionTypeLoc>())
7901           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7902 
7903         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7904           << FixItHint::CreateInsertion(AddConstLoc, " const");
7905       }
7906     }
7907   }
7908 
7909   if (Redeclaration) {
7910     // NewFD and OldDecl represent declarations that need to be
7911     // merged.
7912     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7913       NewFD->setInvalidDecl();
7914       return Redeclaration;
7915     }
7916 
7917     Previous.clear();
7918     Previous.addDecl(OldDecl);
7919 
7920     if (FunctionTemplateDecl *OldTemplateDecl
7921                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7922       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7923       FunctionTemplateDecl *NewTemplateDecl
7924         = NewFD->getDescribedFunctionTemplate();
7925       assert(NewTemplateDecl && "Template/non-template mismatch");
7926       if (CXXMethodDecl *Method
7927             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7928         Method->setAccess(OldTemplateDecl->getAccess());
7929         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7930       }
7931 
7932       // If this is an explicit specialization of a member that is a function
7933       // template, mark it as a member specialization.
7934       if (IsExplicitSpecialization &&
7935           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7936         NewTemplateDecl->setMemberSpecialization();
7937         assert(OldTemplateDecl->isMemberSpecialization());
7938       }
7939 
7940     } else {
7941       // This needs to happen first so that 'inline' propagates.
7942       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7943 
7944       if (isa<CXXMethodDecl>(NewFD)) {
7945         // A valid redeclaration of a C++ method must be out-of-line,
7946         // but (unfortunately) it's not necessarily a definition
7947         // because of templates, which means that the previous
7948         // declaration is not necessarily from the class definition.
7949 
7950         // For just setting the access, that doesn't matter.
7951         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7952         NewFD->setAccess(oldMethod->getAccess());
7953 
7954         // Update the key-function state if necessary for this ABI.
7955         if (NewFD->isInlined() &&
7956             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7957           // setNonKeyFunction needs to work with the original
7958           // declaration from the class definition, and isVirtual() is
7959           // just faster in that case, so map back to that now.
7960           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7961           if (oldMethod->isVirtual()) {
7962             Context.setNonKeyFunction(oldMethod);
7963           }
7964         }
7965       }
7966     }
7967   }
7968 
7969   // Semantic checking for this function declaration (in isolation).
7970 
7971   if (getLangOpts().CPlusPlus) {
7972     // C++-specific checks.
7973     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7974       CheckConstructor(Constructor);
7975     } else if (CXXDestructorDecl *Destructor =
7976                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7977       CXXRecordDecl *Record = Destructor->getParent();
7978       QualType ClassType = Context.getTypeDeclType(Record);
7979 
7980       // FIXME: Shouldn't we be able to perform this check even when the class
7981       // type is dependent? Both gcc and edg can handle that.
7982       if (!ClassType->isDependentType()) {
7983         DeclarationName Name
7984           = Context.DeclarationNames.getCXXDestructorName(
7985                                         Context.getCanonicalType(ClassType));
7986         if (NewFD->getDeclName() != Name) {
7987           Diag(NewFD->getLocation(), diag::err_destructor_name);
7988           NewFD->setInvalidDecl();
7989           return Redeclaration;
7990         }
7991       }
7992     } else if (CXXConversionDecl *Conversion
7993                = dyn_cast<CXXConversionDecl>(NewFD)) {
7994       ActOnConversionDeclarator(Conversion);
7995     }
7996 
7997     // Find any virtual functions that this function overrides.
7998     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7999       if (!Method->isFunctionTemplateSpecialization() &&
8000           !Method->getDescribedFunctionTemplate() &&
8001           Method->isCanonicalDecl()) {
8002         if (AddOverriddenMethods(Method->getParent(), Method)) {
8003           // If the function was marked as "static", we have a problem.
8004           if (NewFD->getStorageClass() == SC_Static) {
8005             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8006           }
8007         }
8008       }
8009 
8010       if (Method->isStatic())
8011         checkThisInStaticMemberFunctionType(Method);
8012     }
8013 
8014     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8015     if (NewFD->isOverloadedOperator() &&
8016         CheckOverloadedOperatorDeclaration(NewFD)) {
8017       NewFD->setInvalidDecl();
8018       return Redeclaration;
8019     }
8020 
8021     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8022     if (NewFD->getLiteralIdentifier() &&
8023         CheckLiteralOperatorDeclaration(NewFD)) {
8024       NewFD->setInvalidDecl();
8025       return Redeclaration;
8026     }
8027 
8028     // In C++, check default arguments now that we have merged decls. Unless
8029     // the lexical context is the class, because in this case this is done
8030     // during delayed parsing anyway.
8031     if (!CurContext->isRecord())
8032       CheckCXXDefaultArguments(NewFD);
8033 
8034     // If this function declares a builtin function, check the type of this
8035     // declaration against the expected type for the builtin.
8036     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8037       ASTContext::GetBuiltinTypeError Error;
8038       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8039       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8040       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8041         // The type of this function differs from the type of the builtin,
8042         // so forget about the builtin entirely.
8043         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8044       }
8045     }
8046 
8047     // If this function is declared as being extern "C", then check to see if
8048     // the function returns a UDT (class, struct, or union type) that is not C
8049     // compatible, and if it does, warn the user.
8050     // But, issue any diagnostic on the first declaration only.
8051     if (NewFD->isExternC() && Previous.empty()) {
8052       QualType R = NewFD->getReturnType();
8053       if (R->isIncompleteType() && !R->isVoidType())
8054         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8055             << NewFD << R;
8056       else if (!R.isPODType(Context) && !R->isVoidType() &&
8057                !R->isObjCObjectPointerType())
8058         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8059     }
8060   }
8061   return Redeclaration;
8062 }
8063 
8064 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8065   // C++11 [basic.start.main]p3:
8066   //   A program that [...] declares main to be inline, static or
8067   //   constexpr is ill-formed.
8068   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8069   //   appear in a declaration of main.
8070   // static main is not an error under C99, but we should warn about it.
8071   // We accept _Noreturn main as an extension.
8072   if (FD->getStorageClass() == SC_Static)
8073     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8074          ? diag::err_static_main : diag::warn_static_main)
8075       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8076   if (FD->isInlineSpecified())
8077     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8078       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8079   if (DS.isNoreturnSpecified()) {
8080     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8081     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8082     Diag(NoreturnLoc, diag::ext_noreturn_main);
8083     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8084       << FixItHint::CreateRemoval(NoreturnRange);
8085   }
8086   if (FD->isConstexpr()) {
8087     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8088       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8089     FD->setConstexpr(false);
8090   }
8091 
8092   if (getLangOpts().OpenCL) {
8093     Diag(FD->getLocation(), diag::err_opencl_no_main)
8094         << FD->hasAttr<OpenCLKernelAttr>();
8095     FD->setInvalidDecl();
8096     return;
8097   }
8098 
8099   QualType T = FD->getType();
8100   assert(T->isFunctionType() && "function decl is not of function type");
8101   const FunctionType* FT = T->castAs<FunctionType>();
8102 
8103   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8104     // In C with GNU extensions we allow main() to have non-integer return
8105     // type, but we should warn about the extension, and we disable the
8106     // implicit-return-zero rule.
8107 
8108     // GCC in C mode accepts qualified 'int'.
8109     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8110       FD->setHasImplicitReturnZero(true);
8111     else {
8112       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8113       SourceRange RTRange = FD->getReturnTypeSourceRange();
8114       if (RTRange.isValid())
8115         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8116             << FixItHint::CreateReplacement(RTRange, "int");
8117     }
8118   } else {
8119     // In C and C++, main magically returns 0 if you fall off the end;
8120     // set the flag which tells us that.
8121     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8122 
8123     // All the standards say that main() should return 'int'.
8124     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8125       FD->setHasImplicitReturnZero(true);
8126     else {
8127       // Otherwise, this is just a flat-out error.
8128       SourceRange RTRange = FD->getReturnTypeSourceRange();
8129       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8130           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8131                                 : FixItHint());
8132       FD->setInvalidDecl(true);
8133     }
8134   }
8135 
8136   // Treat protoless main() as nullary.
8137   if (isa<FunctionNoProtoType>(FT)) return;
8138 
8139   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8140   unsigned nparams = FTP->getNumParams();
8141   assert(FD->getNumParams() == nparams);
8142 
8143   bool HasExtraParameters = (nparams > 3);
8144 
8145   // Darwin passes an undocumented fourth argument of type char**.  If
8146   // other platforms start sprouting these, the logic below will start
8147   // getting shifty.
8148   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8149     HasExtraParameters = false;
8150 
8151   if (HasExtraParameters) {
8152     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8153     FD->setInvalidDecl(true);
8154     nparams = 3;
8155   }
8156 
8157   // FIXME: a lot of the following diagnostics would be improved
8158   // if we had some location information about types.
8159 
8160   QualType CharPP =
8161     Context.getPointerType(Context.getPointerType(Context.CharTy));
8162   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8163 
8164   for (unsigned i = 0; i < nparams; ++i) {
8165     QualType AT = FTP->getParamType(i);
8166 
8167     bool mismatch = true;
8168 
8169     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8170       mismatch = false;
8171     else if (Expected[i] == CharPP) {
8172       // As an extension, the following forms are okay:
8173       //   char const **
8174       //   char const * const *
8175       //   char * const *
8176 
8177       QualifierCollector qs;
8178       const PointerType* PT;
8179       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8180           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8181           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8182                               Context.CharTy)) {
8183         qs.removeConst();
8184         mismatch = !qs.empty();
8185       }
8186     }
8187 
8188     if (mismatch) {
8189       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8190       // TODO: suggest replacing given type with expected type
8191       FD->setInvalidDecl(true);
8192     }
8193   }
8194 
8195   if (nparams == 1 && !FD->isInvalidDecl()) {
8196     Diag(FD->getLocation(), diag::warn_main_one_arg);
8197   }
8198 
8199   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8200     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8201     FD->setInvalidDecl();
8202   }
8203 }
8204 
8205 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8206   QualType T = FD->getType();
8207   assert(T->isFunctionType() && "function decl is not of function type");
8208   const FunctionType *FT = T->castAs<FunctionType>();
8209 
8210   // Set an implicit return of 'zero' if the function can return some integral,
8211   // enumeration, pointer or nullptr type.
8212   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8213       FT->getReturnType()->isAnyPointerType() ||
8214       FT->getReturnType()->isNullPtrType())
8215     // DllMain is exempt because a return value of zero means it failed.
8216     if (FD->getName() != "DllMain")
8217       FD->setHasImplicitReturnZero(true);
8218 
8219   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8220     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8221     FD->setInvalidDecl();
8222   }
8223 }
8224 
8225 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8226   // FIXME: Need strict checking.  In C89, we need to check for
8227   // any assignment, increment, decrement, function-calls, or
8228   // commas outside of a sizeof.  In C99, it's the same list,
8229   // except that the aforementioned are allowed in unevaluated
8230   // expressions.  Everything else falls under the
8231   // "may accept other forms of constant expressions" exception.
8232   // (We never end up here for C++, so the constant expression
8233   // rules there don't matter.)
8234   const Expr *Culprit;
8235   if (Init->isConstantInitializer(Context, false, &Culprit))
8236     return false;
8237   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8238     << Culprit->getSourceRange();
8239   return true;
8240 }
8241 
8242 namespace {
8243   // Visits an initialization expression to see if OrigDecl is evaluated in
8244   // its own initialization and throws a warning if it does.
8245   class SelfReferenceChecker
8246       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8247     Sema &S;
8248     Decl *OrigDecl;
8249     bool isRecordType;
8250     bool isPODType;
8251     bool isReferenceType;
8252 
8253     bool isInitList;
8254     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8255   public:
8256     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8257 
8258     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8259                                                     S(S), OrigDecl(OrigDecl) {
8260       isPODType = false;
8261       isRecordType = false;
8262       isReferenceType = false;
8263       isInitList = false;
8264       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8265         isPODType = VD->getType().isPODType(S.Context);
8266         isRecordType = VD->getType()->isRecordType();
8267         isReferenceType = VD->getType()->isReferenceType();
8268       }
8269     }
8270 
8271     // For most expressions, just call the visitor.  For initializer lists,
8272     // track the index of the field being initialized since fields are
8273     // initialized in order allowing use of previously initialized fields.
8274     void CheckExpr(Expr *E) {
8275       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8276       if (!InitList) {
8277         Visit(E);
8278         return;
8279       }
8280 
8281       // Track and increment the index here.
8282       isInitList = true;
8283       InitFieldIndex.push_back(0);
8284       for (auto Child : InitList->children()) {
8285         CheckExpr(cast<Expr>(Child));
8286         ++InitFieldIndex.back();
8287       }
8288       InitFieldIndex.pop_back();
8289     }
8290 
8291     // Returns true if MemberExpr is checked and no futher checking is needed.
8292     // Returns false if additional checking is required.
8293     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8294       llvm::SmallVector<FieldDecl*, 4> Fields;
8295       Expr *Base = E;
8296       bool ReferenceField = false;
8297 
8298       // Get the field memebers used.
8299       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8300         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8301         if (!FD)
8302           return false;
8303         Fields.push_back(FD);
8304         if (FD->getType()->isReferenceType())
8305           ReferenceField = true;
8306         Base = ME->getBase()->IgnoreParenImpCasts();
8307       }
8308 
8309       // Keep checking only if the base Decl is the same.
8310       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8311       if (!DRE || DRE->getDecl() != OrigDecl)
8312         return false;
8313 
8314       // A reference field can be bound to an unininitialized field.
8315       if (CheckReference && !ReferenceField)
8316         return true;
8317 
8318       // Convert FieldDecls to their index number.
8319       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8320       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8321         UsedFieldIndex.push_back((*I)->getFieldIndex());
8322       }
8323 
8324       // See if a warning is needed by checking the first difference in index
8325       // numbers.  If field being used has index less than the field being
8326       // initialized, then the use is safe.
8327       for (auto UsedIter = UsedFieldIndex.begin(),
8328                 UsedEnd = UsedFieldIndex.end(),
8329                 OrigIter = InitFieldIndex.begin(),
8330                 OrigEnd = InitFieldIndex.end();
8331            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8332         if (*UsedIter < *OrigIter)
8333           return true;
8334         if (*UsedIter > *OrigIter)
8335           break;
8336       }
8337 
8338       // TODO: Add a different warning which will print the field names.
8339       HandleDeclRefExpr(DRE);
8340       return true;
8341     }
8342 
8343     // For most expressions, the cast is directly above the DeclRefExpr.
8344     // For conditional operators, the cast can be outside the conditional
8345     // operator if both expressions are DeclRefExpr's.
8346     void HandleValue(Expr *E) {
8347       E = E->IgnoreParens();
8348       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8349         HandleDeclRefExpr(DRE);
8350         return;
8351       }
8352 
8353       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8354         Visit(CO->getCond());
8355         HandleValue(CO->getTrueExpr());
8356         HandleValue(CO->getFalseExpr());
8357         return;
8358       }
8359 
8360       if (BinaryConditionalOperator *BCO =
8361               dyn_cast<BinaryConditionalOperator>(E)) {
8362         Visit(BCO->getCond());
8363         HandleValue(BCO->getFalseExpr());
8364         return;
8365       }
8366 
8367       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8368         HandleValue(OVE->getSourceExpr());
8369         return;
8370       }
8371 
8372       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8373         if (BO->getOpcode() == BO_Comma) {
8374           Visit(BO->getLHS());
8375           HandleValue(BO->getRHS());
8376           return;
8377         }
8378       }
8379 
8380       if (isa<MemberExpr>(E)) {
8381         if (isInitList) {
8382           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8383                                       false /*CheckReference*/))
8384             return;
8385         }
8386 
8387         Expr *Base = E->IgnoreParenImpCasts();
8388         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8389           // Check for static member variables and don't warn on them.
8390           if (!isa<FieldDecl>(ME->getMemberDecl()))
8391             return;
8392           Base = ME->getBase()->IgnoreParenImpCasts();
8393         }
8394         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8395           HandleDeclRefExpr(DRE);
8396         return;
8397       }
8398 
8399       Visit(E);
8400     }
8401 
8402     // Reference types not handled in HandleValue are handled here since all
8403     // uses of references are bad, not just r-value uses.
8404     void VisitDeclRefExpr(DeclRefExpr *E) {
8405       if (isReferenceType)
8406         HandleDeclRefExpr(E);
8407     }
8408 
8409     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8410       if (E->getCastKind() == CK_LValueToRValue) {
8411         HandleValue(E->getSubExpr());
8412         return;
8413       }
8414 
8415       Inherited::VisitImplicitCastExpr(E);
8416     }
8417 
8418     void VisitMemberExpr(MemberExpr *E) {
8419       if (isInitList) {
8420         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8421           return;
8422       }
8423 
8424       // Don't warn on arrays since they can be treated as pointers.
8425       if (E->getType()->canDecayToPointerType()) return;
8426 
8427       // Warn when a non-static method call is followed by non-static member
8428       // field accesses, which is followed by a DeclRefExpr.
8429       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8430       bool Warn = (MD && !MD->isStatic());
8431       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8432       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8433         if (!isa<FieldDecl>(ME->getMemberDecl()))
8434           Warn = false;
8435         Base = ME->getBase()->IgnoreParenImpCasts();
8436       }
8437 
8438       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8439         if (Warn)
8440           HandleDeclRefExpr(DRE);
8441         return;
8442       }
8443 
8444       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8445       // Visit that expression.
8446       Visit(Base);
8447     }
8448 
8449     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8450       Expr *Callee = E->getCallee();
8451 
8452       if (isa<UnresolvedLookupExpr>(Callee))
8453         return Inherited::VisitCXXOperatorCallExpr(E);
8454 
8455       Visit(Callee);
8456       for (auto Arg: E->arguments())
8457         HandleValue(Arg->IgnoreParenImpCasts());
8458     }
8459 
8460     void VisitUnaryOperator(UnaryOperator *E) {
8461       // For POD record types, addresses of its own members are well-defined.
8462       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8463           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8464         if (!isPODType)
8465           HandleValue(E->getSubExpr());
8466         return;
8467       }
8468 
8469       if (E->isIncrementDecrementOp()) {
8470         HandleValue(E->getSubExpr());
8471         return;
8472       }
8473 
8474       Inherited::VisitUnaryOperator(E);
8475     }
8476 
8477     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8478 
8479     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8480       if (E->getConstructor()->isCopyConstructor()) {
8481         Expr *ArgExpr = E->getArg(0);
8482         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8483           if (ILE->getNumInits() == 1)
8484             ArgExpr = ILE->getInit(0);
8485         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8486           if (ICE->getCastKind() == CK_NoOp)
8487             ArgExpr = ICE->getSubExpr();
8488         HandleValue(ArgExpr);
8489         return;
8490       }
8491       Inherited::VisitCXXConstructExpr(E);
8492     }
8493 
8494     void VisitCallExpr(CallExpr *E) {
8495       // Treat std::move as a use.
8496       if (E->getNumArgs() == 1) {
8497         if (FunctionDecl *FD = E->getDirectCallee()) {
8498           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8499               FD->getIdentifier()->isStr("move")) {
8500             HandleValue(E->getArg(0));
8501             return;
8502           }
8503         }
8504       }
8505 
8506       Inherited::VisitCallExpr(E);
8507     }
8508 
8509     void VisitBinaryOperator(BinaryOperator *E) {
8510       if (E->isCompoundAssignmentOp()) {
8511         HandleValue(E->getLHS());
8512         Visit(E->getRHS());
8513         return;
8514       }
8515 
8516       Inherited::VisitBinaryOperator(E);
8517     }
8518 
8519     // A custom visitor for BinaryConditionalOperator is needed because the
8520     // regular visitor would check the condition and true expression separately
8521     // but both point to the same place giving duplicate diagnostics.
8522     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8523       Visit(E->getCond());
8524       Visit(E->getFalseExpr());
8525     }
8526 
8527     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8528       Decl* ReferenceDecl = DRE->getDecl();
8529       if (OrigDecl != ReferenceDecl) return;
8530       unsigned diag;
8531       if (isReferenceType) {
8532         diag = diag::warn_uninit_self_reference_in_reference_init;
8533       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8534         diag = diag::warn_static_self_reference_in_init;
8535       } else {
8536         diag = diag::warn_uninit_self_reference_in_init;
8537       }
8538 
8539       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8540                             S.PDiag(diag)
8541                               << DRE->getNameInfo().getName()
8542                               << OrigDecl->getLocation()
8543                               << DRE->getSourceRange());
8544     }
8545   };
8546 
8547   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8548   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8549                                  bool DirectInit) {
8550     // Parameters arguments are occassionially constructed with itself,
8551     // for instance, in recursive functions.  Skip them.
8552     if (isa<ParmVarDecl>(OrigDecl))
8553       return;
8554 
8555     E = E->IgnoreParens();
8556 
8557     // Skip checking T a = a where T is not a record or reference type.
8558     // Doing so is a way to silence uninitialized warnings.
8559     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8560       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8561         if (ICE->getCastKind() == CK_LValueToRValue)
8562           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8563             if (DRE->getDecl() == OrigDecl)
8564               return;
8565 
8566     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8567   }
8568 }
8569 
8570 /// AddInitializerToDecl - Adds the initializer Init to the
8571 /// declaration dcl. If DirectInit is true, this is C++ direct
8572 /// initialization rather than copy initialization.
8573 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8574                                 bool DirectInit, bool TypeMayContainAuto) {
8575   // If there is no declaration, there was an error parsing it.  Just ignore
8576   // the initializer.
8577   if (!RealDecl || RealDecl->isInvalidDecl())
8578     return;
8579 
8580   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8581     // With declarators parsed the way they are, the parser cannot
8582     // distinguish between a normal initializer and a pure-specifier.
8583     // Thus this grotesque test.
8584     IntegerLiteral *IL;
8585     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8586         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8587       CheckPureMethod(Method, Init->getSourceRange());
8588     else {
8589       Diag(Method->getLocation(), diag::err_member_function_initialization)
8590         << Method->getDeclName() << Init->getSourceRange();
8591       Method->setInvalidDecl();
8592     }
8593     return;
8594   }
8595 
8596   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8597   if (!VDecl) {
8598     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8599     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8600     RealDecl->setInvalidDecl();
8601     return;
8602   }
8603   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8604 
8605   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8606   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8607     Expr *DeduceInit = Init;
8608     // Initializer could be a C++ direct-initializer. Deduction only works if it
8609     // contains exactly one expression.
8610     if (CXXDirectInit) {
8611       if (CXXDirectInit->getNumExprs() == 0) {
8612         // It isn't possible to write this directly, but it is possible to
8613         // end up in this situation with "auto x(some_pack...);"
8614         Diag(CXXDirectInit->getLocStart(),
8615              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8616                                     : diag::err_auto_var_init_no_expression)
8617           << VDecl->getDeclName() << VDecl->getType()
8618           << VDecl->getSourceRange();
8619         RealDecl->setInvalidDecl();
8620         return;
8621       } else if (CXXDirectInit->getNumExprs() > 1) {
8622         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8623              VDecl->isInitCapture()
8624                  ? diag::err_init_capture_multiple_expressions
8625                  : diag::err_auto_var_init_multiple_expressions)
8626           << VDecl->getDeclName() << VDecl->getType()
8627           << VDecl->getSourceRange();
8628         RealDecl->setInvalidDecl();
8629         return;
8630       } else {
8631         DeduceInit = CXXDirectInit->getExpr(0);
8632         if (isa<InitListExpr>(DeduceInit))
8633           Diag(CXXDirectInit->getLocStart(),
8634                diag::err_auto_var_init_paren_braces)
8635             << VDecl->getDeclName() << VDecl->getType()
8636             << VDecl->getSourceRange();
8637       }
8638     }
8639 
8640     // Expressions default to 'id' when we're in a debugger.
8641     bool DefaultedToAuto = false;
8642     if (getLangOpts().DebuggerCastResultToId &&
8643         Init->getType() == Context.UnknownAnyTy) {
8644       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8645       if (Result.isInvalid()) {
8646         VDecl->setInvalidDecl();
8647         return;
8648       }
8649       Init = Result.get();
8650       DefaultedToAuto = true;
8651     }
8652 
8653     QualType DeducedType;
8654     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8655             DAR_Failed)
8656       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8657     if (DeducedType.isNull()) {
8658       RealDecl->setInvalidDecl();
8659       return;
8660     }
8661     VDecl->setType(DeducedType);
8662     assert(VDecl->isLinkageValid());
8663 
8664     // In ARC, infer lifetime.
8665     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8666       VDecl->setInvalidDecl();
8667 
8668     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8669     // 'id' instead of a specific object type prevents most of our usual checks.
8670     // We only want to warn outside of template instantiations, though:
8671     // inside a template, the 'id' could have come from a parameter.
8672     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8673         DeducedType->isObjCIdType()) {
8674       SourceLocation Loc =
8675           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8676       Diag(Loc, diag::warn_auto_var_is_id)
8677         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8678     }
8679 
8680     // If this is a redeclaration, check that the type we just deduced matches
8681     // the previously declared type.
8682     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8683       // We never need to merge the type, because we cannot form an incomplete
8684       // array of auto, nor deduce such a type.
8685       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8686     }
8687 
8688     // Check the deduced type is valid for a variable declaration.
8689     CheckVariableDeclarationType(VDecl);
8690     if (VDecl->isInvalidDecl())
8691       return;
8692   }
8693 
8694   // dllimport cannot be used on variable definitions.
8695   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8696     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8697     VDecl->setInvalidDecl();
8698     return;
8699   }
8700 
8701   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8702     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8703     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8704     VDecl->setInvalidDecl();
8705     return;
8706   }
8707 
8708   if (!VDecl->getType()->isDependentType()) {
8709     // A definition must end up with a complete type, which means it must be
8710     // complete with the restriction that an array type might be completed by
8711     // the initializer; note that later code assumes this restriction.
8712     QualType BaseDeclType = VDecl->getType();
8713     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8714       BaseDeclType = Array->getElementType();
8715     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8716                             diag::err_typecheck_decl_incomplete_type)) {
8717       RealDecl->setInvalidDecl();
8718       return;
8719     }
8720 
8721     // The variable can not have an abstract class type.
8722     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8723                                diag::err_abstract_type_in_decl,
8724                                AbstractVariableType))
8725       VDecl->setInvalidDecl();
8726   }
8727 
8728   const VarDecl *Def;
8729   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8730     Diag(VDecl->getLocation(), diag::err_redefinition)
8731       << VDecl->getDeclName();
8732     Diag(Def->getLocation(), diag::note_previous_definition);
8733     VDecl->setInvalidDecl();
8734     return;
8735   }
8736 
8737   const VarDecl *PrevInit = nullptr;
8738   if (getLangOpts().CPlusPlus) {
8739     // C++ [class.static.data]p4
8740     //   If a static data member is of const integral or const
8741     //   enumeration type, its declaration in the class definition can
8742     //   specify a constant-initializer which shall be an integral
8743     //   constant expression (5.19). In that case, the member can appear
8744     //   in integral constant expressions. The member shall still be
8745     //   defined in a namespace scope if it is used in the program and the
8746     //   namespace scope definition shall not contain an initializer.
8747     //
8748     // We already performed a redefinition check above, but for static
8749     // data members we also need to check whether there was an in-class
8750     // declaration with an initializer.
8751     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8752       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8753           << VDecl->getDeclName();
8754       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8755       return;
8756     }
8757 
8758     if (VDecl->hasLocalStorage())
8759       getCurFunction()->setHasBranchProtectedScope();
8760 
8761     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8762       VDecl->setInvalidDecl();
8763       return;
8764     }
8765   }
8766 
8767   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8768   // a kernel function cannot be initialized."
8769   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8770     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8771     VDecl->setInvalidDecl();
8772     return;
8773   }
8774 
8775   // Get the decls type and save a reference for later, since
8776   // CheckInitializerTypes may change it.
8777   QualType DclT = VDecl->getType(), SavT = DclT;
8778 
8779   // Expressions default to 'id' when we're in a debugger
8780   // and we are assigning it to a variable of Objective-C pointer type.
8781   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8782       Init->getType() == Context.UnknownAnyTy) {
8783     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8784     if (Result.isInvalid()) {
8785       VDecl->setInvalidDecl();
8786       return;
8787     }
8788     Init = Result.get();
8789   }
8790 
8791   // Perform the initialization.
8792   if (!VDecl->isInvalidDecl()) {
8793     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8794     InitializationKind Kind
8795       = DirectInit ?
8796           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8797                                                            Init->getLocStart(),
8798                                                            Init->getLocEnd())
8799                         : InitializationKind::CreateDirectList(
8800                                                           VDecl->getLocation())
8801                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8802                                                     Init->getLocStart());
8803 
8804     MultiExprArg Args = Init;
8805     if (CXXDirectInit)
8806       Args = MultiExprArg(CXXDirectInit->getExprs(),
8807                           CXXDirectInit->getNumExprs());
8808 
8809     // Try to correct any TypoExprs in the initialization arguments.
8810     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
8811       ExprResult Res =
8812           CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
8813             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
8814             return Init.Failed() ? ExprError() : E;
8815           });
8816       if (Res.isInvalid()) {
8817         VDecl->setInvalidDecl();
8818         return;
8819       }
8820       if (Res.get() != Args[Idx])
8821         Args[Idx] = Res.get();
8822     }
8823 
8824     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8825     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8826     if (Result.isInvalid()) {
8827       VDecl->setInvalidDecl();
8828       return;
8829     }
8830 
8831     Init = Result.getAs<Expr>();
8832   }
8833 
8834   // Check for self-references within variable initializers.
8835   // Variables declared within a function/method body (except for references)
8836   // are handled by a dataflow analysis.
8837   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8838       VDecl->getType()->isReferenceType()) {
8839     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8840   }
8841 
8842   // If the type changed, it means we had an incomplete type that was
8843   // completed by the initializer. For example:
8844   //   int ary[] = { 1, 3, 5 };
8845   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8846   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8847     VDecl->setType(DclT);
8848 
8849   if (!VDecl->isInvalidDecl()) {
8850     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8851 
8852     if (VDecl->hasAttr<BlocksAttr>())
8853       checkRetainCycles(VDecl, Init);
8854 
8855     // It is safe to assign a weak reference into a strong variable.
8856     // Although this code can still have problems:
8857     //   id x = self.weakProp;
8858     //   id y = self.weakProp;
8859     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8860     // paths through the function. This should be revisited if
8861     // -Wrepeated-use-of-weak is made flow-sensitive.
8862     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8863         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8864                          Init->getLocStart()))
8865         getCurFunction()->markSafeWeakUse(Init);
8866   }
8867 
8868   // The initialization is usually a full-expression.
8869   //
8870   // FIXME: If this is a braced initialization of an aggregate, it is not
8871   // an expression, and each individual field initializer is a separate
8872   // full-expression. For instance, in:
8873   //
8874   //   struct Temp { ~Temp(); };
8875   //   struct S { S(Temp); };
8876   //   struct T { S a, b; } t = { Temp(), Temp() }
8877   //
8878   // we should destroy the first Temp before constructing the second.
8879   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8880                                           false,
8881                                           VDecl->isConstexpr());
8882   if (Result.isInvalid()) {
8883     VDecl->setInvalidDecl();
8884     return;
8885   }
8886   Init = Result.get();
8887 
8888   // Attach the initializer to the decl.
8889   VDecl->setInit(Init);
8890 
8891   if (VDecl->isLocalVarDecl()) {
8892     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8893     // static storage duration shall be constant expressions or string literals.
8894     // C++ does not have this restriction.
8895     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8896       const Expr *Culprit;
8897       if (VDecl->getStorageClass() == SC_Static)
8898         CheckForConstantInitializer(Init, DclT);
8899       // C89 is stricter than C99 for non-static aggregate types.
8900       // C89 6.5.7p3: All the expressions [...] in an initializer list
8901       // for an object that has aggregate or union type shall be
8902       // constant expressions.
8903       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8904                isa<InitListExpr>(Init) &&
8905                !Init->isConstantInitializer(Context, false, &Culprit))
8906         Diag(Culprit->getExprLoc(),
8907              diag::ext_aggregate_init_not_constant)
8908           << Culprit->getSourceRange();
8909     }
8910   } else if (VDecl->isStaticDataMember() &&
8911              VDecl->getLexicalDeclContext()->isRecord()) {
8912     // This is an in-class initialization for a static data member, e.g.,
8913     //
8914     // struct S {
8915     //   static const int value = 17;
8916     // };
8917 
8918     // C++ [class.mem]p4:
8919     //   A member-declarator can contain a constant-initializer only
8920     //   if it declares a static member (9.4) of const integral or
8921     //   const enumeration type, see 9.4.2.
8922     //
8923     // C++11 [class.static.data]p3:
8924     //   If a non-volatile const static data member is of integral or
8925     //   enumeration type, its declaration in the class definition can
8926     //   specify a brace-or-equal-initializer in which every initalizer-clause
8927     //   that is an assignment-expression is a constant expression. A static
8928     //   data member of literal type can be declared in the class definition
8929     //   with the constexpr specifier; if so, its declaration shall specify a
8930     //   brace-or-equal-initializer in which every initializer-clause that is
8931     //   an assignment-expression is a constant expression.
8932 
8933     // Do nothing on dependent types.
8934     if (DclT->isDependentType()) {
8935 
8936     // Allow any 'static constexpr' members, whether or not they are of literal
8937     // type. We separately check that every constexpr variable is of literal
8938     // type.
8939     } else if (VDecl->isConstexpr()) {
8940 
8941     // Require constness.
8942     } else if (!DclT.isConstQualified()) {
8943       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8944         << Init->getSourceRange();
8945       VDecl->setInvalidDecl();
8946 
8947     // We allow integer constant expressions in all cases.
8948     } else if (DclT->isIntegralOrEnumerationType()) {
8949       // Check whether the expression is a constant expression.
8950       SourceLocation Loc;
8951       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8952         // In C++11, a non-constexpr const static data member with an
8953         // in-class initializer cannot be volatile.
8954         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8955       else if (Init->isValueDependent())
8956         ; // Nothing to check.
8957       else if (Init->isIntegerConstantExpr(Context, &Loc))
8958         ; // Ok, it's an ICE!
8959       else if (Init->isEvaluatable(Context)) {
8960         // If we can constant fold the initializer through heroics, accept it,
8961         // but report this as a use of an extension for -pedantic.
8962         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8963           << Init->getSourceRange();
8964       } else {
8965         // Otherwise, this is some crazy unknown case.  Report the issue at the
8966         // location provided by the isIntegerConstantExpr failed check.
8967         Diag(Loc, diag::err_in_class_initializer_non_constant)
8968           << Init->getSourceRange();
8969         VDecl->setInvalidDecl();
8970       }
8971 
8972     // We allow foldable floating-point constants as an extension.
8973     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8974       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8975       // it anyway and provide a fixit to add the 'constexpr'.
8976       if (getLangOpts().CPlusPlus11) {
8977         Diag(VDecl->getLocation(),
8978              diag::ext_in_class_initializer_float_type_cxx11)
8979             << DclT << Init->getSourceRange();
8980         Diag(VDecl->getLocStart(),
8981              diag::note_in_class_initializer_float_type_cxx11)
8982             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8983       } else {
8984         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8985           << DclT << Init->getSourceRange();
8986 
8987         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8988           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8989             << Init->getSourceRange();
8990           VDecl->setInvalidDecl();
8991         }
8992       }
8993 
8994     // Suggest adding 'constexpr' in C++11 for literal types.
8995     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8996       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8997         << DclT << Init->getSourceRange()
8998         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8999       VDecl->setConstexpr(true);
9000 
9001     } else {
9002       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9003         << DclT << Init->getSourceRange();
9004       VDecl->setInvalidDecl();
9005     }
9006   } else if (VDecl->isFileVarDecl()) {
9007     if (VDecl->getStorageClass() == SC_Extern &&
9008         (!getLangOpts().CPlusPlus ||
9009          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9010            VDecl->isExternC())) &&
9011         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9012       Diag(VDecl->getLocation(), diag::warn_extern_init);
9013 
9014     // C99 6.7.8p4. All file scoped initializers need to be constant.
9015     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9016       CheckForConstantInitializer(Init, DclT);
9017   }
9018 
9019   // We will represent direct-initialization similarly to copy-initialization:
9020   //    int x(1);  -as-> int x = 1;
9021   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9022   //
9023   // Clients that want to distinguish between the two forms, can check for
9024   // direct initializer using VarDecl::getInitStyle().
9025   // A major benefit is that clients that don't particularly care about which
9026   // exactly form was it (like the CodeGen) can handle both cases without
9027   // special case code.
9028 
9029   // C++ 8.5p11:
9030   // The form of initialization (using parentheses or '=') is generally
9031   // insignificant, but does matter when the entity being initialized has a
9032   // class type.
9033   if (CXXDirectInit) {
9034     assert(DirectInit && "Call-style initializer must be direct init.");
9035     VDecl->setInitStyle(VarDecl::CallInit);
9036   } else if (DirectInit) {
9037     // This must be list-initialization. No other way is direct-initialization.
9038     VDecl->setInitStyle(VarDecl::ListInit);
9039   }
9040 
9041   CheckCompleteVariableDeclaration(VDecl);
9042 }
9043 
9044 /// ActOnInitializerError - Given that there was an error parsing an
9045 /// initializer for the given declaration, try to return to some form
9046 /// of sanity.
9047 void Sema::ActOnInitializerError(Decl *D) {
9048   // Our main concern here is re-establishing invariants like "a
9049   // variable's type is either dependent or complete".
9050   if (!D || D->isInvalidDecl()) return;
9051 
9052   VarDecl *VD = dyn_cast<VarDecl>(D);
9053   if (!VD) return;
9054 
9055   // Auto types are meaningless if we can't make sense of the initializer.
9056   if (ParsingInitForAutoVars.count(D)) {
9057     D->setInvalidDecl();
9058     return;
9059   }
9060 
9061   QualType Ty = VD->getType();
9062   if (Ty->isDependentType()) return;
9063 
9064   // Require a complete type.
9065   if (RequireCompleteType(VD->getLocation(),
9066                           Context.getBaseElementType(Ty),
9067                           diag::err_typecheck_decl_incomplete_type)) {
9068     VD->setInvalidDecl();
9069     return;
9070   }
9071 
9072   // Require a non-abstract type.
9073   if (RequireNonAbstractType(VD->getLocation(), Ty,
9074                              diag::err_abstract_type_in_decl,
9075                              AbstractVariableType)) {
9076     VD->setInvalidDecl();
9077     return;
9078   }
9079 
9080   // Don't bother complaining about constructors or destructors,
9081   // though.
9082 }
9083 
9084 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9085                                   bool TypeMayContainAuto) {
9086   // If there is no declaration, there was an error parsing it. Just ignore it.
9087   if (!RealDecl)
9088     return;
9089 
9090   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9091     QualType Type = Var->getType();
9092 
9093     // C++11 [dcl.spec.auto]p3
9094     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9095       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9096         << Var->getDeclName() << Type;
9097       Var->setInvalidDecl();
9098       return;
9099     }
9100 
9101     // C++11 [class.static.data]p3: A static data member can be declared with
9102     // the constexpr specifier; if so, its declaration shall specify
9103     // a brace-or-equal-initializer.
9104     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9105     // the definition of a variable [...] or the declaration of a static data
9106     // member.
9107     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9108       if (Var->isStaticDataMember())
9109         Diag(Var->getLocation(),
9110              diag::err_constexpr_static_mem_var_requires_init)
9111           << Var->getDeclName();
9112       else
9113         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9114       Var->setInvalidDecl();
9115       return;
9116     }
9117 
9118     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9119     // be initialized.
9120     if (!Var->isInvalidDecl() &&
9121         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9122         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9123       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9124       Var->setInvalidDecl();
9125       return;
9126     }
9127 
9128     switch (Var->isThisDeclarationADefinition()) {
9129     case VarDecl::Definition:
9130       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9131         break;
9132 
9133       // We have an out-of-line definition of a static data member
9134       // that has an in-class initializer, so we type-check this like
9135       // a declaration.
9136       //
9137       // Fall through
9138 
9139     case VarDecl::DeclarationOnly:
9140       // It's only a declaration.
9141 
9142       // Block scope. C99 6.7p7: If an identifier for an object is
9143       // declared with no linkage (C99 6.2.2p6), the type for the
9144       // object shall be complete.
9145       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9146           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9147           RequireCompleteType(Var->getLocation(), Type,
9148                               diag::err_typecheck_decl_incomplete_type))
9149         Var->setInvalidDecl();
9150 
9151       // Make sure that the type is not abstract.
9152       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9153           RequireNonAbstractType(Var->getLocation(), Type,
9154                                  diag::err_abstract_type_in_decl,
9155                                  AbstractVariableType))
9156         Var->setInvalidDecl();
9157       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9158           Var->getStorageClass() == SC_PrivateExtern) {
9159         Diag(Var->getLocation(), diag::warn_private_extern);
9160         Diag(Var->getLocation(), diag::note_private_extern);
9161       }
9162 
9163       return;
9164 
9165     case VarDecl::TentativeDefinition:
9166       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9167       // object that has file scope without an initializer, and without a
9168       // storage-class specifier or with the storage-class specifier "static",
9169       // constitutes a tentative definition. Note: A tentative definition with
9170       // external linkage is valid (C99 6.2.2p5).
9171       if (!Var->isInvalidDecl()) {
9172         if (const IncompleteArrayType *ArrayT
9173                                     = Context.getAsIncompleteArrayType(Type)) {
9174           if (RequireCompleteType(Var->getLocation(),
9175                                   ArrayT->getElementType(),
9176                                   diag::err_illegal_decl_array_incomplete_type))
9177             Var->setInvalidDecl();
9178         } else if (Var->getStorageClass() == SC_Static) {
9179           // C99 6.9.2p3: If the declaration of an identifier for an object is
9180           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9181           // declared type shall not be an incomplete type.
9182           // NOTE: code such as the following
9183           //     static struct s;
9184           //     struct s { int a; };
9185           // is accepted by gcc. Hence here we issue a warning instead of
9186           // an error and we do not invalidate the static declaration.
9187           // NOTE: to avoid multiple warnings, only check the first declaration.
9188           if (Var->isFirstDecl())
9189             RequireCompleteType(Var->getLocation(), Type,
9190                                 diag::ext_typecheck_decl_incomplete_type);
9191         }
9192       }
9193 
9194       // Record the tentative definition; we're done.
9195       if (!Var->isInvalidDecl())
9196         TentativeDefinitions.push_back(Var);
9197       return;
9198     }
9199 
9200     // Provide a specific diagnostic for uninitialized variable
9201     // definitions with incomplete array type.
9202     if (Type->isIncompleteArrayType()) {
9203       Diag(Var->getLocation(),
9204            diag::err_typecheck_incomplete_array_needs_initializer);
9205       Var->setInvalidDecl();
9206       return;
9207     }
9208 
9209     // Provide a specific diagnostic for uninitialized variable
9210     // definitions with reference type.
9211     if (Type->isReferenceType()) {
9212       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9213         << Var->getDeclName()
9214         << SourceRange(Var->getLocation(), Var->getLocation());
9215       Var->setInvalidDecl();
9216       return;
9217     }
9218 
9219     // Do not attempt to type-check the default initializer for a
9220     // variable with dependent type.
9221     if (Type->isDependentType())
9222       return;
9223 
9224     if (Var->isInvalidDecl())
9225       return;
9226 
9227     if (!Var->hasAttr<AliasAttr>()) {
9228       if (RequireCompleteType(Var->getLocation(),
9229                               Context.getBaseElementType(Type),
9230                               diag::err_typecheck_decl_incomplete_type)) {
9231         Var->setInvalidDecl();
9232         return;
9233       }
9234     }
9235 
9236     // The variable can not have an abstract class type.
9237     if (RequireNonAbstractType(Var->getLocation(), Type,
9238                                diag::err_abstract_type_in_decl,
9239                                AbstractVariableType)) {
9240       Var->setInvalidDecl();
9241       return;
9242     }
9243 
9244     // Check for jumps past the implicit initializer.  C++0x
9245     // clarifies that this applies to a "variable with automatic
9246     // storage duration", not a "local variable".
9247     // C++11 [stmt.dcl]p3
9248     //   A program that jumps from a point where a variable with automatic
9249     //   storage duration is not in scope to a point where it is in scope is
9250     //   ill-formed unless the variable has scalar type, class type with a
9251     //   trivial default constructor and a trivial destructor, a cv-qualified
9252     //   version of one of these types, or an array of one of the preceding
9253     //   types and is declared without an initializer.
9254     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9255       if (const RecordType *Record
9256             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9257         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9258         // Mark the function for further checking even if the looser rules of
9259         // C++11 do not require such checks, so that we can diagnose
9260         // incompatibilities with C++98.
9261         if (!CXXRecord->isPOD())
9262           getCurFunction()->setHasBranchProtectedScope();
9263       }
9264     }
9265 
9266     // C++03 [dcl.init]p9:
9267     //   If no initializer is specified for an object, and the
9268     //   object is of (possibly cv-qualified) non-POD class type (or
9269     //   array thereof), the object shall be default-initialized; if
9270     //   the object is of const-qualified type, the underlying class
9271     //   type shall have a user-declared default
9272     //   constructor. Otherwise, if no initializer is specified for
9273     //   a non- static object, the object and its subobjects, if
9274     //   any, have an indeterminate initial value); if the object
9275     //   or any of its subobjects are of const-qualified type, the
9276     //   program is ill-formed.
9277     // C++0x [dcl.init]p11:
9278     //   If no initializer is specified for an object, the object is
9279     //   default-initialized; [...].
9280     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9281     InitializationKind Kind
9282       = InitializationKind::CreateDefault(Var->getLocation());
9283 
9284     InitializationSequence InitSeq(*this, Entity, Kind, None);
9285     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9286     if (Init.isInvalid())
9287       Var->setInvalidDecl();
9288     else if (Init.get()) {
9289       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9290       // This is important for template substitution.
9291       Var->setInitStyle(VarDecl::CallInit);
9292     }
9293 
9294     CheckCompleteVariableDeclaration(Var);
9295   }
9296 }
9297 
9298 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9299   VarDecl *VD = dyn_cast<VarDecl>(D);
9300   if (!VD) {
9301     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9302     D->setInvalidDecl();
9303     return;
9304   }
9305 
9306   VD->setCXXForRangeDecl(true);
9307 
9308   // for-range-declaration cannot be given a storage class specifier.
9309   int Error = -1;
9310   switch (VD->getStorageClass()) {
9311   case SC_None:
9312     break;
9313   case SC_Extern:
9314     Error = 0;
9315     break;
9316   case SC_Static:
9317     Error = 1;
9318     break;
9319   case SC_PrivateExtern:
9320     Error = 2;
9321     break;
9322   case SC_Auto:
9323     Error = 3;
9324     break;
9325   case SC_Register:
9326     Error = 4;
9327     break;
9328   case SC_OpenCLWorkGroupLocal:
9329     llvm_unreachable("Unexpected storage class");
9330   }
9331   if (VD->isConstexpr())
9332     Error = 5;
9333   if (Error != -1) {
9334     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9335       << VD->getDeclName() << Error;
9336     D->setInvalidDecl();
9337   }
9338 }
9339 
9340 StmtResult
9341 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9342                                  IdentifierInfo *Ident,
9343                                  ParsedAttributes &Attrs,
9344                                  SourceLocation AttrEnd) {
9345   // C++1y [stmt.iter]p1:
9346   //   A range-based for statement of the form
9347   //      for ( for-range-identifier : for-range-initializer ) statement
9348   //   is equivalent to
9349   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9350   DeclSpec DS(Attrs.getPool().getFactory());
9351 
9352   const char *PrevSpec;
9353   unsigned DiagID;
9354   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9355                      getPrintingPolicy());
9356 
9357   Declarator D(DS, Declarator::ForContext);
9358   D.SetIdentifier(Ident, IdentLoc);
9359   D.takeAttributes(Attrs, AttrEnd);
9360 
9361   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9362   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9363                 EmptyAttrs, IdentLoc);
9364   Decl *Var = ActOnDeclarator(S, D);
9365   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9366   FinalizeDeclaration(Var);
9367   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9368                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9369 }
9370 
9371 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9372   if (var->isInvalidDecl()) return;
9373 
9374   // In ARC, don't allow jumps past the implicit initialization of a
9375   // local retaining variable.
9376   if (getLangOpts().ObjCAutoRefCount &&
9377       var->hasLocalStorage()) {
9378     switch (var->getType().getObjCLifetime()) {
9379     case Qualifiers::OCL_None:
9380     case Qualifiers::OCL_ExplicitNone:
9381     case Qualifiers::OCL_Autoreleasing:
9382       break;
9383 
9384     case Qualifiers::OCL_Weak:
9385     case Qualifiers::OCL_Strong:
9386       getCurFunction()->setHasBranchProtectedScope();
9387       break;
9388     }
9389   }
9390 
9391   // Warn about externally-visible variables being defined without a
9392   // prior declaration.  We only want to do this for global
9393   // declarations, but we also specifically need to avoid doing it for
9394   // class members because the linkage of an anonymous class can
9395   // change if it's later given a typedef name.
9396   if (var->isThisDeclarationADefinition() &&
9397       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9398       var->isExternallyVisible() && var->hasLinkage() &&
9399       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9400                                   var->getLocation())) {
9401     // Find a previous declaration that's not a definition.
9402     VarDecl *prev = var->getPreviousDecl();
9403     while (prev && prev->isThisDeclarationADefinition())
9404       prev = prev->getPreviousDecl();
9405 
9406     if (!prev)
9407       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9408   }
9409 
9410   if (var->getTLSKind() == VarDecl::TLS_Static) {
9411     const Expr *Culprit;
9412     if (var->getType().isDestructedType()) {
9413       // GNU C++98 edits for __thread, [basic.start.term]p3:
9414       //   The type of an object with thread storage duration shall not
9415       //   have a non-trivial destructor.
9416       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9417       if (getLangOpts().CPlusPlus11)
9418         Diag(var->getLocation(), diag::note_use_thread_local);
9419     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9420                !var->getInit()->isConstantInitializer(
9421                    Context, var->getType()->isReferenceType(), &Culprit)) {
9422       // GNU C++98 edits for __thread, [basic.start.init]p4:
9423       //   An object of thread storage duration shall not require dynamic
9424       //   initialization.
9425       // FIXME: Need strict checking here.
9426       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9427         << Culprit->getSourceRange();
9428       if (getLangOpts().CPlusPlus11)
9429         Diag(var->getLocation(), diag::note_use_thread_local);
9430     }
9431 
9432   }
9433 
9434   if (var->isThisDeclarationADefinition() &&
9435       ActiveTemplateInstantiations.empty()) {
9436     PragmaStack<StringLiteral *> *Stack = nullptr;
9437     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9438     if (var->getType().isConstQualified())
9439       Stack = &ConstSegStack;
9440     else if (!var->getInit()) {
9441       Stack = &BSSSegStack;
9442       SectionFlags |= ASTContext::PSF_Write;
9443     } else {
9444       Stack = &DataSegStack;
9445       SectionFlags |= ASTContext::PSF_Write;
9446     }
9447     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9448       var->addAttr(
9449           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9450                                       Stack->CurrentValue->getString(),
9451                                       Stack->CurrentPragmaLocation));
9452     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9453       if (UnifySection(SA->getName(), SectionFlags, var))
9454         var->dropAttr<SectionAttr>();
9455 
9456     // Apply the init_seg attribute if this has an initializer.  If the
9457     // initializer turns out to not be dynamic, we'll end up ignoring this
9458     // attribute.
9459     if (CurInitSeg && var->getInit())
9460       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9461                                                CurInitSegLoc));
9462   }
9463 
9464   // All the following checks are C++ only.
9465   if (!getLangOpts().CPlusPlus) return;
9466 
9467   QualType type = var->getType();
9468   if (type->isDependentType()) return;
9469 
9470   // __block variables might require us to capture a copy-initializer.
9471   if (var->hasAttr<BlocksAttr>()) {
9472     // It's currently invalid to ever have a __block variable with an
9473     // array type; should we diagnose that here?
9474 
9475     // Regardless, we don't want to ignore array nesting when
9476     // constructing this copy.
9477     if (type->isStructureOrClassType()) {
9478       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9479       SourceLocation poi = var->getLocation();
9480       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9481       ExprResult result
9482         = PerformMoveOrCopyInitialization(
9483             InitializedEntity::InitializeBlock(poi, type, false),
9484             var, var->getType(), varRef, /*AllowNRVO=*/true);
9485       if (!result.isInvalid()) {
9486         result = MaybeCreateExprWithCleanups(result);
9487         Expr *init = result.getAs<Expr>();
9488         Context.setBlockVarCopyInits(var, init);
9489       }
9490     }
9491   }
9492 
9493   Expr *Init = var->getInit();
9494   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9495   QualType baseType = Context.getBaseElementType(type);
9496 
9497   if (!var->getDeclContext()->isDependentContext() &&
9498       Init && !Init->isValueDependent()) {
9499     if (IsGlobal && !var->isConstexpr() &&
9500         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9501                                     var->getLocation())) {
9502       // Warn about globals which don't have a constant initializer.  Don't
9503       // warn about globals with a non-trivial destructor because we already
9504       // warned about them.
9505       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9506       if (!(RD && !RD->hasTrivialDestructor()) &&
9507           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9508         Diag(var->getLocation(), diag::warn_global_constructor)
9509           << Init->getSourceRange();
9510     }
9511 
9512     if (var->isConstexpr()) {
9513       SmallVector<PartialDiagnosticAt, 8> Notes;
9514       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9515         SourceLocation DiagLoc = var->getLocation();
9516         // If the note doesn't add any useful information other than a source
9517         // location, fold it into the primary diagnostic.
9518         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9519               diag::note_invalid_subexpr_in_const_expr) {
9520           DiagLoc = Notes[0].first;
9521           Notes.clear();
9522         }
9523         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9524           << var << Init->getSourceRange();
9525         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9526           Diag(Notes[I].first, Notes[I].second);
9527       }
9528     } else if (var->isUsableInConstantExpressions(Context)) {
9529       // Check whether the initializer of a const variable of integral or
9530       // enumeration type is an ICE now, since we can't tell whether it was
9531       // initialized by a constant expression if we check later.
9532       var->checkInitIsICE();
9533     }
9534   }
9535 
9536   // Require the destructor.
9537   if (const RecordType *recordType = baseType->getAs<RecordType>())
9538     FinalizeVarWithDestructor(var, recordType);
9539 }
9540 
9541 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9542 /// any semantic actions necessary after any initializer has been attached.
9543 void
9544 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9545   // Note that we are no longer parsing the initializer for this declaration.
9546   ParsingInitForAutoVars.erase(ThisDecl);
9547 
9548   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9549   if (!VD)
9550     return;
9551 
9552   checkAttributesAfterMerging(*this, *VD);
9553 
9554   // Static locals inherit dll attributes from their function.
9555   if (VD->isStaticLocal()) {
9556     if (FunctionDecl *FD =
9557             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9558       if (Attr *A = getDLLAttr(FD)) {
9559         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9560         NewAttr->setInherited(true);
9561         VD->addAttr(NewAttr);
9562       }
9563     }
9564   }
9565 
9566   // Grab the dllimport or dllexport attribute off of the VarDecl.
9567   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9568 
9569   // Imported static data members cannot be defined out-of-line.
9570   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9571     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9572         VD->isThisDeclarationADefinition()) {
9573       // We allow definitions of dllimport class template static data members
9574       // with a warning.
9575       CXXRecordDecl *Context =
9576         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9577       bool IsClassTemplateMember =
9578           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9579           Context->getDescribedClassTemplate();
9580 
9581       Diag(VD->getLocation(),
9582            IsClassTemplateMember
9583                ? diag::warn_attribute_dllimport_static_field_definition
9584                : diag::err_attribute_dllimport_static_field_definition);
9585       Diag(IA->getLocation(), diag::note_attribute);
9586       if (!IsClassTemplateMember)
9587         VD->setInvalidDecl();
9588     }
9589   }
9590 
9591   // dllimport/dllexport variables cannot be thread local, their TLS index
9592   // isn't exported with the variable.
9593   if (DLLAttr && VD->getTLSKind()) {
9594     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9595                                                                   << DLLAttr;
9596     VD->setInvalidDecl();
9597   }
9598 
9599   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9600     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9601       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9602       VD->dropAttr<UsedAttr>();
9603     }
9604   }
9605 
9606   if (!VD->isInvalidDecl() &&
9607       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9608     if (const VarDecl *Def = VD->getDefinition()) {
9609       if (Def->hasAttr<AliasAttr>()) {
9610         Diag(VD->getLocation(), diag::err_tentative_after_alias)
9611             << VD->getDeclName();
9612         Diag(Def->getLocation(), diag::note_previous_definition);
9613         VD->setInvalidDecl();
9614       }
9615     }
9616   }
9617 
9618   const DeclContext *DC = VD->getDeclContext();
9619   // If there's a #pragma GCC visibility in scope, and this isn't a class
9620   // member, set the visibility of this variable.
9621   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9622     AddPushedVisibilityAttribute(VD);
9623 
9624   // FIXME: Warn on unused templates.
9625   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9626       !isa<VarTemplatePartialSpecializationDecl>(VD))
9627     MarkUnusedFileScopedDecl(VD);
9628 
9629   // Now we have parsed the initializer and can update the table of magic
9630   // tag values.
9631   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9632       !VD->getType()->isIntegralOrEnumerationType())
9633     return;
9634 
9635   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9636     const Expr *MagicValueExpr = VD->getInit();
9637     if (!MagicValueExpr) {
9638       continue;
9639     }
9640     llvm::APSInt MagicValueInt;
9641     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9642       Diag(I->getRange().getBegin(),
9643            diag::err_type_tag_for_datatype_not_ice)
9644         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9645       continue;
9646     }
9647     if (MagicValueInt.getActiveBits() > 64) {
9648       Diag(I->getRange().getBegin(),
9649            diag::err_type_tag_for_datatype_too_large)
9650         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9651       continue;
9652     }
9653     uint64_t MagicValue = MagicValueInt.getZExtValue();
9654     RegisterTypeTagForDatatype(I->getArgumentKind(),
9655                                MagicValue,
9656                                I->getMatchingCType(),
9657                                I->getLayoutCompatible(),
9658                                I->getMustBeNull());
9659   }
9660 }
9661 
9662 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9663                                                    ArrayRef<Decl *> Group) {
9664   SmallVector<Decl*, 8> Decls;
9665 
9666   if (DS.isTypeSpecOwned())
9667     Decls.push_back(DS.getRepAsDecl());
9668 
9669   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9670   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9671     if (Decl *D = Group[i]) {
9672       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9673         if (!FirstDeclaratorInGroup)
9674           FirstDeclaratorInGroup = DD;
9675       Decls.push_back(D);
9676     }
9677 
9678   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9679     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9680       HandleTagNumbering(*this, Tag, S);
9681       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9682         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9683     }
9684   }
9685 
9686   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9687 }
9688 
9689 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9690 /// group, performing any necessary semantic checking.
9691 Sema::DeclGroupPtrTy
9692 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9693                            bool TypeMayContainAuto) {
9694   // C++0x [dcl.spec.auto]p7:
9695   //   If the type deduced for the template parameter U is not the same in each
9696   //   deduction, the program is ill-formed.
9697   // FIXME: When initializer-list support is added, a distinction is needed
9698   // between the deduced type U and the deduced type which 'auto' stands for.
9699   //   auto a = 0, b = { 1, 2, 3 };
9700   // is legal because the deduced type U is 'int' in both cases.
9701   if (TypeMayContainAuto && Group.size() > 1) {
9702     QualType Deduced;
9703     CanQualType DeducedCanon;
9704     VarDecl *DeducedDecl = nullptr;
9705     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9706       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9707         AutoType *AT = D->getType()->getContainedAutoType();
9708         // Don't reissue diagnostics when instantiating a template.
9709         if (AT && D->isInvalidDecl())
9710           break;
9711         QualType U = AT ? AT->getDeducedType() : QualType();
9712         if (!U.isNull()) {
9713           CanQualType UCanon = Context.getCanonicalType(U);
9714           if (Deduced.isNull()) {
9715             Deduced = U;
9716             DeducedCanon = UCanon;
9717             DeducedDecl = D;
9718           } else if (DeducedCanon != UCanon) {
9719             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9720                  diag::err_auto_different_deductions)
9721               << (AT->isDecltypeAuto() ? 1 : 0)
9722               << Deduced << DeducedDecl->getDeclName()
9723               << U << D->getDeclName()
9724               << DeducedDecl->getInit()->getSourceRange()
9725               << D->getInit()->getSourceRange();
9726             D->setInvalidDecl();
9727             break;
9728           }
9729         }
9730       }
9731     }
9732   }
9733 
9734   ActOnDocumentableDecls(Group);
9735 
9736   return DeclGroupPtrTy::make(
9737       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9738 }
9739 
9740 void Sema::ActOnDocumentableDecl(Decl *D) {
9741   ActOnDocumentableDecls(D);
9742 }
9743 
9744 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9745   // Don't parse the comment if Doxygen diagnostics are ignored.
9746   if (Group.empty() || !Group[0])
9747    return;
9748 
9749   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9750     return;
9751 
9752   if (Group.size() >= 2) {
9753     // This is a decl group.  Normally it will contain only declarations
9754     // produced from declarator list.  But in case we have any definitions or
9755     // additional declaration references:
9756     //   'typedef struct S {} S;'
9757     //   'typedef struct S *S;'
9758     //   'struct S *pS;'
9759     // FinalizeDeclaratorGroup adds these as separate declarations.
9760     Decl *MaybeTagDecl = Group[0];
9761     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9762       Group = Group.slice(1);
9763     }
9764   }
9765 
9766   // See if there are any new comments that are not attached to a decl.
9767   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9768   if (!Comments.empty() &&
9769       !Comments.back()->isAttached()) {
9770     // There is at least one comment that not attached to a decl.
9771     // Maybe it should be attached to one of these decls?
9772     //
9773     // Note that this way we pick up not only comments that precede the
9774     // declaration, but also comments that *follow* the declaration -- thanks to
9775     // the lookahead in the lexer: we've consumed the semicolon and looked
9776     // ahead through comments.
9777     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9778       Context.getCommentForDecl(Group[i], &PP);
9779   }
9780 }
9781 
9782 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9783 /// to introduce parameters into function prototype scope.
9784 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9785   const DeclSpec &DS = D.getDeclSpec();
9786 
9787   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9788 
9789   // C++03 [dcl.stc]p2 also permits 'auto'.
9790   StorageClass SC = SC_None;
9791   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9792     SC = SC_Register;
9793   } else if (getLangOpts().CPlusPlus &&
9794              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9795     SC = SC_Auto;
9796   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9797     Diag(DS.getStorageClassSpecLoc(),
9798          diag::err_invalid_storage_class_in_func_decl);
9799     D.getMutableDeclSpec().ClearStorageClassSpecs();
9800   }
9801 
9802   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9803     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9804       << DeclSpec::getSpecifierName(TSCS);
9805   if (DS.isConstexprSpecified())
9806     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9807       << 0;
9808 
9809   DiagnoseFunctionSpecifiers(DS);
9810 
9811   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9812   QualType parmDeclType = TInfo->getType();
9813 
9814   if (getLangOpts().CPlusPlus) {
9815     // Check that there are no default arguments inside the type of this
9816     // parameter.
9817     CheckExtraCXXDefaultArguments(D);
9818 
9819     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9820     if (D.getCXXScopeSpec().isSet()) {
9821       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9822         << D.getCXXScopeSpec().getRange();
9823       D.getCXXScopeSpec().clear();
9824     }
9825   }
9826 
9827   // Ensure we have a valid name
9828   IdentifierInfo *II = nullptr;
9829   if (D.hasName()) {
9830     II = D.getIdentifier();
9831     if (!II) {
9832       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9833         << GetNameForDeclarator(D).getName();
9834       D.setInvalidType(true);
9835     }
9836   }
9837 
9838   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9839   if (II) {
9840     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9841                    ForRedeclaration);
9842     LookupName(R, S);
9843     if (R.isSingleResult()) {
9844       NamedDecl *PrevDecl = R.getFoundDecl();
9845       if (PrevDecl->isTemplateParameter()) {
9846         // Maybe we will complain about the shadowed template parameter.
9847         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9848         // Just pretend that we didn't see the previous declaration.
9849         PrevDecl = nullptr;
9850       } else if (S->isDeclScope(PrevDecl)) {
9851         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9852         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9853 
9854         // Recover by removing the name
9855         II = nullptr;
9856         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9857         D.setInvalidType(true);
9858       }
9859     }
9860   }
9861 
9862   // Temporarily put parameter variables in the translation unit, not
9863   // the enclosing context.  This prevents them from accidentally
9864   // looking like class members in C++.
9865   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9866                                     D.getLocStart(),
9867                                     D.getIdentifierLoc(), II,
9868                                     parmDeclType, TInfo,
9869                                     SC);
9870 
9871   if (D.isInvalidType())
9872     New->setInvalidDecl();
9873 
9874   assert(S->isFunctionPrototypeScope());
9875   assert(S->getFunctionPrototypeDepth() >= 1);
9876   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9877                     S->getNextFunctionPrototypeIndex());
9878 
9879   // Add the parameter declaration into this scope.
9880   S->AddDecl(New);
9881   if (II)
9882     IdResolver.AddDecl(New);
9883 
9884   ProcessDeclAttributes(S, New, D);
9885 
9886   if (D.getDeclSpec().isModulePrivateSpecified())
9887     Diag(New->getLocation(), diag::err_module_private_local)
9888       << 1 << New->getDeclName()
9889       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9890       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9891 
9892   if (New->hasAttr<BlocksAttr>()) {
9893     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9894   }
9895   return New;
9896 }
9897 
9898 /// \brief Synthesizes a variable for a parameter arising from a
9899 /// typedef.
9900 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9901                                               SourceLocation Loc,
9902                                               QualType T) {
9903   /* FIXME: setting StartLoc == Loc.
9904      Would it be worth to modify callers so as to provide proper source
9905      location for the unnamed parameters, embedding the parameter's type? */
9906   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9907                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9908                                            SC_None, nullptr);
9909   Param->setImplicit();
9910   return Param;
9911 }
9912 
9913 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9914                                     ParmVarDecl * const *ParamEnd) {
9915   // Don't diagnose unused-parameter errors in template instantiations; we
9916   // will already have done so in the template itself.
9917   if (!ActiveTemplateInstantiations.empty())
9918     return;
9919 
9920   for (; Param != ParamEnd; ++Param) {
9921     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9922         !(*Param)->hasAttr<UnusedAttr>()) {
9923       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9924         << (*Param)->getDeclName();
9925     }
9926   }
9927 }
9928 
9929 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9930                                                   ParmVarDecl * const *ParamEnd,
9931                                                   QualType ReturnTy,
9932                                                   NamedDecl *D) {
9933   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9934     return;
9935 
9936   // Warn if the return value is pass-by-value and larger than the specified
9937   // threshold.
9938   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9939     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9940     if (Size > LangOpts.NumLargeByValueCopy)
9941       Diag(D->getLocation(), diag::warn_return_value_size)
9942           << D->getDeclName() << Size;
9943   }
9944 
9945   // Warn if any parameter is pass-by-value and larger than the specified
9946   // threshold.
9947   for (; Param != ParamEnd; ++Param) {
9948     QualType T = (*Param)->getType();
9949     if (T->isDependentType() || !T.isPODType(Context))
9950       continue;
9951     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9952     if (Size > LangOpts.NumLargeByValueCopy)
9953       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9954           << (*Param)->getDeclName() << Size;
9955   }
9956 }
9957 
9958 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9959                                   SourceLocation NameLoc, IdentifierInfo *Name,
9960                                   QualType T, TypeSourceInfo *TSInfo,
9961                                   StorageClass SC) {
9962   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9963   if (getLangOpts().ObjCAutoRefCount &&
9964       T.getObjCLifetime() == Qualifiers::OCL_None &&
9965       T->isObjCLifetimeType()) {
9966 
9967     Qualifiers::ObjCLifetime lifetime;
9968 
9969     // Special cases for arrays:
9970     //   - if it's const, use __unsafe_unretained
9971     //   - otherwise, it's an error
9972     if (T->isArrayType()) {
9973       if (!T.isConstQualified()) {
9974         DelayedDiagnostics.add(
9975             sema::DelayedDiagnostic::makeForbiddenType(
9976             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9977       }
9978       lifetime = Qualifiers::OCL_ExplicitNone;
9979     } else {
9980       lifetime = T->getObjCARCImplicitLifetime();
9981     }
9982     T = Context.getLifetimeQualifiedType(T, lifetime);
9983   }
9984 
9985   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9986                                          Context.getAdjustedParameterType(T),
9987                                          TSInfo, SC, nullptr);
9988 
9989   // Parameters can not be abstract class types.
9990   // For record types, this is done by the AbstractClassUsageDiagnoser once
9991   // the class has been completely parsed.
9992   if (!CurContext->isRecord() &&
9993       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9994                              AbstractParamType))
9995     New->setInvalidDecl();
9996 
9997   // Parameter declarators cannot be interface types. All ObjC objects are
9998   // passed by reference.
9999   if (T->isObjCObjectType()) {
10000     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10001     Diag(NameLoc,
10002          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10003       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10004     T = Context.getObjCObjectPointerType(T);
10005     New->setType(T);
10006   }
10007 
10008   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10009   // duration shall not be qualified by an address-space qualifier."
10010   // Since all parameters have automatic store duration, they can not have
10011   // an address space.
10012   if (T.getAddressSpace() != 0) {
10013     // OpenCL allows function arguments declared to be an array of a type
10014     // to be qualified with an address space.
10015     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10016       Diag(NameLoc, diag::err_arg_with_address_space);
10017       New->setInvalidDecl();
10018     }
10019   }
10020 
10021   return New;
10022 }
10023 
10024 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10025                                            SourceLocation LocAfterDecls) {
10026   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10027 
10028   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10029   // for a K&R function.
10030   if (!FTI.hasPrototype) {
10031     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10032       --i;
10033       if (FTI.Params[i].Param == nullptr) {
10034         SmallString<256> Code;
10035         llvm::raw_svector_ostream(Code)
10036             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10037         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10038             << FTI.Params[i].Ident
10039             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10040 
10041         // Implicitly declare the argument as type 'int' for lack of a better
10042         // type.
10043         AttributeFactory attrs;
10044         DeclSpec DS(attrs);
10045         const char* PrevSpec; // unused
10046         unsigned DiagID; // unused
10047         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10048                            DiagID, Context.getPrintingPolicy());
10049         // Use the identifier location for the type source range.
10050         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10051         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10052         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10053         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10054         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10055       }
10056     }
10057   }
10058 }
10059 
10060 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10061   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10062   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10063   Scope *ParentScope = FnBodyScope->getParent();
10064 
10065   D.setFunctionDefinitionKind(FDK_Definition);
10066   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10067   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10068 }
10069 
10070 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10071   Consumer.HandleInlineMethodDefinition(D);
10072 }
10073 
10074 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10075                              const FunctionDecl*& PossibleZeroParamPrototype) {
10076   // Don't warn about invalid declarations.
10077   if (FD->isInvalidDecl())
10078     return false;
10079 
10080   // Or declarations that aren't global.
10081   if (!FD->isGlobal())
10082     return false;
10083 
10084   // Don't warn about C++ member functions.
10085   if (isa<CXXMethodDecl>(FD))
10086     return false;
10087 
10088   // Don't warn about 'main'.
10089   if (FD->isMain())
10090     return false;
10091 
10092   // Don't warn about inline functions.
10093   if (FD->isInlined())
10094     return false;
10095 
10096   // Don't warn about function templates.
10097   if (FD->getDescribedFunctionTemplate())
10098     return false;
10099 
10100   // Don't warn about function template specializations.
10101   if (FD->isFunctionTemplateSpecialization())
10102     return false;
10103 
10104   // Don't warn for OpenCL kernels.
10105   if (FD->hasAttr<OpenCLKernelAttr>())
10106     return false;
10107 
10108   bool MissingPrototype = true;
10109   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10110        Prev; Prev = Prev->getPreviousDecl()) {
10111     // Ignore any declarations that occur in function or method
10112     // scope, because they aren't visible from the header.
10113     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10114       continue;
10115 
10116     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10117     if (FD->getNumParams() == 0)
10118       PossibleZeroParamPrototype = Prev;
10119     break;
10120   }
10121 
10122   return MissingPrototype;
10123 }
10124 
10125 void
10126 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10127                                    const FunctionDecl *EffectiveDefinition) {
10128   // Don't complain if we're in GNU89 mode and the previous definition
10129   // was an extern inline function.
10130   const FunctionDecl *Definition = EffectiveDefinition;
10131   if (!Definition)
10132     if (!FD->isDefined(Definition))
10133       return;
10134 
10135   if (canRedefineFunction(Definition, getLangOpts()))
10136     return;
10137 
10138   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10139       Definition->getStorageClass() == SC_Extern)
10140     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10141         << FD->getDeclName() << getLangOpts().CPlusPlus;
10142   else
10143     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10144 
10145   Diag(Definition->getLocation(), diag::note_previous_definition);
10146   FD->setInvalidDecl();
10147 }
10148 
10149 
10150 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10151                                    Sema &S) {
10152   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10153 
10154   LambdaScopeInfo *LSI = S.PushLambdaScope();
10155   LSI->CallOperator = CallOperator;
10156   LSI->Lambda = LambdaClass;
10157   LSI->ReturnType = CallOperator->getReturnType();
10158   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10159 
10160   if (LCD == LCD_None)
10161     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10162   else if (LCD == LCD_ByCopy)
10163     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10164   else if (LCD == LCD_ByRef)
10165     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10166   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10167 
10168   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10169   LSI->Mutable = !CallOperator->isConst();
10170 
10171   // Add the captures to the LSI so they can be noted as already
10172   // captured within tryCaptureVar.
10173   auto I = LambdaClass->field_begin();
10174   for (const auto &C : LambdaClass->captures()) {
10175     if (C.capturesVariable()) {
10176       VarDecl *VD = C.getCapturedVar();
10177       if (VD->isInitCapture())
10178         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10179       QualType CaptureType = VD->getType();
10180       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10181       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10182           /*RefersToCapturedVariable*/true, C.getLocation(),
10183           /*EllipsisLoc*/C.isPackExpansion()
10184                          ? C.getEllipsisLoc() : SourceLocation(),
10185           CaptureType, /*Expr*/ nullptr);
10186 
10187     } else if (C.capturesThis()) {
10188       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10189                               S.getCurrentThisType(), /*Expr*/ nullptr);
10190     } else {
10191       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10192     }
10193     ++I;
10194   }
10195 }
10196 
10197 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10198   // Clear the last template instantiation error context.
10199   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10200 
10201   if (!D)
10202     return D;
10203   FunctionDecl *FD = nullptr;
10204 
10205   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10206     FD = FunTmpl->getTemplatedDecl();
10207   else
10208     FD = cast<FunctionDecl>(D);
10209   // If we are instantiating a generic lambda call operator, push
10210   // a LambdaScopeInfo onto the function stack.  But use the information
10211   // that's already been calculated (ActOnLambdaExpr) to prime the current
10212   // LambdaScopeInfo.
10213   // When the template operator is being specialized, the LambdaScopeInfo,
10214   // has to be properly restored so that tryCaptureVariable doesn't try
10215   // and capture any new variables. In addition when calculating potential
10216   // captures during transformation of nested lambdas, it is necessary to
10217   // have the LSI properly restored.
10218   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10219     assert(ActiveTemplateInstantiations.size() &&
10220       "There should be an active template instantiation on the stack "
10221       "when instantiating a generic lambda!");
10222     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10223   }
10224   else
10225     // Enter a new function scope
10226     PushFunctionScope();
10227 
10228   // See if this is a redefinition.
10229   if (!FD->isLateTemplateParsed())
10230     CheckForFunctionRedefinition(FD);
10231 
10232   // Builtin functions cannot be defined.
10233   if (unsigned BuiltinID = FD->getBuiltinID()) {
10234     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10235         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10236       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10237       FD->setInvalidDecl();
10238     }
10239   }
10240 
10241   // The return type of a function definition must be complete
10242   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10243   QualType ResultType = FD->getReturnType();
10244   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10245       !FD->isInvalidDecl() &&
10246       RequireCompleteType(FD->getLocation(), ResultType,
10247                           diag::err_func_def_incomplete_result))
10248     FD->setInvalidDecl();
10249 
10250   // GNU warning -Wmissing-prototypes:
10251   //   Warn if a global function is defined without a previous
10252   //   prototype declaration. This warning is issued even if the
10253   //   definition itself provides a prototype. The aim is to detect
10254   //   global functions that fail to be declared in header files.
10255   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10256   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10257     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10258 
10259     if (PossibleZeroParamPrototype) {
10260       // We found a declaration that is not a prototype,
10261       // but that could be a zero-parameter prototype
10262       if (TypeSourceInfo *TI =
10263               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10264         TypeLoc TL = TI->getTypeLoc();
10265         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10266           Diag(PossibleZeroParamPrototype->getLocation(),
10267                diag::note_declaration_not_a_prototype)
10268             << PossibleZeroParamPrototype
10269             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10270       }
10271     }
10272   }
10273 
10274   if (FnBodyScope)
10275     PushDeclContext(FnBodyScope, FD);
10276 
10277   // Check the validity of our function parameters
10278   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10279                            /*CheckParameterNames=*/true);
10280 
10281   // Introduce our parameters into the function scope
10282   for (auto Param : FD->params()) {
10283     Param->setOwningFunction(FD);
10284 
10285     // If this has an identifier, add it to the scope stack.
10286     if (Param->getIdentifier() && FnBodyScope) {
10287       CheckShadow(FnBodyScope, Param);
10288 
10289       PushOnScopeChains(Param, FnBodyScope);
10290     }
10291   }
10292 
10293   // If we had any tags defined in the function prototype,
10294   // introduce them into the function scope.
10295   if (FnBodyScope) {
10296     for (ArrayRef<NamedDecl *>::iterator
10297              I = FD->getDeclsInPrototypeScope().begin(),
10298              E = FD->getDeclsInPrototypeScope().end();
10299          I != E; ++I) {
10300       NamedDecl *D = *I;
10301 
10302       // Some of these decls (like enums) may have been pinned to the translation unit
10303       // for lack of a real context earlier. If so, remove from the translation unit
10304       // and reattach to the current context.
10305       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10306         // Is the decl actually in the context?
10307         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10308           if (DI == D) {
10309             Context.getTranslationUnitDecl()->removeDecl(D);
10310             break;
10311           }
10312         }
10313         // Either way, reassign the lexical decl context to our FunctionDecl.
10314         D->setLexicalDeclContext(CurContext);
10315       }
10316 
10317       // If the decl has a non-null name, make accessible in the current scope.
10318       if (!D->getName().empty())
10319         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10320 
10321       // Similarly, dive into enums and fish their constants out, making them
10322       // accessible in this scope.
10323       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10324         for (auto *EI : ED->enumerators())
10325           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10326       }
10327     }
10328   }
10329 
10330   // Ensure that the function's exception specification is instantiated.
10331   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10332     ResolveExceptionSpec(D->getLocation(), FPT);
10333 
10334   // dllimport cannot be applied to non-inline function definitions.
10335   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10336       !FD->isTemplateInstantiation()) {
10337     assert(!FD->hasAttr<DLLExportAttr>());
10338     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10339     FD->setInvalidDecl();
10340     return D;
10341   }
10342   // We want to attach documentation to original Decl (which might be
10343   // a function template).
10344   ActOnDocumentableDecl(D);
10345   if (getCurLexicalContext()->isObjCContainer() &&
10346       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10347       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10348     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10349 
10350   return D;
10351 }
10352 
10353 /// \brief Given the set of return statements within a function body,
10354 /// compute the variables that are subject to the named return value
10355 /// optimization.
10356 ///
10357 /// Each of the variables that is subject to the named return value
10358 /// optimization will be marked as NRVO variables in the AST, and any
10359 /// return statement that has a marked NRVO variable as its NRVO candidate can
10360 /// use the named return value optimization.
10361 ///
10362 /// This function applies a very simplistic algorithm for NRVO: if every return
10363 /// statement in the scope of a variable has the same NRVO candidate, that
10364 /// candidate is an NRVO variable.
10365 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10366   ReturnStmt **Returns = Scope->Returns.data();
10367 
10368   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10369     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10370       if (!NRVOCandidate->isNRVOVariable())
10371         Returns[I]->setNRVOCandidate(nullptr);
10372     }
10373   }
10374 }
10375 
10376 bool Sema::canDelayFunctionBody(const Declarator &D) {
10377   // We can't delay parsing the body of a constexpr function template (yet).
10378   if (D.getDeclSpec().isConstexprSpecified())
10379     return false;
10380 
10381   // We can't delay parsing the body of a function template with a deduced
10382   // return type (yet).
10383   if (D.getDeclSpec().containsPlaceholderType()) {
10384     // If the placeholder introduces a non-deduced trailing return type,
10385     // we can still delay parsing it.
10386     if (D.getNumTypeObjects()) {
10387       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10388       if (Outer.Kind == DeclaratorChunk::Function &&
10389           Outer.Fun.hasTrailingReturnType()) {
10390         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10391         return Ty.isNull() || !Ty->isUndeducedType();
10392       }
10393     }
10394     return false;
10395   }
10396 
10397   return true;
10398 }
10399 
10400 bool Sema::canSkipFunctionBody(Decl *D) {
10401   // We cannot skip the body of a function (or function template) which is
10402   // constexpr, since we may need to evaluate its body in order to parse the
10403   // rest of the file.
10404   // We cannot skip the body of a function with an undeduced return type,
10405   // because any callers of that function need to know the type.
10406   if (const FunctionDecl *FD = D->getAsFunction())
10407     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10408       return false;
10409   return Consumer.shouldSkipFunctionBody(D);
10410 }
10411 
10412 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10413   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10414     FD->setHasSkippedBody();
10415   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10416     MD->setHasSkippedBody();
10417   return ActOnFinishFunctionBody(Decl, nullptr);
10418 }
10419 
10420 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10421   return ActOnFinishFunctionBody(D, BodyArg, false);
10422 }
10423 
10424 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10425                                     bool IsInstantiation) {
10426   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10427 
10428   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10429   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10430 
10431   if (FD) {
10432     FD->setBody(Body);
10433 
10434     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10435         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10436       // If the function has a deduced result type but contains no 'return'
10437       // statements, the result type as written must be exactly 'auto', and
10438       // the deduced result type is 'void'.
10439       if (!FD->getReturnType()->getAs<AutoType>()) {
10440         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10441             << FD->getReturnType();
10442         FD->setInvalidDecl();
10443       } else {
10444         // Substitute 'void' for the 'auto' in the type.
10445         TypeLoc ResultType = getReturnTypeLoc(FD);
10446         Context.adjustDeducedFunctionResultType(
10447             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10448       }
10449     }
10450 
10451     // The only way to be included in UndefinedButUsed is if there is an
10452     // ODR use before the definition. Avoid the expensive map lookup if this
10453     // is the first declaration.
10454     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10455       if (!FD->isExternallyVisible())
10456         UndefinedButUsed.erase(FD);
10457       else if (FD->isInlined() &&
10458                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10459                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10460         UndefinedButUsed.erase(FD);
10461     }
10462 
10463     // If the function implicitly returns zero (like 'main') or is naked,
10464     // don't complain about missing return statements.
10465     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10466       WP.disableCheckFallThrough();
10467 
10468     // MSVC permits the use of pure specifier (=0) on function definition,
10469     // defined at class scope, warn about this non-standard construct.
10470     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10471       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10472 
10473     if (!FD->isInvalidDecl()) {
10474       // Don't diagnose unused parameters of defaulted or deleted functions.
10475       if (Body)
10476         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10477       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10478                                              FD->getReturnType(), FD);
10479 
10480       // If this is a constructor, we need a vtable.
10481       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10482         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10483 
10484       // Try to apply the named return value optimization. We have to check
10485       // if we can do this here because lambdas keep return statements around
10486       // to deduce an implicit return type.
10487       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10488           !FD->isDependentContext())
10489         computeNRVO(Body, getCurFunction());
10490     }
10491 
10492     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10493            "Function parsing confused");
10494   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10495     assert(MD == getCurMethodDecl() && "Method parsing confused");
10496     MD->setBody(Body);
10497     if (!MD->isInvalidDecl()) {
10498       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10499       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10500                                              MD->getReturnType(), MD);
10501 
10502       if (Body)
10503         computeNRVO(Body, getCurFunction());
10504     }
10505     if (getCurFunction()->ObjCShouldCallSuper) {
10506       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10507         << MD->getSelector().getAsString();
10508       getCurFunction()->ObjCShouldCallSuper = false;
10509     }
10510     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10511       const ObjCMethodDecl *InitMethod = nullptr;
10512       bool isDesignated =
10513           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10514       assert(isDesignated && InitMethod);
10515       (void)isDesignated;
10516 
10517       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10518         auto IFace = MD->getClassInterface();
10519         if (!IFace)
10520           return false;
10521         auto SuperD = IFace->getSuperClass();
10522         if (!SuperD)
10523           return false;
10524         return SuperD->getIdentifier() ==
10525             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10526       };
10527       // Don't issue this warning for unavailable inits or direct subclasses
10528       // of NSObject.
10529       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10530         Diag(MD->getLocation(),
10531              diag::warn_objc_designated_init_missing_super_call);
10532         Diag(InitMethod->getLocation(),
10533              diag::note_objc_designated_init_marked_here);
10534       }
10535       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10536     }
10537     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10538       // Don't issue this warning for unavaialable inits.
10539       if (!MD->isUnavailable())
10540         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10541       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10542     }
10543   } else {
10544     return nullptr;
10545   }
10546 
10547   assert(!getCurFunction()->ObjCShouldCallSuper &&
10548          "This should only be set for ObjC methods, which should have been "
10549          "handled in the block above.");
10550 
10551   // Verify and clean out per-function state.
10552   if (Body) {
10553     // C++ constructors that have function-try-blocks can't have return
10554     // statements in the handlers of that block. (C++ [except.handle]p14)
10555     // Verify this.
10556     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10557       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10558 
10559     // Verify that gotos and switch cases don't jump into scopes illegally.
10560     if (getCurFunction()->NeedsScopeChecking() &&
10561         !PP.isCodeCompletionEnabled())
10562       DiagnoseInvalidJumps(Body);
10563 
10564     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10565       if (!Destructor->getParent()->isDependentType())
10566         CheckDestructor(Destructor);
10567 
10568       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10569                                              Destructor->getParent());
10570     }
10571 
10572     // If any errors have occurred, clear out any temporaries that may have
10573     // been leftover. This ensures that these temporaries won't be picked up for
10574     // deletion in some later function.
10575     if (getDiagnostics().hasErrorOccurred() ||
10576         getDiagnostics().getSuppressAllDiagnostics()) {
10577       DiscardCleanupsInEvaluationContext();
10578     }
10579     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10580         !isa<FunctionTemplateDecl>(dcl)) {
10581       // Since the body is valid, issue any analysis-based warnings that are
10582       // enabled.
10583       ActivePolicy = &WP;
10584     }
10585 
10586     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10587         (!CheckConstexprFunctionDecl(FD) ||
10588          !CheckConstexprFunctionBody(FD, Body)))
10589       FD->setInvalidDecl();
10590 
10591     if (FD && FD->hasAttr<NakedAttr>()) {
10592       for (const Stmt *S : Body->children()) {
10593         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10594           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10595           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10596           FD->setInvalidDecl();
10597           break;
10598         }
10599       }
10600     }
10601 
10602     assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
10603            && "Leftover temporaries in function");
10604     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10605     assert(MaybeODRUseExprs.empty() &&
10606            "Leftover expressions for odr-use checking");
10607   }
10608 
10609   if (!IsInstantiation)
10610     PopDeclContext();
10611 
10612   PopFunctionScopeInfo(ActivePolicy, dcl);
10613   // If any errors have occurred, clear out any temporaries that may have
10614   // been leftover. This ensures that these temporaries won't be picked up for
10615   // deletion in some later function.
10616   if (getDiagnostics().hasErrorOccurred()) {
10617     DiscardCleanupsInEvaluationContext();
10618   }
10619 
10620   return dcl;
10621 }
10622 
10623 
10624 /// When we finish delayed parsing of an attribute, we must attach it to the
10625 /// relevant Decl.
10626 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10627                                        ParsedAttributes &Attrs) {
10628   // Always attach attributes to the underlying decl.
10629   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10630     D = TD->getTemplatedDecl();
10631   ProcessDeclAttributeList(S, D, Attrs.getList());
10632 
10633   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10634     if (Method->isStatic())
10635       checkThisInStaticMemberFunctionAttributes(Method);
10636 }
10637 
10638 
10639 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10640 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10641 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10642                                           IdentifierInfo &II, Scope *S) {
10643   // Before we produce a declaration for an implicitly defined
10644   // function, see whether there was a locally-scoped declaration of
10645   // this name as a function or variable. If so, use that
10646   // (non-visible) declaration, and complain about it.
10647   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10648     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10649     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10650     return ExternCPrev;
10651   }
10652 
10653   // Extension in C99.  Legal in C90, but warn about it.
10654   unsigned diag_id;
10655   if (II.getName().startswith("__builtin_"))
10656     diag_id = diag::warn_builtin_unknown;
10657   else if (getLangOpts().C99)
10658     diag_id = diag::ext_implicit_function_decl;
10659   else
10660     diag_id = diag::warn_implicit_function_decl;
10661   Diag(Loc, diag_id) << &II;
10662 
10663   // Because typo correction is expensive, only do it if the implicit
10664   // function declaration is going to be treated as an error.
10665   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10666     TypoCorrection Corrected;
10667     if (S &&
10668         (Corrected = CorrectTypo(
10669              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10670              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10671       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10672                    /*ErrorRecovery*/false);
10673   }
10674 
10675   // Set a Declarator for the implicit definition: int foo();
10676   const char *Dummy;
10677   AttributeFactory attrFactory;
10678   DeclSpec DS(attrFactory);
10679   unsigned DiagID;
10680   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10681                                   Context.getPrintingPolicy());
10682   (void)Error; // Silence warning.
10683   assert(!Error && "Error setting up implicit decl!");
10684   SourceLocation NoLoc;
10685   Declarator D(DS, Declarator::BlockContext);
10686   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10687                                              /*IsAmbiguous=*/false,
10688                                              /*LParenLoc=*/NoLoc,
10689                                              /*Params=*/nullptr,
10690                                              /*NumParams=*/0,
10691                                              /*EllipsisLoc=*/NoLoc,
10692                                              /*RParenLoc=*/NoLoc,
10693                                              /*TypeQuals=*/0,
10694                                              /*RefQualifierIsLvalueRef=*/true,
10695                                              /*RefQualifierLoc=*/NoLoc,
10696                                              /*ConstQualifierLoc=*/NoLoc,
10697                                              /*VolatileQualifierLoc=*/NoLoc,
10698                                              /*RestrictQualifierLoc=*/NoLoc,
10699                                              /*MutableLoc=*/NoLoc,
10700                                              EST_None,
10701                                              /*ESpecLoc=*/NoLoc,
10702                                              /*Exceptions=*/nullptr,
10703                                              /*ExceptionRanges=*/nullptr,
10704                                              /*NumExceptions=*/0,
10705                                              /*NoexceptExpr=*/nullptr,
10706                                              /*ExceptionSpecTokens=*/nullptr,
10707                                              Loc, Loc, D),
10708                 DS.getAttributes(),
10709                 SourceLocation());
10710   D.SetIdentifier(&II, Loc);
10711 
10712   // Insert this function into translation-unit scope.
10713 
10714   DeclContext *PrevDC = CurContext;
10715   CurContext = Context.getTranslationUnitDecl();
10716 
10717   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10718   FD->setImplicit();
10719 
10720   CurContext = PrevDC;
10721 
10722   AddKnownFunctionAttributes(FD);
10723 
10724   return FD;
10725 }
10726 
10727 /// \brief Adds any function attributes that we know a priori based on
10728 /// the declaration of this function.
10729 ///
10730 /// These attributes can apply both to implicitly-declared builtins
10731 /// (like __builtin___printf_chk) or to library-declared functions
10732 /// like NSLog or printf.
10733 ///
10734 /// We need to check for duplicate attributes both here and where user-written
10735 /// attributes are applied to declarations.
10736 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10737   if (FD->isInvalidDecl())
10738     return;
10739 
10740   // If this is a built-in function, map its builtin attributes to
10741   // actual attributes.
10742   if (unsigned BuiltinID = FD->getBuiltinID()) {
10743     // Handle printf-formatting attributes.
10744     unsigned FormatIdx;
10745     bool HasVAListArg;
10746     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10747       if (!FD->hasAttr<FormatAttr>()) {
10748         const char *fmt = "printf";
10749         unsigned int NumParams = FD->getNumParams();
10750         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10751             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10752           fmt = "NSString";
10753         FD->addAttr(FormatAttr::CreateImplicit(Context,
10754                                                &Context.Idents.get(fmt),
10755                                                FormatIdx+1,
10756                                                HasVAListArg ? 0 : FormatIdx+2,
10757                                                FD->getLocation()));
10758       }
10759     }
10760     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10761                                              HasVAListArg)) {
10762      if (!FD->hasAttr<FormatAttr>())
10763        FD->addAttr(FormatAttr::CreateImplicit(Context,
10764                                               &Context.Idents.get("scanf"),
10765                                               FormatIdx+1,
10766                                               HasVAListArg ? 0 : FormatIdx+2,
10767                                               FD->getLocation()));
10768     }
10769 
10770     // Mark const if we don't care about errno and that is the only
10771     // thing preventing the function from being const. This allows
10772     // IRgen to use LLVM intrinsics for such functions.
10773     if (!getLangOpts().MathErrno &&
10774         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10775       if (!FD->hasAttr<ConstAttr>())
10776         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10777     }
10778 
10779     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10780         !FD->hasAttr<ReturnsTwiceAttr>())
10781       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10782                                          FD->getLocation()));
10783     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10784       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10785     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10786       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10787   }
10788 
10789   IdentifierInfo *Name = FD->getIdentifier();
10790   if (!Name)
10791     return;
10792   if ((!getLangOpts().CPlusPlus &&
10793        FD->getDeclContext()->isTranslationUnit()) ||
10794       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10795        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10796        LinkageSpecDecl::lang_c)) {
10797     // Okay: this could be a libc/libm/Objective-C function we know
10798     // about.
10799   } else
10800     return;
10801 
10802   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10803     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10804     // target-specific builtins, perhaps?
10805     if (!FD->hasAttr<FormatAttr>())
10806       FD->addAttr(FormatAttr::CreateImplicit(Context,
10807                                              &Context.Idents.get("printf"), 2,
10808                                              Name->isStr("vasprintf") ? 0 : 3,
10809                                              FD->getLocation()));
10810   }
10811 
10812   if (Name->isStr("__CFStringMakeConstantString")) {
10813     // We already have a __builtin___CFStringMakeConstantString,
10814     // but builds that use -fno-constant-cfstrings don't go through that.
10815     if (!FD->hasAttr<FormatArgAttr>())
10816       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10817                                                 FD->getLocation()));
10818   }
10819 }
10820 
10821 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10822                                     TypeSourceInfo *TInfo) {
10823   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10824   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10825 
10826   if (!TInfo) {
10827     assert(D.isInvalidType() && "no declarator info for valid type");
10828     TInfo = Context.getTrivialTypeSourceInfo(T);
10829   }
10830 
10831   // Scope manipulation handled by caller.
10832   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10833                                            D.getLocStart(),
10834                                            D.getIdentifierLoc(),
10835                                            D.getIdentifier(),
10836                                            TInfo);
10837 
10838   // Bail out immediately if we have an invalid declaration.
10839   if (D.isInvalidType()) {
10840     NewTD->setInvalidDecl();
10841     return NewTD;
10842   }
10843 
10844   if (D.getDeclSpec().isModulePrivateSpecified()) {
10845     if (CurContext->isFunctionOrMethod())
10846       Diag(NewTD->getLocation(), diag::err_module_private_local)
10847         << 2 << NewTD->getDeclName()
10848         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10849         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10850     else
10851       NewTD->setModulePrivate();
10852   }
10853 
10854   // C++ [dcl.typedef]p8:
10855   //   If the typedef declaration defines an unnamed class (or
10856   //   enum), the first typedef-name declared by the declaration
10857   //   to be that class type (or enum type) is used to denote the
10858   //   class type (or enum type) for linkage purposes only.
10859   // We need to check whether the type was declared in the declaration.
10860   switch (D.getDeclSpec().getTypeSpecType()) {
10861   case TST_enum:
10862   case TST_struct:
10863   case TST_interface:
10864   case TST_union:
10865   case TST_class: {
10866     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10867 
10868     // Do nothing if the tag is not anonymous or already has an
10869     // associated typedef (from an earlier typedef in this decl group).
10870     if (tagFromDeclSpec->getIdentifier()) break;
10871     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10872 
10873     // A well-formed anonymous tag must always be a TUK_Definition.
10874     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10875 
10876     // The type must match the tag exactly;  no qualifiers allowed.
10877     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10878       break;
10879 
10880     // If we've already computed linkage for the anonymous tag, then
10881     // adding a typedef name for the anonymous decl can change that
10882     // linkage, which might be a serious problem.  Diagnose this as
10883     // unsupported and ignore the typedef name.  TODO: we should
10884     // pursue this as a language defect and establish a formal rule
10885     // for how to handle it.
10886     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10887       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10888 
10889       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10890       tagLoc = getLocForEndOfToken(tagLoc);
10891 
10892       llvm::SmallString<40> textToInsert;
10893       textToInsert += ' ';
10894       textToInsert += D.getIdentifier()->getName();
10895       Diag(tagLoc, diag::note_typedef_changes_linkage)
10896         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10897       break;
10898     }
10899 
10900     // Otherwise, set this is the anon-decl typedef for the tag.
10901     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10902     break;
10903   }
10904 
10905   default:
10906     break;
10907   }
10908 
10909   return NewTD;
10910 }
10911 
10912 
10913 /// \brief Check that this is a valid underlying type for an enum declaration.
10914 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10915   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10916   QualType T = TI->getType();
10917 
10918   if (T->isDependentType())
10919     return false;
10920 
10921   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10922     if (BT->isInteger())
10923       return false;
10924 
10925   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10926   return true;
10927 }
10928 
10929 /// Check whether this is a valid redeclaration of a previous enumeration.
10930 /// \return true if the redeclaration was invalid.
10931 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10932                                   QualType EnumUnderlyingTy,
10933                                   const EnumDecl *Prev) {
10934   bool IsFixed = !EnumUnderlyingTy.isNull();
10935 
10936   if (IsScoped != Prev->isScoped()) {
10937     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10938       << Prev->isScoped();
10939     Diag(Prev->getLocation(), diag::note_previous_declaration);
10940     return true;
10941   }
10942 
10943   if (IsFixed && Prev->isFixed()) {
10944     if (!EnumUnderlyingTy->isDependentType() &&
10945         !Prev->getIntegerType()->isDependentType() &&
10946         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10947                                         Prev->getIntegerType())) {
10948       // TODO: Highlight the underlying type of the redeclaration.
10949       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10950         << EnumUnderlyingTy << Prev->getIntegerType();
10951       Diag(Prev->getLocation(), diag::note_previous_declaration)
10952           << Prev->getIntegerTypeRange();
10953       return true;
10954     }
10955   } else if (IsFixed != Prev->isFixed()) {
10956     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10957       << Prev->isFixed();
10958     Diag(Prev->getLocation(), diag::note_previous_declaration);
10959     return true;
10960   }
10961 
10962   return false;
10963 }
10964 
10965 /// \brief Get diagnostic %select index for tag kind for
10966 /// redeclaration diagnostic message.
10967 /// WARNING: Indexes apply to particular diagnostics only!
10968 ///
10969 /// \returns diagnostic %select index.
10970 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10971   switch (Tag) {
10972   case TTK_Struct: return 0;
10973   case TTK_Interface: return 1;
10974   case TTK_Class:  return 2;
10975   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10976   }
10977 }
10978 
10979 /// \brief Determine if tag kind is a class-key compatible with
10980 /// class for redeclaration (class, struct, or __interface).
10981 ///
10982 /// \returns true iff the tag kind is compatible.
10983 static bool isClassCompatTagKind(TagTypeKind Tag)
10984 {
10985   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10986 }
10987 
10988 /// \brief Determine whether a tag with a given kind is acceptable
10989 /// as a redeclaration of the given tag declaration.
10990 ///
10991 /// \returns true if the new tag kind is acceptable, false otherwise.
10992 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10993                                         TagTypeKind NewTag, bool isDefinition,
10994                                         SourceLocation NewTagLoc,
10995                                         const IdentifierInfo &Name) {
10996   // C++ [dcl.type.elab]p3:
10997   //   The class-key or enum keyword present in the
10998   //   elaborated-type-specifier shall agree in kind with the
10999   //   declaration to which the name in the elaborated-type-specifier
11000   //   refers. This rule also applies to the form of
11001   //   elaborated-type-specifier that declares a class-name or
11002   //   friend class since it can be construed as referring to the
11003   //   definition of the class. Thus, in any
11004   //   elaborated-type-specifier, the enum keyword shall be used to
11005   //   refer to an enumeration (7.2), the union class-key shall be
11006   //   used to refer to a union (clause 9), and either the class or
11007   //   struct class-key shall be used to refer to a class (clause 9)
11008   //   declared using the class or struct class-key.
11009   TagTypeKind OldTag = Previous->getTagKind();
11010   if (!isDefinition || !isClassCompatTagKind(NewTag))
11011     if (OldTag == NewTag)
11012       return true;
11013 
11014   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11015     // Warn about the struct/class tag mismatch.
11016     bool isTemplate = false;
11017     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11018       isTemplate = Record->getDescribedClassTemplate();
11019 
11020     if (!ActiveTemplateInstantiations.empty()) {
11021       // In a template instantiation, do not offer fix-its for tag mismatches
11022       // since they usually mess up the template instead of fixing the problem.
11023       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11024         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11025         << getRedeclDiagFromTagKind(OldTag);
11026       return true;
11027     }
11028 
11029     if (isDefinition) {
11030       // On definitions, check previous tags and issue a fix-it for each
11031       // one that doesn't match the current tag.
11032       if (Previous->getDefinition()) {
11033         // Don't suggest fix-its for redefinitions.
11034         return true;
11035       }
11036 
11037       bool previousMismatch = false;
11038       for (auto I : Previous->redecls()) {
11039         if (I->getTagKind() != NewTag) {
11040           if (!previousMismatch) {
11041             previousMismatch = true;
11042             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11043               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11044               << getRedeclDiagFromTagKind(I->getTagKind());
11045           }
11046           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11047             << getRedeclDiagFromTagKind(NewTag)
11048             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11049                  TypeWithKeyword::getTagTypeKindName(NewTag));
11050         }
11051       }
11052       return true;
11053     }
11054 
11055     // Check for a previous definition.  If current tag and definition
11056     // are same type, do nothing.  If no definition, but disagree with
11057     // with previous tag type, give a warning, but no fix-it.
11058     const TagDecl *Redecl = Previous->getDefinition() ?
11059                             Previous->getDefinition() : Previous;
11060     if (Redecl->getTagKind() == NewTag) {
11061       return true;
11062     }
11063 
11064     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11065       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11066       << getRedeclDiagFromTagKind(OldTag);
11067     Diag(Redecl->getLocation(), diag::note_previous_use);
11068 
11069     // If there is a previous definition, suggest a fix-it.
11070     if (Previous->getDefinition()) {
11071         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11072           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11073           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11074                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11075     }
11076 
11077     return true;
11078   }
11079   return false;
11080 }
11081 
11082 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11083 /// from an outer enclosing namespace or file scope inside a friend declaration.
11084 /// This should provide the commented out code in the following snippet:
11085 ///   namespace N {
11086 ///     struct X;
11087 ///     namespace M {
11088 ///       struct Y { friend struct /*N::*/ X; };
11089 ///     }
11090 ///   }
11091 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11092                                          SourceLocation NameLoc) {
11093   // While the decl is in a namespace, do repeated lookup of that name and see
11094   // if we get the same namespace back.  If we do not, continue until
11095   // translation unit scope, at which point we have a fully qualified NNS.
11096   SmallVector<IdentifierInfo *, 4> Namespaces;
11097   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11098   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11099     // This tag should be declared in a namespace, which can only be enclosed by
11100     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11101     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11102     if (!Namespace || Namespace->isAnonymousNamespace())
11103       return FixItHint();
11104     IdentifierInfo *II = Namespace->getIdentifier();
11105     Namespaces.push_back(II);
11106     NamedDecl *Lookup = SemaRef.LookupSingleName(
11107         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11108     if (Lookup == Namespace)
11109       break;
11110   }
11111 
11112   // Once we have all the namespaces, reverse them to go outermost first, and
11113   // build an NNS.
11114   SmallString<64> Insertion;
11115   llvm::raw_svector_ostream OS(Insertion);
11116   if (DC->isTranslationUnit())
11117     OS << "::";
11118   std::reverse(Namespaces.begin(), Namespaces.end());
11119   for (auto *II : Namespaces)
11120     OS << II->getName() << "::";
11121   OS.flush();
11122   return FixItHint::CreateInsertion(NameLoc, Insertion);
11123 }
11124 
11125 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11126 /// former case, Name will be non-null.  In the later case, Name will be null.
11127 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11128 /// reference/declaration/definition of a tag.
11129 ///
11130 /// IsTypeSpecifier is true if this is a type-specifier (or
11131 /// trailing-type-specifier) other than one in an alias-declaration.
11132 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11133                      SourceLocation KWLoc, CXXScopeSpec &SS,
11134                      IdentifierInfo *Name, SourceLocation NameLoc,
11135                      AttributeList *Attr, AccessSpecifier AS,
11136                      SourceLocation ModulePrivateLoc,
11137                      MultiTemplateParamsArg TemplateParameterLists,
11138                      bool &OwnedDecl, bool &IsDependent,
11139                      SourceLocation ScopedEnumKWLoc,
11140                      bool ScopedEnumUsesClassTag,
11141                      TypeResult UnderlyingType,
11142                      bool IsTypeSpecifier) {
11143   // If this is not a definition, it must have a name.
11144   IdentifierInfo *OrigName = Name;
11145   assert((Name != nullptr || TUK == TUK_Definition) &&
11146          "Nameless record must be a definition!");
11147   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11148 
11149   OwnedDecl = false;
11150   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11151   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11152 
11153   // FIXME: Check explicit specializations more carefully.
11154   bool isExplicitSpecialization = false;
11155   bool Invalid = false;
11156 
11157   // We only need to do this matching if we have template parameters
11158   // or a scope specifier, which also conveniently avoids this work
11159   // for non-C++ cases.
11160   if (TemplateParameterLists.size() > 0 ||
11161       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11162     if (TemplateParameterList *TemplateParams =
11163             MatchTemplateParametersToScopeSpecifier(
11164                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11165                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11166       if (Kind == TTK_Enum) {
11167         Diag(KWLoc, diag::err_enum_template);
11168         return nullptr;
11169       }
11170 
11171       if (TemplateParams->size() > 0) {
11172         // This is a declaration or definition of a class template (which may
11173         // be a member of another template).
11174 
11175         if (Invalid)
11176           return nullptr;
11177 
11178         OwnedDecl = false;
11179         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11180                                                SS, Name, NameLoc, Attr,
11181                                                TemplateParams, AS,
11182                                                ModulePrivateLoc,
11183                                                /*FriendLoc*/SourceLocation(),
11184                                                TemplateParameterLists.size()-1,
11185                                                TemplateParameterLists.data());
11186         return Result.get();
11187       } else {
11188         // The "template<>" header is extraneous.
11189         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11190           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11191         isExplicitSpecialization = true;
11192       }
11193     }
11194   }
11195 
11196   // Figure out the underlying type if this a enum declaration. We need to do
11197   // this early, because it's needed to detect if this is an incompatible
11198   // redeclaration.
11199   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11200 
11201   if (Kind == TTK_Enum) {
11202     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11203       // No underlying type explicitly specified, or we failed to parse the
11204       // type, default to int.
11205       EnumUnderlying = Context.IntTy.getTypePtr();
11206     else if (UnderlyingType.get()) {
11207       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11208       // integral type; any cv-qualification is ignored.
11209       TypeSourceInfo *TI = nullptr;
11210       GetTypeFromParser(UnderlyingType.get(), &TI);
11211       EnumUnderlying = TI;
11212 
11213       if (CheckEnumUnderlyingType(TI))
11214         // Recover by falling back to int.
11215         EnumUnderlying = Context.IntTy.getTypePtr();
11216 
11217       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11218                                           UPPC_FixedUnderlyingType))
11219         EnumUnderlying = Context.IntTy.getTypePtr();
11220 
11221     } else if (getLangOpts().MSVCCompat)
11222       // Microsoft enums are always of int type.
11223       EnumUnderlying = Context.IntTy.getTypePtr();
11224   }
11225 
11226   DeclContext *SearchDC = CurContext;
11227   DeclContext *DC = CurContext;
11228   bool isStdBadAlloc = false;
11229 
11230   RedeclarationKind Redecl = ForRedeclaration;
11231   if (TUK == TUK_Friend || TUK == TUK_Reference)
11232     Redecl = NotForRedeclaration;
11233 
11234   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11235   if (Name && SS.isNotEmpty()) {
11236     // We have a nested-name tag ('struct foo::bar').
11237 
11238     // Check for invalid 'foo::'.
11239     if (SS.isInvalid()) {
11240       Name = nullptr;
11241       goto CreateNewDecl;
11242     }
11243 
11244     // If this is a friend or a reference to a class in a dependent
11245     // context, don't try to make a decl for it.
11246     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11247       DC = computeDeclContext(SS, false);
11248       if (!DC) {
11249         IsDependent = true;
11250         return nullptr;
11251       }
11252     } else {
11253       DC = computeDeclContext(SS, true);
11254       if (!DC) {
11255         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11256           << SS.getRange();
11257         return nullptr;
11258       }
11259     }
11260 
11261     if (RequireCompleteDeclContext(SS, DC))
11262       return nullptr;
11263 
11264     SearchDC = DC;
11265     // Look-up name inside 'foo::'.
11266     LookupQualifiedName(Previous, DC);
11267 
11268     if (Previous.isAmbiguous())
11269       return nullptr;
11270 
11271     if (Previous.empty()) {
11272       // Name lookup did not find anything. However, if the
11273       // nested-name-specifier refers to the current instantiation,
11274       // and that current instantiation has any dependent base
11275       // classes, we might find something at instantiation time: treat
11276       // this as a dependent elaborated-type-specifier.
11277       // But this only makes any sense for reference-like lookups.
11278       if (Previous.wasNotFoundInCurrentInstantiation() &&
11279           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11280         IsDependent = true;
11281         return nullptr;
11282       }
11283 
11284       // A tag 'foo::bar' must already exist.
11285       Diag(NameLoc, diag::err_not_tag_in_scope)
11286         << Kind << Name << DC << SS.getRange();
11287       Name = nullptr;
11288       Invalid = true;
11289       goto CreateNewDecl;
11290     }
11291   } else if (Name) {
11292     // If this is a named struct, check to see if there was a previous forward
11293     // declaration or definition.
11294     // FIXME: We're looking into outer scopes here, even when we
11295     // shouldn't be. Doing so can result in ambiguities that we
11296     // shouldn't be diagnosing.
11297     LookupName(Previous, S);
11298 
11299     // When declaring or defining a tag, ignore ambiguities introduced
11300     // by types using'ed into this scope.
11301     if (Previous.isAmbiguous() &&
11302         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11303       LookupResult::Filter F = Previous.makeFilter();
11304       while (F.hasNext()) {
11305         NamedDecl *ND = F.next();
11306         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11307           F.erase();
11308       }
11309       F.done();
11310     }
11311 
11312     // C++11 [namespace.memdef]p3:
11313     //   If the name in a friend declaration is neither qualified nor
11314     //   a template-id and the declaration is a function or an
11315     //   elaborated-type-specifier, the lookup to determine whether
11316     //   the entity has been previously declared shall not consider
11317     //   any scopes outside the innermost enclosing namespace.
11318     //
11319     // MSVC doesn't implement the above rule for types, so a friend tag
11320     // declaration may be a redeclaration of a type declared in an enclosing
11321     // scope.  They do implement this rule for friend functions.
11322     //
11323     // Does it matter that this should be by scope instead of by
11324     // semantic context?
11325     if (!Previous.empty() && TUK == TUK_Friend) {
11326       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11327       LookupResult::Filter F = Previous.makeFilter();
11328       bool FriendSawTagOutsideEnclosingNamespace = false;
11329       while (F.hasNext()) {
11330         NamedDecl *ND = F.next();
11331         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11332         if (DC->isFileContext() &&
11333             !EnclosingNS->Encloses(ND->getDeclContext())) {
11334           if (getLangOpts().MSVCCompat)
11335             FriendSawTagOutsideEnclosingNamespace = true;
11336           else
11337             F.erase();
11338         }
11339       }
11340       F.done();
11341 
11342       // Diagnose this MSVC extension in the easy case where lookup would have
11343       // unambiguously found something outside the enclosing namespace.
11344       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11345         NamedDecl *ND = Previous.getFoundDecl();
11346         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11347             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11348       }
11349     }
11350 
11351     // Note:  there used to be some attempt at recovery here.
11352     if (Previous.isAmbiguous())
11353       return nullptr;
11354 
11355     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11356       // FIXME: This makes sure that we ignore the contexts associated
11357       // with C structs, unions, and enums when looking for a matching
11358       // tag declaration or definition. See the similar lookup tweak
11359       // in Sema::LookupName; is there a better way to deal with this?
11360       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11361         SearchDC = SearchDC->getParent();
11362     }
11363   }
11364 
11365   if (Previous.isSingleResult() &&
11366       Previous.getFoundDecl()->isTemplateParameter()) {
11367     // Maybe we will complain about the shadowed template parameter.
11368     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11369     // Just pretend that we didn't see the previous declaration.
11370     Previous.clear();
11371   }
11372 
11373   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11374       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11375     // This is a declaration of or a reference to "std::bad_alloc".
11376     isStdBadAlloc = true;
11377 
11378     if (Previous.empty() && StdBadAlloc) {
11379       // std::bad_alloc has been implicitly declared (but made invisible to
11380       // name lookup). Fill in this implicit declaration as the previous
11381       // declaration, so that the declarations get chained appropriately.
11382       Previous.addDecl(getStdBadAlloc());
11383     }
11384   }
11385 
11386   // If we didn't find a previous declaration, and this is a reference
11387   // (or friend reference), move to the correct scope.  In C++, we
11388   // also need to do a redeclaration lookup there, just in case
11389   // there's a shadow friend decl.
11390   if (Name && Previous.empty() &&
11391       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11392     if (Invalid) goto CreateNewDecl;
11393     assert(SS.isEmpty());
11394 
11395     if (TUK == TUK_Reference) {
11396       // C++ [basic.scope.pdecl]p5:
11397       //   -- for an elaborated-type-specifier of the form
11398       //
11399       //          class-key identifier
11400       //
11401       //      if the elaborated-type-specifier is used in the
11402       //      decl-specifier-seq or parameter-declaration-clause of a
11403       //      function defined in namespace scope, the identifier is
11404       //      declared as a class-name in the namespace that contains
11405       //      the declaration; otherwise, except as a friend
11406       //      declaration, the identifier is declared in the smallest
11407       //      non-class, non-function-prototype scope that contains the
11408       //      declaration.
11409       //
11410       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11411       // C structs and unions.
11412       //
11413       // It is an error in C++ to declare (rather than define) an enum
11414       // type, including via an elaborated type specifier.  We'll
11415       // diagnose that later; for now, declare the enum in the same
11416       // scope as we would have picked for any other tag type.
11417       //
11418       // GNU C also supports this behavior as part of its incomplete
11419       // enum types extension, while GNU C++ does not.
11420       //
11421       // Find the context where we'll be declaring the tag.
11422       // FIXME: We would like to maintain the current DeclContext as the
11423       // lexical context,
11424       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11425         SearchDC = SearchDC->getParent();
11426 
11427       // Find the scope where we'll be declaring the tag.
11428       while (S->isClassScope() ||
11429              (getLangOpts().CPlusPlus &&
11430               S->isFunctionPrototypeScope()) ||
11431              ((S->getFlags() & Scope::DeclScope) == 0) ||
11432              (S->getEntity() && S->getEntity()->isTransparentContext()))
11433         S = S->getParent();
11434     } else {
11435       assert(TUK == TUK_Friend);
11436       // C++ [namespace.memdef]p3:
11437       //   If a friend declaration in a non-local class first declares a
11438       //   class or function, the friend class or function is a member of
11439       //   the innermost enclosing namespace.
11440       SearchDC = SearchDC->getEnclosingNamespaceContext();
11441     }
11442 
11443     // In C++, we need to do a redeclaration lookup to properly
11444     // diagnose some problems.
11445     if (getLangOpts().CPlusPlus) {
11446       Previous.setRedeclarationKind(ForRedeclaration);
11447       LookupQualifiedName(Previous, SearchDC);
11448     }
11449   }
11450 
11451   if (!Previous.empty()) {
11452     NamedDecl *PrevDecl = Previous.getFoundDecl();
11453     NamedDecl *DirectPrevDecl =
11454         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11455 
11456     // It's okay to have a tag decl in the same scope as a typedef
11457     // which hides a tag decl in the same scope.  Finding this
11458     // insanity with a redeclaration lookup can only actually happen
11459     // in C++.
11460     //
11461     // This is also okay for elaborated-type-specifiers, which is
11462     // technically forbidden by the current standard but which is
11463     // okay according to the likely resolution of an open issue;
11464     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11465     if (getLangOpts().CPlusPlus) {
11466       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11467         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11468           TagDecl *Tag = TT->getDecl();
11469           if (Tag->getDeclName() == Name &&
11470               Tag->getDeclContext()->getRedeclContext()
11471                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11472             PrevDecl = Tag;
11473             Previous.clear();
11474             Previous.addDecl(Tag);
11475             Previous.resolveKind();
11476           }
11477         }
11478       }
11479     }
11480 
11481     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11482       // If this is a use of a previous tag, or if the tag is already declared
11483       // in the same scope (so that the definition/declaration completes or
11484       // rementions the tag), reuse the decl.
11485       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11486           isDeclInScope(DirectPrevDecl, SearchDC, S,
11487                         SS.isNotEmpty() || isExplicitSpecialization)) {
11488         // Make sure that this wasn't declared as an enum and now used as a
11489         // struct or something similar.
11490         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11491                                           TUK == TUK_Definition, KWLoc,
11492                                           *Name)) {
11493           bool SafeToContinue
11494             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11495                Kind != TTK_Enum);
11496           if (SafeToContinue)
11497             Diag(KWLoc, diag::err_use_with_wrong_tag)
11498               << Name
11499               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11500                                               PrevTagDecl->getKindName());
11501           else
11502             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11503           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11504 
11505           if (SafeToContinue)
11506             Kind = PrevTagDecl->getTagKind();
11507           else {
11508             // Recover by making this an anonymous redefinition.
11509             Name = nullptr;
11510             Previous.clear();
11511             Invalid = true;
11512           }
11513         }
11514 
11515         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11516           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11517 
11518           // If this is an elaborated-type-specifier for a scoped enumeration,
11519           // the 'class' keyword is not necessary and not permitted.
11520           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11521             if (ScopedEnum)
11522               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11523                 << PrevEnum->isScoped()
11524                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11525             return PrevTagDecl;
11526           }
11527 
11528           QualType EnumUnderlyingTy;
11529           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11530             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11531           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11532             EnumUnderlyingTy = QualType(T, 0);
11533 
11534           // All conflicts with previous declarations are recovered by
11535           // returning the previous declaration, unless this is a definition,
11536           // in which case we want the caller to bail out.
11537           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11538                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11539             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11540         }
11541 
11542         // C++11 [class.mem]p1:
11543         //   A member shall not be declared twice in the member-specification,
11544         //   except that a nested class or member class template can be declared
11545         //   and then later defined.
11546         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11547             S->isDeclScope(PrevDecl)) {
11548           Diag(NameLoc, diag::ext_member_redeclared);
11549           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11550         }
11551 
11552         if (!Invalid) {
11553           // If this is a use, just return the declaration we found, unless
11554           // we have attributes.
11555 
11556           // FIXME: In the future, return a variant or some other clue
11557           // for the consumer of this Decl to know it doesn't own it.
11558           // For our current ASTs this shouldn't be a problem, but will
11559           // need to be changed with DeclGroups.
11560           if (!Attr &&
11561               ((TUK == TUK_Reference &&
11562                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11563                || TUK == TUK_Friend))
11564             return PrevTagDecl;
11565 
11566           // Diagnose attempts to redefine a tag.
11567           if (TUK == TUK_Definition) {
11568             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11569               // If we're defining a specialization and the previous definition
11570               // is from an implicit instantiation, don't emit an error
11571               // here; we'll catch this in the general case below.
11572               bool IsExplicitSpecializationAfterInstantiation = false;
11573               if (isExplicitSpecialization) {
11574                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11575                   IsExplicitSpecializationAfterInstantiation =
11576                     RD->getTemplateSpecializationKind() !=
11577                     TSK_ExplicitSpecialization;
11578                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11579                   IsExplicitSpecializationAfterInstantiation =
11580                     ED->getTemplateSpecializationKind() !=
11581                     TSK_ExplicitSpecialization;
11582               }
11583 
11584               if (!IsExplicitSpecializationAfterInstantiation) {
11585                 // A redeclaration in function prototype scope in C isn't
11586                 // visible elsewhere, so merely issue a warning.
11587                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11588                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11589                 else
11590                   Diag(NameLoc, diag::err_redefinition) << Name;
11591                 Diag(Def->getLocation(), diag::note_previous_definition);
11592                 // If this is a redefinition, recover by making this
11593                 // struct be anonymous, which will make any later
11594                 // references get the previous definition.
11595                 Name = nullptr;
11596                 Previous.clear();
11597                 Invalid = true;
11598               }
11599             } else {
11600               // If the type is currently being defined, complain
11601               // about a nested redefinition.
11602               const TagType *Tag
11603                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
11604               if (Tag->isBeingDefined()) {
11605                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11606                 Diag(PrevTagDecl->getLocation(),
11607                      diag::note_previous_definition);
11608                 Name = nullptr;
11609                 Previous.clear();
11610                 Invalid = true;
11611               }
11612             }
11613 
11614             // Okay, this is definition of a previously declared or referenced
11615             // tag. We're going to create a new Decl for it.
11616           }
11617 
11618           // Okay, we're going to make a redeclaration.  If this is some kind
11619           // of reference, make sure we build the redeclaration in the same DC
11620           // as the original, and ignore the current access specifier.
11621           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11622             SearchDC = PrevTagDecl->getDeclContext();
11623             AS = AS_none;
11624           }
11625         }
11626         // If we get here we have (another) forward declaration or we
11627         // have a definition.  Just create a new decl.
11628 
11629       } else {
11630         // If we get here, this is a definition of a new tag type in a nested
11631         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11632         // new decl/type.  We set PrevDecl to NULL so that the entities
11633         // have distinct types.
11634         Previous.clear();
11635       }
11636       // If we get here, we're going to create a new Decl. If PrevDecl
11637       // is non-NULL, it's a definition of the tag declared by
11638       // PrevDecl. If it's NULL, we have a new definition.
11639 
11640 
11641     // Otherwise, PrevDecl is not a tag, but was found with tag
11642     // lookup.  This is only actually possible in C++, where a few
11643     // things like templates still live in the tag namespace.
11644     } else {
11645       // Use a better diagnostic if an elaborated-type-specifier
11646       // found the wrong kind of type on the first
11647       // (non-redeclaration) lookup.
11648       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11649           !Previous.isForRedeclaration()) {
11650         unsigned Kind = 0;
11651         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11652         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11653         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11654         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11655         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11656         Invalid = true;
11657 
11658       // Otherwise, only diagnose if the declaration is in scope.
11659       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11660                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11661         // do nothing
11662 
11663       // Diagnose implicit declarations introduced by elaborated types.
11664       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11665         unsigned Kind = 0;
11666         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11667         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11668         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11669         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11670         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11671         Invalid = true;
11672 
11673       // Otherwise it's a declaration.  Call out a particularly common
11674       // case here.
11675       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11676         unsigned Kind = 0;
11677         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11678         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11679           << Name << Kind << TND->getUnderlyingType();
11680         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11681         Invalid = true;
11682 
11683       // Otherwise, diagnose.
11684       } else {
11685         // The tag name clashes with something else in the target scope,
11686         // issue an error and recover by making this tag be anonymous.
11687         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11688         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11689         Name = nullptr;
11690         Invalid = true;
11691       }
11692 
11693       // The existing declaration isn't relevant to us; we're in a
11694       // new scope, so clear out the previous declaration.
11695       Previous.clear();
11696     }
11697   }
11698 
11699 CreateNewDecl:
11700 
11701   TagDecl *PrevDecl = nullptr;
11702   if (Previous.isSingleResult())
11703     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11704 
11705   // If there is an identifier, use the location of the identifier as the
11706   // location of the decl, otherwise use the location of the struct/union
11707   // keyword.
11708   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11709 
11710   // Otherwise, create a new declaration. If there is a previous
11711   // declaration of the same entity, the two will be linked via
11712   // PrevDecl.
11713   TagDecl *New;
11714 
11715   bool IsForwardReference = false;
11716   if (Kind == TTK_Enum) {
11717     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11718     // enum X { A, B, C } D;    D should chain to X.
11719     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11720                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11721                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11722     // If this is an undefined enum, warn.
11723     if (TUK != TUK_Definition && !Invalid) {
11724       TagDecl *Def;
11725       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11726           cast<EnumDecl>(New)->isFixed()) {
11727         // C++0x: 7.2p2: opaque-enum-declaration.
11728         // Conflicts are diagnosed above. Do nothing.
11729       }
11730       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11731         Diag(Loc, diag::ext_forward_ref_enum_def)
11732           << New;
11733         Diag(Def->getLocation(), diag::note_previous_definition);
11734       } else {
11735         unsigned DiagID = diag::ext_forward_ref_enum;
11736         if (getLangOpts().MSVCCompat)
11737           DiagID = diag::ext_ms_forward_ref_enum;
11738         else if (getLangOpts().CPlusPlus)
11739           DiagID = diag::err_forward_ref_enum;
11740         Diag(Loc, DiagID);
11741 
11742         // If this is a forward-declared reference to an enumeration, make a
11743         // note of it; we won't actually be introducing the declaration into
11744         // the declaration context.
11745         if (TUK == TUK_Reference)
11746           IsForwardReference = true;
11747       }
11748     }
11749 
11750     if (EnumUnderlying) {
11751       EnumDecl *ED = cast<EnumDecl>(New);
11752       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11753         ED->setIntegerTypeSourceInfo(TI);
11754       else
11755         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11756       ED->setPromotionType(ED->getIntegerType());
11757     }
11758 
11759   } else {
11760     // struct/union/class
11761 
11762     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11763     // struct X { int A; } D;    D should chain to X.
11764     if (getLangOpts().CPlusPlus) {
11765       // FIXME: Look for a way to use RecordDecl for simple structs.
11766       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11767                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11768 
11769       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11770         StdBadAlloc = cast<CXXRecordDecl>(New);
11771     } else
11772       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11773                                cast_or_null<RecordDecl>(PrevDecl));
11774   }
11775 
11776   // C++11 [dcl.type]p3:
11777   //   A type-specifier-seq shall not define a class or enumeration [...].
11778   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11779     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11780       << Context.getTagDeclType(New);
11781     Invalid = true;
11782   }
11783 
11784   // Maybe add qualifier info.
11785   if (SS.isNotEmpty()) {
11786     if (SS.isSet()) {
11787       // If this is either a declaration or a definition, check the
11788       // nested-name-specifier against the current context. We don't do this
11789       // for explicit specializations, because they have similar checking
11790       // (with more specific diagnostics) in the call to
11791       // CheckMemberSpecialization, below.
11792       if (!isExplicitSpecialization &&
11793           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11794           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11795         Invalid = true;
11796 
11797       New->setQualifierInfo(SS.getWithLocInContext(Context));
11798       if (TemplateParameterLists.size() > 0) {
11799         New->setTemplateParameterListsInfo(Context,
11800                                            TemplateParameterLists.size(),
11801                                            TemplateParameterLists.data());
11802       }
11803     }
11804     else
11805       Invalid = true;
11806   }
11807 
11808   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11809     // Add alignment attributes if necessary; these attributes are checked when
11810     // the ASTContext lays out the structure.
11811     //
11812     // It is important for implementing the correct semantics that this
11813     // happen here (in act on tag decl). The #pragma pack stack is
11814     // maintained as a result of parser callbacks which can occur at
11815     // many points during the parsing of a struct declaration (because
11816     // the #pragma tokens are effectively skipped over during the
11817     // parsing of the struct).
11818     if (TUK == TUK_Definition) {
11819       AddAlignmentAttributesForRecord(RD);
11820       AddMsStructLayoutForRecord(RD);
11821     }
11822   }
11823 
11824   if (ModulePrivateLoc.isValid()) {
11825     if (isExplicitSpecialization)
11826       Diag(New->getLocation(), diag::err_module_private_specialization)
11827         << 2
11828         << FixItHint::CreateRemoval(ModulePrivateLoc);
11829     // __module_private__ does not apply to local classes. However, we only
11830     // diagnose this as an error when the declaration specifiers are
11831     // freestanding. Here, we just ignore the __module_private__.
11832     else if (!SearchDC->isFunctionOrMethod())
11833       New->setModulePrivate();
11834   }
11835 
11836   // If this is a specialization of a member class (of a class template),
11837   // check the specialization.
11838   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11839     Invalid = true;
11840 
11841   // If we're declaring or defining a tag in function prototype scope in C,
11842   // note that this type can only be used within the function and add it to
11843   // the list of decls to inject into the function definition scope.
11844   if ((Name || Kind == TTK_Enum) &&
11845       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11846     if (getLangOpts().CPlusPlus) {
11847       // C++ [dcl.fct]p6:
11848       //   Types shall not be defined in return or parameter types.
11849       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11850         Diag(Loc, diag::err_type_defined_in_param_type)
11851             << Name;
11852         Invalid = true;
11853       }
11854     } else {
11855       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11856     }
11857     DeclsInPrototypeScope.push_back(New);
11858   }
11859 
11860   if (Invalid)
11861     New->setInvalidDecl();
11862 
11863   if (Attr)
11864     ProcessDeclAttributeList(S, New, Attr);
11865 
11866   // Set the lexical context. If the tag has a C++ scope specifier, the
11867   // lexical context will be different from the semantic context.
11868   New->setLexicalDeclContext(CurContext);
11869 
11870   // Mark this as a friend decl if applicable.
11871   // In Microsoft mode, a friend declaration also acts as a forward
11872   // declaration so we always pass true to setObjectOfFriendDecl to make
11873   // the tag name visible.
11874   if (TUK == TUK_Friend)
11875     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11876 
11877   // Set the access specifier.
11878   if (!Invalid && SearchDC->isRecord())
11879     SetMemberAccessSpecifier(New, PrevDecl, AS);
11880 
11881   if (TUK == TUK_Definition)
11882     New->startDefinition();
11883 
11884   // If this has an identifier, add it to the scope stack.
11885   if (TUK == TUK_Friend) {
11886     // We might be replacing an existing declaration in the lookup tables;
11887     // if so, borrow its access specifier.
11888     if (PrevDecl)
11889       New->setAccess(PrevDecl->getAccess());
11890 
11891     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11892     DC->makeDeclVisibleInContext(New);
11893     if (Name) // can be null along some error paths
11894       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11895         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11896   } else if (Name) {
11897     S = getNonFieldDeclScope(S);
11898     PushOnScopeChains(New, S, !IsForwardReference);
11899     if (IsForwardReference)
11900       SearchDC->makeDeclVisibleInContext(New);
11901 
11902   } else {
11903     CurContext->addDecl(New);
11904   }
11905 
11906   // If this is the C FILE type, notify the AST context.
11907   if (IdentifierInfo *II = New->getIdentifier())
11908     if (!New->isInvalidDecl() &&
11909         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11910         II->isStr("FILE"))
11911       Context.setFILEDecl(New);
11912 
11913   if (PrevDecl)
11914     mergeDeclAttributes(New, PrevDecl);
11915 
11916   // If there's a #pragma GCC visibility in scope, set the visibility of this
11917   // record.
11918   AddPushedVisibilityAttribute(New);
11919 
11920   OwnedDecl = true;
11921   // In C++, don't return an invalid declaration. We can't recover well from
11922   // the cases where we make the type anonymous.
11923   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11924 }
11925 
11926 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11927   AdjustDeclIfTemplate(TagD);
11928   TagDecl *Tag = cast<TagDecl>(TagD);
11929 
11930   // Enter the tag context.
11931   PushDeclContext(S, Tag);
11932 
11933   ActOnDocumentableDecl(TagD);
11934 
11935   // If there's a #pragma GCC visibility in scope, set the visibility of this
11936   // record.
11937   AddPushedVisibilityAttribute(Tag);
11938 }
11939 
11940 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11941   assert(isa<ObjCContainerDecl>(IDecl) &&
11942          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11943   DeclContext *OCD = cast<DeclContext>(IDecl);
11944   assert(getContainingDC(OCD) == CurContext &&
11945       "The next DeclContext should be lexically contained in the current one.");
11946   CurContext = OCD;
11947   return IDecl;
11948 }
11949 
11950 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11951                                            SourceLocation FinalLoc,
11952                                            bool IsFinalSpelledSealed,
11953                                            SourceLocation LBraceLoc) {
11954   AdjustDeclIfTemplate(TagD);
11955   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11956 
11957   FieldCollector->StartClass();
11958 
11959   if (!Record->getIdentifier())
11960     return;
11961 
11962   if (FinalLoc.isValid())
11963     Record->addAttr(new (Context)
11964                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11965 
11966   // C++ [class]p2:
11967   //   [...] The class-name is also inserted into the scope of the
11968   //   class itself; this is known as the injected-class-name. For
11969   //   purposes of access checking, the injected-class-name is treated
11970   //   as if it were a public member name.
11971   CXXRecordDecl *InjectedClassName
11972     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11973                             Record->getLocStart(), Record->getLocation(),
11974                             Record->getIdentifier(),
11975                             /*PrevDecl=*/nullptr,
11976                             /*DelayTypeCreation=*/true);
11977   Context.getTypeDeclType(InjectedClassName, Record);
11978   InjectedClassName->setImplicit();
11979   InjectedClassName->setAccess(AS_public);
11980   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11981       InjectedClassName->setDescribedClassTemplate(Template);
11982   PushOnScopeChains(InjectedClassName, S);
11983   assert(InjectedClassName->isInjectedClassName() &&
11984          "Broken injected-class-name");
11985 }
11986 
11987 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11988                                     SourceLocation RBraceLoc) {
11989   AdjustDeclIfTemplate(TagD);
11990   TagDecl *Tag = cast<TagDecl>(TagD);
11991   Tag->setRBraceLoc(RBraceLoc);
11992 
11993   // Make sure we "complete" the definition even it is invalid.
11994   if (Tag->isBeingDefined()) {
11995     assert(Tag->isInvalidDecl() && "We should already have completed it");
11996     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11997       RD->completeDefinition();
11998   }
11999 
12000   if (isa<CXXRecordDecl>(Tag))
12001     FieldCollector->FinishClass();
12002 
12003   // Exit this scope of this tag's definition.
12004   PopDeclContext();
12005 
12006   if (getCurLexicalContext()->isObjCContainer() &&
12007       Tag->getDeclContext()->isFileContext())
12008     Tag->setTopLevelDeclInObjCContainer();
12009 
12010   // Notify the consumer that we've defined a tag.
12011   if (!Tag->isInvalidDecl())
12012     Consumer.HandleTagDeclDefinition(Tag);
12013 }
12014 
12015 void Sema::ActOnObjCContainerFinishDefinition() {
12016   // Exit this scope of this interface definition.
12017   PopDeclContext();
12018 }
12019 
12020 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12021   assert(DC == CurContext && "Mismatch of container contexts");
12022   OriginalLexicalContext = DC;
12023   ActOnObjCContainerFinishDefinition();
12024 }
12025 
12026 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12027   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12028   OriginalLexicalContext = nullptr;
12029 }
12030 
12031 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12032   AdjustDeclIfTemplate(TagD);
12033   TagDecl *Tag = cast<TagDecl>(TagD);
12034   Tag->setInvalidDecl();
12035 
12036   // Make sure we "complete" the definition even it is invalid.
12037   if (Tag->isBeingDefined()) {
12038     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12039       RD->completeDefinition();
12040   }
12041 
12042   // We're undoing ActOnTagStartDefinition here, not
12043   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12044   // the FieldCollector.
12045 
12046   PopDeclContext();
12047 }
12048 
12049 // Note that FieldName may be null for anonymous bitfields.
12050 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12051                                 IdentifierInfo *FieldName,
12052                                 QualType FieldTy, bool IsMsStruct,
12053                                 Expr *BitWidth, bool *ZeroWidth) {
12054   // Default to true; that shouldn't confuse checks for emptiness
12055   if (ZeroWidth)
12056     *ZeroWidth = true;
12057 
12058   // C99 6.7.2.1p4 - verify the field type.
12059   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12060   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12061     // Handle incomplete types with specific error.
12062     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12063       return ExprError();
12064     if (FieldName)
12065       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12066         << FieldName << FieldTy << BitWidth->getSourceRange();
12067     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12068       << FieldTy << BitWidth->getSourceRange();
12069   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12070                                              UPPC_BitFieldWidth))
12071     return ExprError();
12072 
12073   // If the bit-width is type- or value-dependent, don't try to check
12074   // it now.
12075   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12076     return BitWidth;
12077 
12078   llvm::APSInt Value;
12079   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12080   if (ICE.isInvalid())
12081     return ICE;
12082   BitWidth = ICE.get();
12083 
12084   if (Value != 0 && ZeroWidth)
12085     *ZeroWidth = false;
12086 
12087   // Zero-width bitfield is ok for anonymous field.
12088   if (Value == 0 && FieldName)
12089     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12090 
12091   if (Value.isSigned() && Value.isNegative()) {
12092     if (FieldName)
12093       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12094                << FieldName << Value.toString(10);
12095     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12096       << Value.toString(10);
12097   }
12098 
12099   if (!FieldTy->isDependentType()) {
12100     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12101     if (Value.getZExtValue() > TypeSize) {
12102       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12103           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12104         if (FieldName)
12105           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12106             << FieldName << (unsigned)Value.getZExtValue()
12107             << (unsigned)TypeSize;
12108 
12109         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12110           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12111       }
12112 
12113       if (FieldName)
12114         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12115           << FieldName << (unsigned)Value.getZExtValue()
12116           << (unsigned)TypeSize;
12117       else
12118         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12119           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12120     }
12121   }
12122 
12123   return BitWidth;
12124 }
12125 
12126 /// ActOnField - Each field of a C struct/union is passed into this in order
12127 /// to create a FieldDecl object for it.
12128 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12129                        Declarator &D, Expr *BitfieldWidth) {
12130   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12131                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12132                                /*InitStyle=*/ICIS_NoInit, AS_public);
12133   return Res;
12134 }
12135 
12136 /// HandleField - Analyze a field of a C struct or a C++ data member.
12137 ///
12138 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12139                              SourceLocation DeclStart,
12140                              Declarator &D, Expr *BitWidth,
12141                              InClassInitStyle InitStyle,
12142                              AccessSpecifier AS) {
12143   IdentifierInfo *II = D.getIdentifier();
12144   SourceLocation Loc = DeclStart;
12145   if (II) Loc = D.getIdentifierLoc();
12146 
12147   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12148   QualType T = TInfo->getType();
12149   if (getLangOpts().CPlusPlus) {
12150     CheckExtraCXXDefaultArguments(D);
12151 
12152     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12153                                         UPPC_DataMemberType)) {
12154       D.setInvalidType();
12155       T = Context.IntTy;
12156       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12157     }
12158   }
12159 
12160   // TR 18037 does not allow fields to be declared with address spaces.
12161   if (T.getQualifiers().hasAddressSpace()) {
12162     Diag(Loc, diag::err_field_with_address_space);
12163     D.setInvalidType();
12164   }
12165 
12166   // OpenCL 1.2 spec, s6.9 r:
12167   // The event type cannot be used to declare a structure or union field.
12168   if (LangOpts.OpenCL && T->isEventT()) {
12169     Diag(Loc, diag::err_event_t_struct_field);
12170     D.setInvalidType();
12171   }
12172 
12173   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12174 
12175   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12176     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12177          diag::err_invalid_thread)
12178       << DeclSpec::getSpecifierName(TSCS);
12179 
12180   // Check to see if this name was declared as a member previously
12181   NamedDecl *PrevDecl = nullptr;
12182   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12183   LookupName(Previous, S);
12184   switch (Previous.getResultKind()) {
12185     case LookupResult::Found:
12186     case LookupResult::FoundUnresolvedValue:
12187       PrevDecl = Previous.getAsSingle<NamedDecl>();
12188       break;
12189 
12190     case LookupResult::FoundOverloaded:
12191       PrevDecl = Previous.getRepresentativeDecl();
12192       break;
12193 
12194     case LookupResult::NotFound:
12195     case LookupResult::NotFoundInCurrentInstantiation:
12196     case LookupResult::Ambiguous:
12197       break;
12198   }
12199   Previous.suppressDiagnostics();
12200 
12201   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12202     // Maybe we will complain about the shadowed template parameter.
12203     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12204     // Just pretend that we didn't see the previous declaration.
12205     PrevDecl = nullptr;
12206   }
12207 
12208   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12209     PrevDecl = nullptr;
12210 
12211   bool Mutable
12212     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12213   SourceLocation TSSL = D.getLocStart();
12214   FieldDecl *NewFD
12215     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12216                      TSSL, AS, PrevDecl, &D);
12217 
12218   if (NewFD->isInvalidDecl())
12219     Record->setInvalidDecl();
12220 
12221   if (D.getDeclSpec().isModulePrivateSpecified())
12222     NewFD->setModulePrivate();
12223 
12224   if (NewFD->isInvalidDecl() && PrevDecl) {
12225     // Don't introduce NewFD into scope; there's already something
12226     // with the same name in the same scope.
12227   } else if (II) {
12228     PushOnScopeChains(NewFD, S);
12229   } else
12230     Record->addDecl(NewFD);
12231 
12232   return NewFD;
12233 }
12234 
12235 /// \brief Build a new FieldDecl and check its well-formedness.
12236 ///
12237 /// This routine builds a new FieldDecl given the fields name, type,
12238 /// record, etc. \p PrevDecl should refer to any previous declaration
12239 /// with the same name and in the same scope as the field to be
12240 /// created.
12241 ///
12242 /// \returns a new FieldDecl.
12243 ///
12244 /// \todo The Declarator argument is a hack. It will be removed once
12245 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12246                                 TypeSourceInfo *TInfo,
12247                                 RecordDecl *Record, SourceLocation Loc,
12248                                 bool Mutable, Expr *BitWidth,
12249                                 InClassInitStyle InitStyle,
12250                                 SourceLocation TSSL,
12251                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12252                                 Declarator *D) {
12253   IdentifierInfo *II = Name.getAsIdentifierInfo();
12254   bool InvalidDecl = false;
12255   if (D) InvalidDecl = D->isInvalidType();
12256 
12257   // If we receive a broken type, recover by assuming 'int' and
12258   // marking this declaration as invalid.
12259   if (T.isNull()) {
12260     InvalidDecl = true;
12261     T = Context.IntTy;
12262   }
12263 
12264   QualType EltTy = Context.getBaseElementType(T);
12265   if (!EltTy->isDependentType()) {
12266     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12267       // Fields of incomplete type force their record to be invalid.
12268       Record->setInvalidDecl();
12269       InvalidDecl = true;
12270     } else {
12271       NamedDecl *Def;
12272       EltTy->isIncompleteType(&Def);
12273       if (Def && Def->isInvalidDecl()) {
12274         Record->setInvalidDecl();
12275         InvalidDecl = true;
12276       }
12277     }
12278   }
12279 
12280   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12281   if (BitWidth && getLangOpts().OpenCL) {
12282     Diag(Loc, diag::err_opencl_bitfields);
12283     InvalidDecl = true;
12284   }
12285 
12286   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12287   // than a variably modified type.
12288   if (!InvalidDecl && T->isVariablyModifiedType()) {
12289     bool SizeIsNegative;
12290     llvm::APSInt Oversized;
12291 
12292     TypeSourceInfo *FixedTInfo =
12293       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12294                                                     SizeIsNegative,
12295                                                     Oversized);
12296     if (FixedTInfo) {
12297       Diag(Loc, diag::warn_illegal_constant_array_size);
12298       TInfo = FixedTInfo;
12299       T = FixedTInfo->getType();
12300     } else {
12301       if (SizeIsNegative)
12302         Diag(Loc, diag::err_typecheck_negative_array_size);
12303       else if (Oversized.getBoolValue())
12304         Diag(Loc, diag::err_array_too_large)
12305           << Oversized.toString(10);
12306       else
12307         Diag(Loc, diag::err_typecheck_field_variable_size);
12308       InvalidDecl = true;
12309     }
12310   }
12311 
12312   // Fields can not have abstract class types
12313   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12314                                              diag::err_abstract_type_in_decl,
12315                                              AbstractFieldType))
12316     InvalidDecl = true;
12317 
12318   bool ZeroWidth = false;
12319   // If this is declared as a bit-field, check the bit-field.
12320   if (!InvalidDecl && BitWidth) {
12321     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12322                               &ZeroWidth).get();
12323     if (!BitWidth) {
12324       InvalidDecl = true;
12325       BitWidth = nullptr;
12326       ZeroWidth = false;
12327     }
12328   }
12329 
12330   // Check that 'mutable' is consistent with the type of the declaration.
12331   if (!InvalidDecl && Mutable) {
12332     unsigned DiagID = 0;
12333     if (T->isReferenceType())
12334       DiagID = diag::err_mutable_reference;
12335     else if (T.isConstQualified())
12336       DiagID = diag::err_mutable_const;
12337 
12338     if (DiagID) {
12339       SourceLocation ErrLoc = Loc;
12340       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12341         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12342       Diag(ErrLoc, DiagID);
12343       Mutable = false;
12344       InvalidDecl = true;
12345     }
12346   }
12347 
12348   // C++11 [class.union]p8 (DR1460):
12349   //   At most one variant member of a union may have a
12350   //   brace-or-equal-initializer.
12351   if (InitStyle != ICIS_NoInit)
12352     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12353 
12354   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12355                                        BitWidth, Mutable, InitStyle);
12356   if (InvalidDecl)
12357     NewFD->setInvalidDecl();
12358 
12359   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12360     Diag(Loc, diag::err_duplicate_member) << II;
12361     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12362     NewFD->setInvalidDecl();
12363   }
12364 
12365   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12366     if (Record->isUnion()) {
12367       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12368         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12369         if (RDecl->getDefinition()) {
12370           // C++ [class.union]p1: An object of a class with a non-trivial
12371           // constructor, a non-trivial copy constructor, a non-trivial
12372           // destructor, or a non-trivial copy assignment operator
12373           // cannot be a member of a union, nor can an array of such
12374           // objects.
12375           if (CheckNontrivialField(NewFD))
12376             NewFD->setInvalidDecl();
12377         }
12378       }
12379 
12380       // C++ [class.union]p1: If a union contains a member of reference type,
12381       // the program is ill-formed, except when compiling with MSVC extensions
12382       // enabled.
12383       if (EltTy->isReferenceType()) {
12384         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12385                                     diag::ext_union_member_of_reference_type :
12386                                     diag::err_union_member_of_reference_type)
12387           << NewFD->getDeclName() << EltTy;
12388         if (!getLangOpts().MicrosoftExt)
12389           NewFD->setInvalidDecl();
12390       }
12391     }
12392   }
12393 
12394   // FIXME: We need to pass in the attributes given an AST
12395   // representation, not a parser representation.
12396   if (D) {
12397     // FIXME: The current scope is almost... but not entirely... correct here.
12398     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12399 
12400     if (NewFD->hasAttrs())
12401       CheckAlignasUnderalignment(NewFD);
12402   }
12403 
12404   // In auto-retain/release, infer strong retension for fields of
12405   // retainable type.
12406   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12407     NewFD->setInvalidDecl();
12408 
12409   if (T.isObjCGCWeak())
12410     Diag(Loc, diag::warn_attribute_weak_on_field);
12411 
12412   NewFD->setAccess(AS);
12413   return NewFD;
12414 }
12415 
12416 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12417   assert(FD);
12418   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12419 
12420   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12421     return false;
12422 
12423   QualType EltTy = Context.getBaseElementType(FD->getType());
12424   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12425     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12426     if (RDecl->getDefinition()) {
12427       // We check for copy constructors before constructors
12428       // because otherwise we'll never get complaints about
12429       // copy constructors.
12430 
12431       CXXSpecialMember member = CXXInvalid;
12432       // We're required to check for any non-trivial constructors. Since the
12433       // implicit default constructor is suppressed if there are any
12434       // user-declared constructors, we just need to check that there is a
12435       // trivial default constructor and a trivial copy constructor. (We don't
12436       // worry about move constructors here, since this is a C++98 check.)
12437       if (RDecl->hasNonTrivialCopyConstructor())
12438         member = CXXCopyConstructor;
12439       else if (!RDecl->hasTrivialDefaultConstructor())
12440         member = CXXDefaultConstructor;
12441       else if (RDecl->hasNonTrivialCopyAssignment())
12442         member = CXXCopyAssignment;
12443       else if (RDecl->hasNonTrivialDestructor())
12444         member = CXXDestructor;
12445 
12446       if (member != CXXInvalid) {
12447         if (!getLangOpts().CPlusPlus11 &&
12448             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12449           // Objective-C++ ARC: it is an error to have a non-trivial field of
12450           // a union. However, system headers in Objective-C programs
12451           // occasionally have Objective-C lifetime objects within unions,
12452           // and rather than cause the program to fail, we make those
12453           // members unavailable.
12454           SourceLocation Loc = FD->getLocation();
12455           if (getSourceManager().isInSystemHeader(Loc)) {
12456             if (!FD->hasAttr<UnavailableAttr>())
12457               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12458                                   "this system field has retaining ownership",
12459                                   Loc));
12460             return false;
12461           }
12462         }
12463 
12464         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12465                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12466                diag::err_illegal_union_or_anon_struct_member)
12467           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12468         DiagnoseNontrivial(RDecl, member);
12469         return !getLangOpts().CPlusPlus11;
12470       }
12471     }
12472   }
12473 
12474   return false;
12475 }
12476 
12477 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12478 ///  AST enum value.
12479 static ObjCIvarDecl::AccessControl
12480 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12481   switch (ivarVisibility) {
12482   default: llvm_unreachable("Unknown visitibility kind");
12483   case tok::objc_private: return ObjCIvarDecl::Private;
12484   case tok::objc_public: return ObjCIvarDecl::Public;
12485   case tok::objc_protected: return ObjCIvarDecl::Protected;
12486   case tok::objc_package: return ObjCIvarDecl::Package;
12487   }
12488 }
12489 
12490 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12491 /// in order to create an IvarDecl object for it.
12492 Decl *Sema::ActOnIvar(Scope *S,
12493                                 SourceLocation DeclStart,
12494                                 Declarator &D, Expr *BitfieldWidth,
12495                                 tok::ObjCKeywordKind Visibility) {
12496 
12497   IdentifierInfo *II = D.getIdentifier();
12498   Expr *BitWidth = (Expr*)BitfieldWidth;
12499   SourceLocation Loc = DeclStart;
12500   if (II) Loc = D.getIdentifierLoc();
12501 
12502   // FIXME: Unnamed fields can be handled in various different ways, for
12503   // example, unnamed unions inject all members into the struct namespace!
12504 
12505   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12506   QualType T = TInfo->getType();
12507 
12508   if (BitWidth) {
12509     // 6.7.2.1p3, 6.7.2.1p4
12510     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12511     if (!BitWidth)
12512       D.setInvalidType();
12513   } else {
12514     // Not a bitfield.
12515 
12516     // validate II.
12517 
12518   }
12519   if (T->isReferenceType()) {
12520     Diag(Loc, diag::err_ivar_reference_type);
12521     D.setInvalidType();
12522   }
12523   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12524   // than a variably modified type.
12525   else if (T->isVariablyModifiedType()) {
12526     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12527     D.setInvalidType();
12528   }
12529 
12530   // Get the visibility (access control) for this ivar.
12531   ObjCIvarDecl::AccessControl ac =
12532     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12533                                         : ObjCIvarDecl::None;
12534   // Must set ivar's DeclContext to its enclosing interface.
12535   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12536   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12537     return nullptr;
12538   ObjCContainerDecl *EnclosingContext;
12539   if (ObjCImplementationDecl *IMPDecl =
12540       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12541     if (LangOpts.ObjCRuntime.isFragile()) {
12542     // Case of ivar declared in an implementation. Context is that of its class.
12543       EnclosingContext = IMPDecl->getClassInterface();
12544       assert(EnclosingContext && "Implementation has no class interface!");
12545     }
12546     else
12547       EnclosingContext = EnclosingDecl;
12548   } else {
12549     if (ObjCCategoryDecl *CDecl =
12550         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12551       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12552         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12553         return nullptr;
12554       }
12555     }
12556     EnclosingContext = EnclosingDecl;
12557   }
12558 
12559   // Construct the decl.
12560   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12561                                              DeclStart, Loc, II, T,
12562                                              TInfo, ac, (Expr *)BitfieldWidth);
12563 
12564   if (II) {
12565     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12566                                            ForRedeclaration);
12567     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12568         && !isa<TagDecl>(PrevDecl)) {
12569       Diag(Loc, diag::err_duplicate_member) << II;
12570       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12571       NewID->setInvalidDecl();
12572     }
12573   }
12574 
12575   // Process attributes attached to the ivar.
12576   ProcessDeclAttributes(S, NewID, D);
12577 
12578   if (D.isInvalidType())
12579     NewID->setInvalidDecl();
12580 
12581   // In ARC, infer 'retaining' for ivars of retainable type.
12582   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12583     NewID->setInvalidDecl();
12584 
12585   if (D.getDeclSpec().isModulePrivateSpecified())
12586     NewID->setModulePrivate();
12587 
12588   if (II) {
12589     // FIXME: When interfaces are DeclContexts, we'll need to add
12590     // these to the interface.
12591     S->AddDecl(NewID);
12592     IdResolver.AddDecl(NewID);
12593   }
12594 
12595   if (LangOpts.ObjCRuntime.isNonFragile() &&
12596       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12597     Diag(Loc, diag::warn_ivars_in_interface);
12598 
12599   return NewID;
12600 }
12601 
12602 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12603 /// class and class extensions. For every class \@interface and class
12604 /// extension \@interface, if the last ivar is a bitfield of any type,
12605 /// then add an implicit `char :0` ivar to the end of that interface.
12606 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12607                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12608   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12609     return;
12610 
12611   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12612   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12613 
12614   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12615     return;
12616   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12617   if (!ID) {
12618     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12619       if (!CD->IsClassExtension())
12620         return;
12621     }
12622     // No need to add this to end of @implementation.
12623     else
12624       return;
12625   }
12626   // All conditions are met. Add a new bitfield to the tail end of ivars.
12627   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12628   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12629 
12630   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12631                               DeclLoc, DeclLoc, nullptr,
12632                               Context.CharTy,
12633                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12634                                                                DeclLoc),
12635                               ObjCIvarDecl::Private, BW,
12636                               true);
12637   AllIvarDecls.push_back(Ivar);
12638 }
12639 
12640 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12641                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12642                        SourceLocation RBrac, AttributeList *Attr) {
12643   assert(EnclosingDecl && "missing record or interface decl");
12644 
12645   // If this is an Objective-C @implementation or category and we have
12646   // new fields here we should reset the layout of the interface since
12647   // it will now change.
12648   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12649     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12650     switch (DC->getKind()) {
12651     default: break;
12652     case Decl::ObjCCategory:
12653       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12654       break;
12655     case Decl::ObjCImplementation:
12656       Context.
12657         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12658       break;
12659     }
12660   }
12661 
12662   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12663 
12664   // Start counting up the number of named members; make sure to include
12665   // members of anonymous structs and unions in the total.
12666   unsigned NumNamedMembers = 0;
12667   if (Record) {
12668     for (const auto *I : Record->decls()) {
12669       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12670         if (IFD->getDeclName())
12671           ++NumNamedMembers;
12672     }
12673   }
12674 
12675   // Verify that all the fields are okay.
12676   SmallVector<FieldDecl*, 32> RecFields;
12677 
12678   bool ARCErrReported = false;
12679   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12680        i != end; ++i) {
12681     FieldDecl *FD = cast<FieldDecl>(*i);
12682 
12683     // Get the type for the field.
12684     const Type *FDTy = FD->getType().getTypePtr();
12685 
12686     if (!FD->isAnonymousStructOrUnion()) {
12687       // Remember all fields written by the user.
12688       RecFields.push_back(FD);
12689     }
12690 
12691     // If the field is already invalid for some reason, don't emit more
12692     // diagnostics about it.
12693     if (FD->isInvalidDecl()) {
12694       EnclosingDecl->setInvalidDecl();
12695       continue;
12696     }
12697 
12698     // C99 6.7.2.1p2:
12699     //   A structure or union shall not contain a member with
12700     //   incomplete or function type (hence, a structure shall not
12701     //   contain an instance of itself, but may contain a pointer to
12702     //   an instance of itself), except that the last member of a
12703     //   structure with more than one named member may have incomplete
12704     //   array type; such a structure (and any union containing,
12705     //   possibly recursively, a member that is such a structure)
12706     //   shall not be a member of a structure or an element of an
12707     //   array.
12708     if (FDTy->isFunctionType()) {
12709       // Field declared as a function.
12710       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12711         << FD->getDeclName();
12712       FD->setInvalidDecl();
12713       EnclosingDecl->setInvalidDecl();
12714       continue;
12715     } else if (FDTy->isIncompleteArrayType() && Record &&
12716                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12717                 ((getLangOpts().MicrosoftExt ||
12718                   getLangOpts().CPlusPlus) &&
12719                  (i + 1 == Fields.end() || Record->isUnion())))) {
12720       // Flexible array member.
12721       // Microsoft and g++ is more permissive regarding flexible array.
12722       // It will accept flexible array in union and also
12723       // as the sole element of a struct/class.
12724       unsigned DiagID = 0;
12725       if (Record->isUnion())
12726         DiagID = getLangOpts().MicrosoftExt
12727                      ? diag::ext_flexible_array_union_ms
12728                      : getLangOpts().CPlusPlus
12729                            ? diag::ext_flexible_array_union_gnu
12730                            : diag::err_flexible_array_union;
12731       else if (Fields.size() == 1)
12732         DiagID = getLangOpts().MicrosoftExt
12733                      ? diag::ext_flexible_array_empty_aggregate_ms
12734                      : getLangOpts().CPlusPlus
12735                            ? diag::ext_flexible_array_empty_aggregate_gnu
12736                            : NumNamedMembers < 1
12737                                  ? diag::err_flexible_array_empty_aggregate
12738                                  : 0;
12739 
12740       if (DiagID)
12741         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12742                                         << Record->getTagKind();
12743       // While the layout of types that contain virtual bases is not specified
12744       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12745       // virtual bases after the derived members.  This would make a flexible
12746       // array member declared at the end of an object not adjacent to the end
12747       // of the type.
12748       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12749         if (RD->getNumVBases() != 0)
12750           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12751             << FD->getDeclName() << Record->getTagKind();
12752       if (!getLangOpts().C99)
12753         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12754           << FD->getDeclName() << Record->getTagKind();
12755 
12756       // If the element type has a non-trivial destructor, we would not
12757       // implicitly destroy the elements, so disallow it for now.
12758       //
12759       // FIXME: GCC allows this. We should probably either implicitly delete
12760       // the destructor of the containing class, or just allow this.
12761       QualType BaseElem = Context.getBaseElementType(FD->getType());
12762       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12763         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12764           << FD->getDeclName() << FD->getType();
12765         FD->setInvalidDecl();
12766         EnclosingDecl->setInvalidDecl();
12767         continue;
12768       }
12769       // Okay, we have a legal flexible array member at the end of the struct.
12770       Record->setHasFlexibleArrayMember(true);
12771     } else if (!FDTy->isDependentType() &&
12772                RequireCompleteType(FD->getLocation(), FD->getType(),
12773                                    diag::err_field_incomplete)) {
12774       // Incomplete type
12775       FD->setInvalidDecl();
12776       EnclosingDecl->setInvalidDecl();
12777       continue;
12778     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12779       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12780         // A type which contains a flexible array member is considered to be a
12781         // flexible array member.
12782         Record->setHasFlexibleArrayMember(true);
12783         if (!Record->isUnion()) {
12784           // If this is a struct/class and this is not the last element, reject
12785           // it.  Note that GCC supports variable sized arrays in the middle of
12786           // structures.
12787           if (i + 1 != Fields.end())
12788             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12789               << FD->getDeclName() << FD->getType();
12790           else {
12791             // We support flexible arrays at the end of structs in
12792             // other structs as an extension.
12793             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12794               << FD->getDeclName();
12795           }
12796         }
12797       }
12798       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12799           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12800                                  diag::err_abstract_type_in_decl,
12801                                  AbstractIvarType)) {
12802         // Ivars can not have abstract class types
12803         FD->setInvalidDecl();
12804       }
12805       if (Record && FDTTy->getDecl()->hasObjectMember())
12806         Record->setHasObjectMember(true);
12807       if (Record && FDTTy->getDecl()->hasVolatileMember())
12808         Record->setHasVolatileMember(true);
12809     } else if (FDTy->isObjCObjectType()) {
12810       /// A field cannot be an Objective-c object
12811       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12812         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12813       QualType T = Context.getObjCObjectPointerType(FD->getType());
12814       FD->setType(T);
12815     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12816                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12817       // It's an error in ARC if a field has lifetime.
12818       // We don't want to report this in a system header, though,
12819       // so we just make the field unavailable.
12820       // FIXME: that's really not sufficient; we need to make the type
12821       // itself invalid to, say, initialize or copy.
12822       QualType T = FD->getType();
12823       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12824       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12825         SourceLocation loc = FD->getLocation();
12826         if (getSourceManager().isInSystemHeader(loc)) {
12827           if (!FD->hasAttr<UnavailableAttr>()) {
12828             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12829                               "this system field has retaining ownership",
12830                               loc));
12831           }
12832         } else {
12833           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12834             << T->isBlockPointerType() << Record->getTagKind();
12835         }
12836         ARCErrReported = true;
12837       }
12838     } else if (getLangOpts().ObjC1 &&
12839                getLangOpts().getGC() != LangOptions::NonGC &&
12840                Record && !Record->hasObjectMember()) {
12841       if (FD->getType()->isObjCObjectPointerType() ||
12842           FD->getType().isObjCGCStrong())
12843         Record->setHasObjectMember(true);
12844       else if (Context.getAsArrayType(FD->getType())) {
12845         QualType BaseType = Context.getBaseElementType(FD->getType());
12846         if (BaseType->isRecordType() &&
12847             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12848           Record->setHasObjectMember(true);
12849         else if (BaseType->isObjCObjectPointerType() ||
12850                  BaseType.isObjCGCStrong())
12851                Record->setHasObjectMember(true);
12852       }
12853     }
12854     if (Record && FD->getType().isVolatileQualified())
12855       Record->setHasVolatileMember(true);
12856     // Keep track of the number of named members.
12857     if (FD->getIdentifier())
12858       ++NumNamedMembers;
12859   }
12860 
12861   // Okay, we successfully defined 'Record'.
12862   if (Record) {
12863     bool Completed = false;
12864     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12865       if (!CXXRecord->isInvalidDecl()) {
12866         // Set access bits correctly on the directly-declared conversions.
12867         for (CXXRecordDecl::conversion_iterator
12868                I = CXXRecord->conversion_begin(),
12869                E = CXXRecord->conversion_end(); I != E; ++I)
12870           I.setAccess((*I)->getAccess());
12871 
12872         if (!CXXRecord->isDependentType()) {
12873           if (CXXRecord->hasUserDeclaredDestructor()) {
12874             // Adjust user-defined destructor exception spec.
12875             if (getLangOpts().CPlusPlus11)
12876               AdjustDestructorExceptionSpec(CXXRecord,
12877                                             CXXRecord->getDestructor());
12878           }
12879 
12880           // Add any implicitly-declared members to this class.
12881           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12882 
12883           // If we have virtual base classes, we may end up finding multiple
12884           // final overriders for a given virtual function. Check for this
12885           // problem now.
12886           if (CXXRecord->getNumVBases()) {
12887             CXXFinalOverriderMap FinalOverriders;
12888             CXXRecord->getFinalOverriders(FinalOverriders);
12889 
12890             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12891                                              MEnd = FinalOverriders.end();
12892                  M != MEnd; ++M) {
12893               for (OverridingMethods::iterator SO = M->second.begin(),
12894                                             SOEnd = M->second.end();
12895                    SO != SOEnd; ++SO) {
12896                 assert(SO->second.size() > 0 &&
12897                        "Virtual function without overridding functions?");
12898                 if (SO->second.size() == 1)
12899                   continue;
12900 
12901                 // C++ [class.virtual]p2:
12902                 //   In a derived class, if a virtual member function of a base
12903                 //   class subobject has more than one final overrider the
12904                 //   program is ill-formed.
12905                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12906                   << (const NamedDecl *)M->first << Record;
12907                 Diag(M->first->getLocation(),
12908                      diag::note_overridden_virtual_function);
12909                 for (OverridingMethods::overriding_iterator
12910                           OM = SO->second.begin(),
12911                        OMEnd = SO->second.end();
12912                      OM != OMEnd; ++OM)
12913                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12914                     << (const NamedDecl *)M->first << OM->Method->getParent();
12915 
12916                 Record->setInvalidDecl();
12917               }
12918             }
12919             CXXRecord->completeDefinition(&FinalOverriders);
12920             Completed = true;
12921           }
12922         }
12923       }
12924     }
12925 
12926     if (!Completed)
12927       Record->completeDefinition();
12928 
12929     if (Record->hasAttrs()) {
12930       CheckAlignasUnderalignment(Record);
12931 
12932       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12933         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12934                                            IA->getRange(), IA->getBestCase(),
12935                                            IA->getSemanticSpelling());
12936     }
12937 
12938     // Check if the structure/union declaration is a type that can have zero
12939     // size in C. For C this is a language extension, for C++ it may cause
12940     // compatibility problems.
12941     bool CheckForZeroSize;
12942     if (!getLangOpts().CPlusPlus) {
12943       CheckForZeroSize = true;
12944     } else {
12945       // For C++ filter out types that cannot be referenced in C code.
12946       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12947       CheckForZeroSize =
12948           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12949           !CXXRecord->isDependentType() &&
12950           CXXRecord->isCLike();
12951     }
12952     if (CheckForZeroSize) {
12953       bool ZeroSize = true;
12954       bool IsEmpty = true;
12955       unsigned NonBitFields = 0;
12956       for (RecordDecl::field_iterator I = Record->field_begin(),
12957                                       E = Record->field_end();
12958            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12959         IsEmpty = false;
12960         if (I->isUnnamedBitfield()) {
12961           if (I->getBitWidthValue(Context) > 0)
12962             ZeroSize = false;
12963         } else {
12964           ++NonBitFields;
12965           QualType FieldType = I->getType();
12966           if (FieldType->isIncompleteType() ||
12967               !Context.getTypeSizeInChars(FieldType).isZero())
12968             ZeroSize = false;
12969         }
12970       }
12971 
12972       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12973       // allowed in C++, but warn if its declaration is inside
12974       // extern "C" block.
12975       if (ZeroSize) {
12976         Diag(RecLoc, getLangOpts().CPlusPlus ?
12977                          diag::warn_zero_size_struct_union_in_extern_c :
12978                          diag::warn_zero_size_struct_union_compat)
12979           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12980       }
12981 
12982       // Structs without named members are extension in C (C99 6.7.2.1p7),
12983       // but are accepted by GCC.
12984       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12985         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12986                                diag::ext_no_named_members_in_struct_union)
12987           << Record->isUnion();
12988       }
12989     }
12990   } else {
12991     ObjCIvarDecl **ClsFields =
12992       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12993     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12994       ID->setEndOfDefinitionLoc(RBrac);
12995       // Add ivar's to class's DeclContext.
12996       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12997         ClsFields[i]->setLexicalDeclContext(ID);
12998         ID->addDecl(ClsFields[i]);
12999       }
13000       // Must enforce the rule that ivars in the base classes may not be
13001       // duplicates.
13002       if (ID->getSuperClass())
13003         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13004     } else if (ObjCImplementationDecl *IMPDecl =
13005                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13006       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13007       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13008         // Ivar declared in @implementation never belongs to the implementation.
13009         // Only it is in implementation's lexical context.
13010         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13011       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13012       IMPDecl->setIvarLBraceLoc(LBrac);
13013       IMPDecl->setIvarRBraceLoc(RBrac);
13014     } else if (ObjCCategoryDecl *CDecl =
13015                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13016       // case of ivars in class extension; all other cases have been
13017       // reported as errors elsewhere.
13018       // FIXME. Class extension does not have a LocEnd field.
13019       // CDecl->setLocEnd(RBrac);
13020       // Add ivar's to class extension's DeclContext.
13021       // Diagnose redeclaration of private ivars.
13022       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13023       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13024         if (IDecl) {
13025           if (const ObjCIvarDecl *ClsIvar =
13026               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13027             Diag(ClsFields[i]->getLocation(),
13028                  diag::err_duplicate_ivar_declaration);
13029             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13030             continue;
13031           }
13032           for (const auto *Ext : IDecl->known_extensions()) {
13033             if (const ObjCIvarDecl *ClsExtIvar
13034                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13035               Diag(ClsFields[i]->getLocation(),
13036                    diag::err_duplicate_ivar_declaration);
13037               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13038               continue;
13039             }
13040           }
13041         }
13042         ClsFields[i]->setLexicalDeclContext(CDecl);
13043         CDecl->addDecl(ClsFields[i]);
13044       }
13045       CDecl->setIvarLBraceLoc(LBrac);
13046       CDecl->setIvarRBraceLoc(RBrac);
13047     }
13048   }
13049 
13050   if (Attr)
13051     ProcessDeclAttributeList(S, Record, Attr);
13052 }
13053 
13054 /// \brief Determine whether the given integral value is representable within
13055 /// the given type T.
13056 static bool isRepresentableIntegerValue(ASTContext &Context,
13057                                         llvm::APSInt &Value,
13058                                         QualType T) {
13059   assert(T->isIntegralType(Context) && "Integral type required!");
13060   unsigned BitWidth = Context.getIntWidth(T);
13061 
13062   if (Value.isUnsigned() || Value.isNonNegative()) {
13063     if (T->isSignedIntegerOrEnumerationType())
13064       --BitWidth;
13065     return Value.getActiveBits() <= BitWidth;
13066   }
13067   return Value.getMinSignedBits() <= BitWidth;
13068 }
13069 
13070 // \brief Given an integral type, return the next larger integral type
13071 // (or a NULL type of no such type exists).
13072 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13073   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13074   // enum checking below.
13075   assert(T->isIntegralType(Context) && "Integral type required!");
13076   const unsigned NumTypes = 4;
13077   QualType SignedIntegralTypes[NumTypes] = {
13078     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13079   };
13080   QualType UnsignedIntegralTypes[NumTypes] = {
13081     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13082     Context.UnsignedLongLongTy
13083   };
13084 
13085   unsigned BitWidth = Context.getTypeSize(T);
13086   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13087                                                         : UnsignedIntegralTypes;
13088   for (unsigned I = 0; I != NumTypes; ++I)
13089     if (Context.getTypeSize(Types[I]) > BitWidth)
13090       return Types[I];
13091 
13092   return QualType();
13093 }
13094 
13095 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13096                                           EnumConstantDecl *LastEnumConst,
13097                                           SourceLocation IdLoc,
13098                                           IdentifierInfo *Id,
13099                                           Expr *Val) {
13100   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13101   llvm::APSInt EnumVal(IntWidth);
13102   QualType EltTy;
13103 
13104   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13105     Val = nullptr;
13106 
13107   if (Val)
13108     Val = DefaultLvalueConversion(Val).get();
13109 
13110   if (Val) {
13111     if (Enum->isDependentType() || Val->isTypeDependent())
13112       EltTy = Context.DependentTy;
13113     else {
13114       SourceLocation ExpLoc;
13115       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13116           !getLangOpts().MSVCCompat) {
13117         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13118         // constant-expression in the enumerator-definition shall be a converted
13119         // constant expression of the underlying type.
13120         EltTy = Enum->getIntegerType();
13121         ExprResult Converted =
13122           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13123                                            CCEK_Enumerator);
13124         if (Converted.isInvalid())
13125           Val = nullptr;
13126         else
13127           Val = Converted.get();
13128       } else if (!Val->isValueDependent() &&
13129                  !(Val = VerifyIntegerConstantExpression(Val,
13130                                                          &EnumVal).get())) {
13131         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13132       } else {
13133         if (Enum->isFixed()) {
13134           EltTy = Enum->getIntegerType();
13135 
13136           // In Obj-C and Microsoft mode, require the enumeration value to be
13137           // representable in the underlying type of the enumeration. In C++11,
13138           // we perform a non-narrowing conversion as part of converted constant
13139           // expression checking.
13140           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13141             if (getLangOpts().MSVCCompat) {
13142               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13143               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13144             } else
13145               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13146           } else
13147             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13148         } else if (getLangOpts().CPlusPlus) {
13149           // C++11 [dcl.enum]p5:
13150           //   If the underlying type is not fixed, the type of each enumerator
13151           //   is the type of its initializing value:
13152           //     - If an initializer is specified for an enumerator, the
13153           //       initializing value has the same type as the expression.
13154           EltTy = Val->getType();
13155         } else {
13156           // C99 6.7.2.2p2:
13157           //   The expression that defines the value of an enumeration constant
13158           //   shall be an integer constant expression that has a value
13159           //   representable as an int.
13160 
13161           // Complain if the value is not representable in an int.
13162           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13163             Diag(IdLoc, diag::ext_enum_value_not_int)
13164               << EnumVal.toString(10) << Val->getSourceRange()
13165               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13166           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13167             // Force the type of the expression to 'int'.
13168             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13169           }
13170           EltTy = Val->getType();
13171         }
13172       }
13173     }
13174   }
13175 
13176   if (!Val) {
13177     if (Enum->isDependentType())
13178       EltTy = Context.DependentTy;
13179     else if (!LastEnumConst) {
13180       // C++0x [dcl.enum]p5:
13181       //   If the underlying type is not fixed, the type of each enumerator
13182       //   is the type of its initializing value:
13183       //     - If no initializer is specified for the first enumerator, the
13184       //       initializing value has an unspecified integral type.
13185       //
13186       // GCC uses 'int' for its unspecified integral type, as does
13187       // C99 6.7.2.2p3.
13188       if (Enum->isFixed()) {
13189         EltTy = Enum->getIntegerType();
13190       }
13191       else {
13192         EltTy = Context.IntTy;
13193       }
13194     } else {
13195       // Assign the last value + 1.
13196       EnumVal = LastEnumConst->getInitVal();
13197       ++EnumVal;
13198       EltTy = LastEnumConst->getType();
13199 
13200       // Check for overflow on increment.
13201       if (EnumVal < LastEnumConst->getInitVal()) {
13202         // C++0x [dcl.enum]p5:
13203         //   If the underlying type is not fixed, the type of each enumerator
13204         //   is the type of its initializing value:
13205         //
13206         //     - Otherwise the type of the initializing value is the same as
13207         //       the type of the initializing value of the preceding enumerator
13208         //       unless the incremented value is not representable in that type,
13209         //       in which case the type is an unspecified integral type
13210         //       sufficient to contain the incremented value. If no such type
13211         //       exists, the program is ill-formed.
13212         QualType T = getNextLargerIntegralType(Context, EltTy);
13213         if (T.isNull() || Enum->isFixed()) {
13214           // There is no integral type larger enough to represent this
13215           // value. Complain, then allow the value to wrap around.
13216           EnumVal = LastEnumConst->getInitVal();
13217           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13218           ++EnumVal;
13219           if (Enum->isFixed())
13220             // When the underlying type is fixed, this is ill-formed.
13221             Diag(IdLoc, diag::err_enumerator_wrapped)
13222               << EnumVal.toString(10)
13223               << EltTy;
13224           else
13225             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13226               << EnumVal.toString(10);
13227         } else {
13228           EltTy = T;
13229         }
13230 
13231         // Retrieve the last enumerator's value, extent that type to the
13232         // type that is supposed to be large enough to represent the incremented
13233         // value, then increment.
13234         EnumVal = LastEnumConst->getInitVal();
13235         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13236         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13237         ++EnumVal;
13238 
13239         // If we're not in C++, diagnose the overflow of enumerator values,
13240         // which in C99 means that the enumerator value is not representable in
13241         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13242         // permits enumerator values that are representable in some larger
13243         // integral type.
13244         if (!getLangOpts().CPlusPlus && !T.isNull())
13245           Diag(IdLoc, diag::warn_enum_value_overflow);
13246       } else if (!getLangOpts().CPlusPlus &&
13247                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13248         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13249         Diag(IdLoc, diag::ext_enum_value_not_int)
13250           << EnumVal.toString(10) << 1;
13251       }
13252     }
13253   }
13254 
13255   if (!EltTy->isDependentType()) {
13256     // Make the enumerator value match the signedness and size of the
13257     // enumerator's type.
13258     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13259     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13260   }
13261 
13262   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13263                                   Val, EnumVal);
13264 }
13265 
13266 
13267 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13268                               SourceLocation IdLoc, IdentifierInfo *Id,
13269                               AttributeList *Attr,
13270                               SourceLocation EqualLoc, Expr *Val) {
13271   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13272   EnumConstantDecl *LastEnumConst =
13273     cast_or_null<EnumConstantDecl>(lastEnumConst);
13274 
13275   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13276   // we find one that is.
13277   S = getNonFieldDeclScope(S);
13278 
13279   // Verify that there isn't already something declared with this name in this
13280   // scope.
13281   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13282                                          ForRedeclaration);
13283   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13284     // Maybe we will complain about the shadowed template parameter.
13285     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13286     // Just pretend that we didn't see the previous declaration.
13287     PrevDecl = nullptr;
13288   }
13289 
13290   if (PrevDecl) {
13291     // When in C++, we may get a TagDecl with the same name; in this case the
13292     // enum constant will 'hide' the tag.
13293     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13294            "Received TagDecl when not in C++!");
13295     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13296       if (isa<EnumConstantDecl>(PrevDecl))
13297         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13298       else
13299         Diag(IdLoc, diag::err_redefinition) << Id;
13300       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13301       return nullptr;
13302     }
13303   }
13304 
13305   // C++ [class.mem]p15:
13306   // If T is the name of a class, then each of the following shall have a name
13307   // different from T:
13308   // - every enumerator of every member of class T that is an unscoped
13309   // enumerated type
13310   if (CXXRecordDecl *Record
13311                       = dyn_cast<CXXRecordDecl>(
13312                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13313     if (!TheEnumDecl->isScoped() &&
13314         Record->getIdentifier() && Record->getIdentifier() == Id)
13315       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13316 
13317   EnumConstantDecl *New =
13318     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13319 
13320   if (New) {
13321     // Process attributes.
13322     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13323 
13324     // Register this decl in the current scope stack.
13325     New->setAccess(TheEnumDecl->getAccess());
13326     PushOnScopeChains(New, S);
13327   }
13328 
13329   ActOnDocumentableDecl(New);
13330 
13331   return New;
13332 }
13333 
13334 // Returns true when the enum initial expression does not trigger the
13335 // duplicate enum warning.  A few common cases are exempted as follows:
13336 // Element2 = Element1
13337 // Element2 = Element1 + 1
13338 // Element2 = Element1 - 1
13339 // Where Element2 and Element1 are from the same enum.
13340 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13341   Expr *InitExpr = ECD->getInitExpr();
13342   if (!InitExpr)
13343     return true;
13344   InitExpr = InitExpr->IgnoreImpCasts();
13345 
13346   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13347     if (!BO->isAdditiveOp())
13348       return true;
13349     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13350     if (!IL)
13351       return true;
13352     if (IL->getValue() != 1)
13353       return true;
13354 
13355     InitExpr = BO->getLHS();
13356   }
13357 
13358   // This checks if the elements are from the same enum.
13359   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13360   if (!DRE)
13361     return true;
13362 
13363   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13364   if (!EnumConstant)
13365     return true;
13366 
13367   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13368       Enum)
13369     return true;
13370 
13371   return false;
13372 }
13373 
13374 struct DupKey {
13375   int64_t val;
13376   bool isTombstoneOrEmptyKey;
13377   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13378     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13379 };
13380 
13381 static DupKey GetDupKey(const llvm::APSInt& Val) {
13382   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13383                 false);
13384 }
13385 
13386 struct DenseMapInfoDupKey {
13387   static DupKey getEmptyKey() { return DupKey(0, true); }
13388   static DupKey getTombstoneKey() { return DupKey(1, true); }
13389   static unsigned getHashValue(const DupKey Key) {
13390     return (unsigned)(Key.val * 37);
13391   }
13392   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13393     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13394            LHS.val == RHS.val;
13395   }
13396 };
13397 
13398 // Emits a warning when an element is implicitly set a value that
13399 // a previous element has already been set to.
13400 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13401                                         EnumDecl *Enum,
13402                                         QualType EnumType) {
13403   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13404     return;
13405   // Avoid anonymous enums
13406   if (!Enum->getIdentifier())
13407     return;
13408 
13409   // Only check for small enums.
13410   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13411     return;
13412 
13413   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13414   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13415 
13416   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13417   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13418           ValueToVectorMap;
13419 
13420   DuplicatesVector DupVector;
13421   ValueToVectorMap EnumMap;
13422 
13423   // Populate the EnumMap with all values represented by enum constants without
13424   // an initialier.
13425   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13426     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13427 
13428     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13429     // this constant.  Skip this enum since it may be ill-formed.
13430     if (!ECD) {
13431       return;
13432     }
13433 
13434     if (ECD->getInitExpr())
13435       continue;
13436 
13437     DupKey Key = GetDupKey(ECD->getInitVal());
13438     DeclOrVector &Entry = EnumMap[Key];
13439 
13440     // First time encountering this value.
13441     if (Entry.isNull())
13442       Entry = ECD;
13443   }
13444 
13445   // Create vectors for any values that has duplicates.
13446   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13447     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13448     if (!ValidDuplicateEnum(ECD, Enum))
13449       continue;
13450 
13451     DupKey Key = GetDupKey(ECD->getInitVal());
13452 
13453     DeclOrVector& Entry = EnumMap[Key];
13454     if (Entry.isNull())
13455       continue;
13456 
13457     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13458       // Ensure constants are different.
13459       if (D == ECD)
13460         continue;
13461 
13462       // Create new vector and push values onto it.
13463       ECDVector *Vec = new ECDVector();
13464       Vec->push_back(D);
13465       Vec->push_back(ECD);
13466 
13467       // Update entry to point to the duplicates vector.
13468       Entry = Vec;
13469 
13470       // Store the vector somewhere we can consult later for quick emission of
13471       // diagnostics.
13472       DupVector.push_back(Vec);
13473       continue;
13474     }
13475 
13476     ECDVector *Vec = Entry.get<ECDVector*>();
13477     // Make sure constants are not added more than once.
13478     if (*Vec->begin() == ECD)
13479       continue;
13480 
13481     Vec->push_back(ECD);
13482   }
13483 
13484   // Emit diagnostics.
13485   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13486                                   DupVectorEnd = DupVector.end();
13487        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13488     ECDVector *Vec = *DupVectorIter;
13489     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13490 
13491     // Emit warning for one enum constant.
13492     ECDVector::iterator I = Vec->begin();
13493     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13494       << (*I)->getName() << (*I)->getInitVal().toString(10)
13495       << (*I)->getSourceRange();
13496     ++I;
13497 
13498     // Emit one note for each of the remaining enum constants with
13499     // the same value.
13500     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13501       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13502         << (*I)->getName() << (*I)->getInitVal().toString(10)
13503         << (*I)->getSourceRange();
13504     delete Vec;
13505   }
13506 }
13507 
13508 bool
13509 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13510                         bool AllowMask) const {
13511   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13512   assert(FEAttr && "looking for value in non-flag enum");
13513 
13514   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13515   unsigned Width = FlagMask.getBitWidth();
13516 
13517   // We will try a zero-extended value for the regular check first.
13518   llvm::APInt ExtVal = Val.zextOrSelf(Width);
13519 
13520   // A value is in a flag enum if either its bits are a subset of the enum's
13521   // flag bits (the first condition) or we are allowing masks and the same is
13522   // true of its complement (the second condition). When masks are allowed, we
13523   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13524   //
13525   // While it's true that any value could be used as a mask, the assumption is
13526   // that a mask will have all of the insignificant bits set. Anything else is
13527   // likely a logic error.
13528   if (!(FlagMask & ExtVal))
13529     return true;
13530 
13531   if (AllowMask) {
13532     // Try a one-extended value instead. This can happen if the enum is wider
13533     // than the constant used, in C with extensions to allow for wider enums.
13534     // The mask will still have the correct behaviour, so we give the user the
13535     // benefit of the doubt.
13536     //
13537     // FIXME: This heuristic can cause weird results if the enum was extended
13538     // to a larger type and is signed, because then bit-masks of smaller types
13539     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13540     // detect that case and will get a false positive for it. In most cases,
13541     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13542     // be fine just to accept this as a warning.
13543     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13544     if (!(FlagMask & ~ExtVal))
13545       return true;
13546   }
13547 
13548   return false;
13549 }
13550 
13551 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13552                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13553                          ArrayRef<Decl *> Elements,
13554                          Scope *S, AttributeList *Attr) {
13555   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13556   QualType EnumType = Context.getTypeDeclType(Enum);
13557 
13558   if (Attr)
13559     ProcessDeclAttributeList(S, Enum, Attr);
13560 
13561   if (Enum->isDependentType()) {
13562     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13563       EnumConstantDecl *ECD =
13564         cast_or_null<EnumConstantDecl>(Elements[i]);
13565       if (!ECD) continue;
13566 
13567       ECD->setType(EnumType);
13568     }
13569 
13570     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13571     return;
13572   }
13573 
13574   // TODO: If the result value doesn't fit in an int, it must be a long or long
13575   // long value.  ISO C does not support this, but GCC does as an extension,
13576   // emit a warning.
13577   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13578   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13579   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13580 
13581   // Verify that all the values are okay, compute the size of the values, and
13582   // reverse the list.
13583   unsigned NumNegativeBits = 0;
13584   unsigned NumPositiveBits = 0;
13585 
13586   // Keep track of whether all elements have type int.
13587   bool AllElementsInt = true;
13588 
13589   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13590     EnumConstantDecl *ECD =
13591       cast_or_null<EnumConstantDecl>(Elements[i]);
13592     if (!ECD) continue;  // Already issued a diagnostic.
13593 
13594     const llvm::APSInt &InitVal = ECD->getInitVal();
13595 
13596     // Keep track of the size of positive and negative values.
13597     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13598       NumPositiveBits = std::max(NumPositiveBits,
13599                                  (unsigned)InitVal.getActiveBits());
13600     else
13601       NumNegativeBits = std::max(NumNegativeBits,
13602                                  (unsigned)InitVal.getMinSignedBits());
13603 
13604     // Keep track of whether every enum element has type int (very commmon).
13605     if (AllElementsInt)
13606       AllElementsInt = ECD->getType() == Context.IntTy;
13607   }
13608 
13609   // Figure out the type that should be used for this enum.
13610   QualType BestType;
13611   unsigned BestWidth;
13612 
13613   // C++0x N3000 [conv.prom]p3:
13614   //   An rvalue of an unscoped enumeration type whose underlying
13615   //   type is not fixed can be converted to an rvalue of the first
13616   //   of the following types that can represent all the values of
13617   //   the enumeration: int, unsigned int, long int, unsigned long
13618   //   int, long long int, or unsigned long long int.
13619   // C99 6.4.4.3p2:
13620   //   An identifier declared as an enumeration constant has type int.
13621   // The C99 rule is modified by a gcc extension
13622   QualType BestPromotionType;
13623 
13624   bool Packed = Enum->hasAttr<PackedAttr>();
13625   // -fshort-enums is the equivalent to specifying the packed attribute on all
13626   // enum definitions.
13627   if (LangOpts.ShortEnums)
13628     Packed = true;
13629 
13630   if (Enum->isFixed()) {
13631     BestType = Enum->getIntegerType();
13632     if (BestType->isPromotableIntegerType())
13633       BestPromotionType = Context.getPromotedIntegerType(BestType);
13634     else
13635       BestPromotionType = BestType;
13636 
13637     BestWidth = Context.getIntWidth(BestType);
13638   }
13639   else if (NumNegativeBits) {
13640     // If there is a negative value, figure out the smallest integer type (of
13641     // int/long/longlong) that fits.
13642     // If it's packed, check also if it fits a char or a short.
13643     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13644       BestType = Context.SignedCharTy;
13645       BestWidth = CharWidth;
13646     } else if (Packed && NumNegativeBits <= ShortWidth &&
13647                NumPositiveBits < ShortWidth) {
13648       BestType = Context.ShortTy;
13649       BestWidth = ShortWidth;
13650     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13651       BestType = Context.IntTy;
13652       BestWidth = IntWidth;
13653     } else {
13654       BestWidth = Context.getTargetInfo().getLongWidth();
13655 
13656       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13657         BestType = Context.LongTy;
13658       } else {
13659         BestWidth = Context.getTargetInfo().getLongLongWidth();
13660 
13661         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13662           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13663         BestType = Context.LongLongTy;
13664       }
13665     }
13666     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13667   } else {
13668     // If there is no negative value, figure out the smallest type that fits
13669     // all of the enumerator values.
13670     // If it's packed, check also if it fits a char or a short.
13671     if (Packed && NumPositiveBits <= CharWidth) {
13672       BestType = Context.UnsignedCharTy;
13673       BestPromotionType = Context.IntTy;
13674       BestWidth = CharWidth;
13675     } else if (Packed && NumPositiveBits <= ShortWidth) {
13676       BestType = Context.UnsignedShortTy;
13677       BestPromotionType = Context.IntTy;
13678       BestWidth = ShortWidth;
13679     } else if (NumPositiveBits <= IntWidth) {
13680       BestType = Context.UnsignedIntTy;
13681       BestWidth = IntWidth;
13682       BestPromotionType
13683         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13684                            ? Context.UnsignedIntTy : Context.IntTy;
13685     } else if (NumPositiveBits <=
13686                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13687       BestType = Context.UnsignedLongTy;
13688       BestPromotionType
13689         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13690                            ? Context.UnsignedLongTy : Context.LongTy;
13691     } else {
13692       BestWidth = Context.getTargetInfo().getLongLongWidth();
13693       assert(NumPositiveBits <= BestWidth &&
13694              "How could an initializer get larger than ULL?");
13695       BestType = Context.UnsignedLongLongTy;
13696       BestPromotionType
13697         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13698                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13699     }
13700   }
13701 
13702   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
13703   if (FEAttr)
13704     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
13705 
13706   // Loop over all of the enumerator constants, changing their types to match
13707   // the type of the enum if needed. If we have a flag type, we also prepare the
13708   // FlagBits cache.
13709   for (auto *D : Elements) {
13710     auto *ECD = cast_or_null<EnumConstantDecl>(D);
13711     if (!ECD) continue;  // Already issued a diagnostic.
13712 
13713     // Standard C says the enumerators have int type, but we allow, as an
13714     // extension, the enumerators to be larger than int size.  If each
13715     // enumerator value fits in an int, type it as an int, otherwise type it the
13716     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13717     // that X has type 'int', not 'unsigned'.
13718 
13719     // Determine whether the value fits into an int.
13720     llvm::APSInt InitVal = ECD->getInitVal();
13721 
13722     // If it fits into an integer type, force it.  Otherwise force it to match
13723     // the enum decl type.
13724     QualType NewTy;
13725     unsigned NewWidth;
13726     bool NewSign;
13727     if (!getLangOpts().CPlusPlus &&
13728         !Enum->isFixed() &&
13729         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13730       NewTy = Context.IntTy;
13731       NewWidth = IntWidth;
13732       NewSign = true;
13733     } else if (ECD->getType() == BestType) {
13734       // Already the right type!
13735       if (getLangOpts().CPlusPlus)
13736         // C++ [dcl.enum]p4: Following the closing brace of an
13737         // enum-specifier, each enumerator has the type of its
13738         // enumeration.
13739         ECD->setType(EnumType);
13740       goto flagbits;
13741     } else {
13742       NewTy = BestType;
13743       NewWidth = BestWidth;
13744       NewSign = BestType->isSignedIntegerOrEnumerationType();
13745     }
13746 
13747     // Adjust the APSInt value.
13748     InitVal = InitVal.extOrTrunc(NewWidth);
13749     InitVal.setIsSigned(NewSign);
13750     ECD->setInitVal(InitVal);
13751 
13752     // Adjust the Expr initializer and type.
13753     if (ECD->getInitExpr() &&
13754         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13755       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13756                                                 CK_IntegralCast,
13757                                                 ECD->getInitExpr(),
13758                                                 /*base paths*/ nullptr,
13759                                                 VK_RValue));
13760     if (getLangOpts().CPlusPlus)
13761       // C++ [dcl.enum]p4: Following the closing brace of an
13762       // enum-specifier, each enumerator has the type of its
13763       // enumeration.
13764       ECD->setType(EnumType);
13765     else
13766       ECD->setType(NewTy);
13767 
13768 flagbits:
13769     // Check to see if we have a constant with exactly one bit set. Note that x
13770     // & (x - 1) will be nonzero if and only if x has more than one bit set.
13771     if (FEAttr) {
13772       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
13773       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
13774         FEAttr->getFlagBits() |= ExtVal;
13775       }
13776     }
13777   }
13778 
13779   if (FEAttr) {
13780     for (Decl *D : Elements) {
13781       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
13782       if (!ECD) continue;  // Already issued a diagnostic.
13783 
13784       llvm::APSInt InitVal = ECD->getInitVal();
13785       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
13786         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
13787           << ECD << Enum;
13788     }
13789   }
13790 
13791 
13792 
13793   Enum->completeDefinition(BestType, BestPromotionType,
13794                            NumPositiveBits, NumNegativeBits);
13795 
13796   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13797 
13798   // Now that the enum type is defined, ensure it's not been underaligned.
13799   if (Enum->hasAttrs())
13800     CheckAlignasUnderalignment(Enum);
13801 }
13802 
13803 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13804                                   SourceLocation StartLoc,
13805                                   SourceLocation EndLoc) {
13806   StringLiteral *AsmString = cast<StringLiteral>(expr);
13807 
13808   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13809                                                    AsmString, StartLoc,
13810                                                    EndLoc);
13811   CurContext->addDecl(New);
13812   return New;
13813 }
13814 
13815 static void checkModuleImportContext(Sema &S, Module *M,
13816                                      SourceLocation ImportLoc,
13817                                      DeclContext *DC) {
13818   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13819     switch (LSD->getLanguage()) {
13820     case LinkageSpecDecl::lang_c:
13821       if (!M->IsExternC) {
13822         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13823           << M->getFullModuleName();
13824         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13825         return;
13826       }
13827       break;
13828     case LinkageSpecDecl::lang_cxx:
13829       break;
13830     }
13831     DC = LSD->getParent();
13832   }
13833 
13834   while (isa<LinkageSpecDecl>(DC))
13835     DC = DC->getParent();
13836   if (!isa<TranslationUnitDecl>(DC)) {
13837     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13838       << M->getFullModuleName() << DC;
13839     S.Diag(cast<Decl>(DC)->getLocStart(),
13840            diag::note_module_import_not_at_top_level)
13841       << DC;
13842   }
13843 }
13844 
13845 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13846                                    SourceLocation ImportLoc,
13847                                    ModuleIdPath Path) {
13848   Module *Mod =
13849       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13850                                    /*IsIncludeDirective=*/false);
13851   if (!Mod)
13852     return true;
13853 
13854   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13855 
13856   // FIXME: we should support importing a submodule within a different submodule
13857   // of the same top-level module. Until we do, make it an error rather than
13858   // silently ignoring the import.
13859   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13860     Diag(ImportLoc, diag::err_module_self_import)
13861         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13862   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13863     Diag(ImportLoc, diag::err_module_import_in_implementation)
13864         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13865 
13866   SmallVector<SourceLocation, 2> IdentifierLocs;
13867   Module *ModCheck = Mod;
13868   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13869     // If we've run out of module parents, just drop the remaining identifiers.
13870     // We need the length to be consistent.
13871     if (!ModCheck)
13872       break;
13873     ModCheck = ModCheck->Parent;
13874 
13875     IdentifierLocs.push_back(Path[I].second);
13876   }
13877 
13878   ImportDecl *Import = ImportDecl::Create(Context,
13879                                           Context.getTranslationUnitDecl(),
13880                                           AtLoc.isValid()? AtLoc : ImportLoc,
13881                                           Mod, IdentifierLocs);
13882   Context.getTranslationUnitDecl()->addDecl(Import);
13883   return Import;
13884 }
13885 
13886 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13887   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13888 
13889   // FIXME: Should we synthesize an ImportDecl here?
13890   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13891                                       /*Complain=*/true);
13892 }
13893 
13894 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13895                                                       Module *Mod) {
13896   // Bail if we're not allowed to implicitly import a module here.
13897   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13898     return;
13899 
13900   // Create the implicit import declaration.
13901   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13902   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13903                                                    Loc, Mod, Loc);
13904   TU->addDecl(ImportD);
13905   Consumer.HandleImplicitImportDecl(ImportD);
13906 
13907   // Make the module visible.
13908   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13909                                       /*Complain=*/false);
13910 }
13911 
13912 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13913                                       IdentifierInfo* AliasName,
13914                                       SourceLocation PragmaLoc,
13915                                       SourceLocation NameLoc,
13916                                       SourceLocation AliasNameLoc) {
13917   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13918                                     LookupOrdinaryName);
13919   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13920                                                     AliasName->getName(), 0);
13921 
13922   if (PrevDecl)
13923     PrevDecl->addAttr(Attr);
13924   else
13925     (void)ExtnameUndeclaredIdentifiers.insert(
13926       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13927 }
13928 
13929 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13930                              SourceLocation PragmaLoc,
13931                              SourceLocation NameLoc) {
13932   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13933 
13934   if (PrevDecl) {
13935     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13936   } else {
13937     (void)WeakUndeclaredIdentifiers.insert(
13938       std::pair<IdentifierInfo*,WeakInfo>
13939         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
13940   }
13941 }
13942 
13943 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13944                                 IdentifierInfo* AliasName,
13945                                 SourceLocation PragmaLoc,
13946                                 SourceLocation NameLoc,
13947                                 SourceLocation AliasNameLoc) {
13948   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13949                                     LookupOrdinaryName);
13950   WeakInfo W = WeakInfo(Name, NameLoc);
13951 
13952   if (PrevDecl) {
13953     if (!PrevDecl->hasAttr<AliasAttr>())
13954       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13955         DeclApplyPragmaWeak(TUScope, ND, W);
13956   } else {
13957     (void)WeakUndeclaredIdentifiers.insert(
13958       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13959   }
13960 }
13961 
13962 Decl *Sema::getObjCDeclContext() const {
13963   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13964 }
13965 
13966 AvailabilityResult Sema::getCurContextAvailability() const {
13967   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13968   // If we are within an Objective-C method, we should consult
13969   // both the availability of the method as well as the
13970   // enclosing class.  If the class is (say) deprecated,
13971   // the entire method is considered deprecated from the
13972   // purpose of checking if the current context is deprecated.
13973   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13974     AvailabilityResult R = MD->getAvailability();
13975     if (R != AR_Available)
13976       return R;
13977     D = MD->getClassInterface();
13978   }
13979   // If we are within an Objective-c @implementation, it
13980   // gets the same availability context as the @interface.
13981   else if (const ObjCImplementationDecl *ID =
13982             dyn_cast<ObjCImplementationDecl>(D)) {
13983     D = ID->getClassInterface();
13984   }
13985   // Recover from user error.
13986   return D ? D->getAvailability() : AR_Available;
13987 }
13988