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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              IdentifierInfo **CorrectedII) {
256   // Determine where we will perform name lookup.
257   DeclContext *LookupCtx = nullptr;
258   if (ObjectTypePtr) {
259     QualType ObjectType = ObjectTypePtr.get();
260     if (ObjectType->isRecordType())
261       LookupCtx = computeDeclContext(ObjectType);
262   } else if (SS && SS->isNotEmpty()) {
263     LookupCtx = computeDeclContext(*SS, false);
264 
265     if (!LookupCtx) {
266       if (isDependentScopeSpecifier(*SS)) {
267         // C++ [temp.res]p3:
268         //   A qualified-id that refers to a type and in which the
269         //   nested-name-specifier depends on a template-parameter (14.6.2)
270         //   shall be prefixed by the keyword typename to indicate that the
271         //   qualified-id denotes a type, forming an
272         //   elaborated-type-specifier (7.1.5.3).
273         //
274         // We therefore do not perform any name lookup if the result would
275         // refer to a member of an unknown specialization.
276         if (!isClassName && !IsCtorOrDtorName)
277           return nullptr;
278 
279         // We know from the grammar that this name refers to a type,
280         // so build a dependent node to describe the type.
281         if (WantNontrivialTypeSourceInfo)
282           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283 
284         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286                                        II, NameLoc);
287         return ParsedType::make(T);
288       }
289 
290       return nullptr;
291     }
292 
293     if (!LookupCtx->isDependentContext() &&
294         RequireCompleteDeclContext(*SS, LookupCtx))
295       return nullptr;
296   }
297 
298   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299   // lookup for class-names.
300   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301                                       LookupOrdinaryName;
302   LookupResult Result(*this, &II, NameLoc, Kind);
303   if (LookupCtx) {
304     // Perform "qualified" name lookup into the declaration context we
305     // computed, which is either the type of the base of a member access
306     // expression or the declaration context associated with a prior
307     // nested-name-specifier.
308     LookupQualifiedName(Result, LookupCtx);
309 
310     if (ObjectTypePtr && Result.empty()) {
311       // C++ [basic.lookup.classref]p3:
312       //   If the unqualified-id is ~type-name, the type-name is looked up
313       //   in the context of the entire postfix-expression. If the type T of
314       //   the object expression is of a class type C, the type-name is also
315       //   looked up in the scope of class C. At least one of the lookups shall
316       //   find a name that refers to (possibly cv-qualified) T.
317       LookupName(Result, S);
318     }
319   } else {
320     // Perform unqualified name lookup.
321     LookupName(Result, S);
322 
323     // For unqualified lookup in a class template in MSVC mode, look into
324     // dependent base classes where the primary class template is known.
325     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326       if (ParsedType TypeInBase =
327               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328         return TypeInBase;
329     }
330   }
331 
332   NamedDecl *IIDecl = nullptr;
333   switch (Result.getResultKind()) {
334   case LookupResult::NotFound:
335   case LookupResult::NotFoundInCurrentInstantiation:
336     if (CorrectedII) {
337       TypoCorrection Correction = CorrectTypo(
338           Result.getLookupNameInfo(), Kind, S, SS,
339           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340           CTK_ErrorRecovery);
341       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342       TemplateTy Template;
343       bool MemberOfUnknownSpecialization;
344       UnqualifiedId TemplateName;
345       TemplateName.setIdentifier(NewII, NameLoc);
346       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347       CXXScopeSpec NewSS, *NewSSPtr = SS;
348       if (SS && NNS) {
349         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350         NewSSPtr = &NewSS;
351       }
352       if (Correction && (NNS || NewII != &II) &&
353           // Ignore a correction to a template type as the to-be-corrected
354           // identifier is not a template (typo correction for template names
355           // is handled elsewhere).
356           !(getLangOpts().CPlusPlus && NewSSPtr &&
357             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358                            Template, MemberOfUnknownSpecialization))) {
359         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360                                     isClassName, HasTrailingDot, ObjectTypePtr,
361                                     IsCtorOrDtorName,
362                                     WantNontrivialTypeSourceInfo);
363         if (Ty) {
364           diagnoseTypo(Correction,
365                        PDiag(diag::err_unknown_type_or_class_name_suggest)
366                          << Result.getLookupName() << isClassName);
367           if (SS && NNS)
368             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369           *CorrectedII = NewII;
370           return Ty;
371         }
372       }
373     }
374     // If typo correction failed or was not performed, fall through
375   case LookupResult::FoundOverloaded:
376   case LookupResult::FoundUnresolvedValue:
377     Result.suppressDiagnostics();
378     return nullptr;
379 
380   case LookupResult::Ambiguous:
381     // Recover from type-hiding ambiguities by hiding the type.  We'll
382     // do the lookup again when looking for an object, and we can
383     // diagnose the error then.  If we don't do this, then the error
384     // about hiding the type will be immediately followed by an error
385     // that only makes sense if the identifier was treated like a type.
386     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387       Result.suppressDiagnostics();
388       return nullptr;
389     }
390 
391     // Look to see if we have a type anywhere in the list of results.
392     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393          Res != ResEnd; ++Res) {
394       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395         if (!IIDecl ||
396             (*Res)->getLocation().getRawEncoding() <
397               IIDecl->getLocation().getRawEncoding())
398           IIDecl = *Res;
399       }
400     }
401 
402     if (!IIDecl) {
403       // None of the entities we found is a type, so there is no way
404       // to even assume that the result is a type. In this case, don't
405       // complain about the ambiguity. The parser will either try to
406       // perform this lookup again (e.g., as an object name), which
407       // will produce the ambiguity, or will complain that it expected
408       // a type name.
409       Result.suppressDiagnostics();
410       return nullptr;
411     }
412 
413     // We found a type within the ambiguous lookup; diagnose the
414     // ambiguity and then return that type. This might be the right
415     // answer, or it might not be, but it suppresses any attempt to
416     // perform the name lookup again.
417     break;
418 
419   case LookupResult::Found:
420     IIDecl = Result.getFoundDecl();
421     break;
422   }
423 
424   assert(IIDecl && "Didn't find decl");
425 
426   QualType T;
427   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428     DiagnoseUseOfDecl(IIDecl, NameLoc);
429 
430     T = Context.getTypeDeclType(TD);
431     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432 
433     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434     // constructor or destructor name (in such a case, the scope specifier
435     // will be attached to the enclosing Expr or Decl node).
436     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437       if (WantNontrivialTypeSourceInfo) {
438         // Construct a type with type-source information.
439         TypeLocBuilder Builder;
440         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441 
442         T = getElaboratedType(ETK_None, *SS, T);
443         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444         ElabTL.setElaboratedKeywordLoc(SourceLocation());
445         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447       } else {
448         T = getElaboratedType(ETK_None, *SS, T);
449       }
450     }
451   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453     if (!HasTrailingDot)
454       T = Context.getObjCInterfaceType(IDecl);
455   }
456 
457   if (T.isNull()) {
458     // If it's not plausibly a type, suppress diagnostics.
459     Result.suppressDiagnostics();
460     return nullptr;
461   }
462   return ParsedType::make(T);
463 }
464 
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468   for (;; DC = DC->getLookupParent()) {
469     DC = DC->getPrimaryContext();
470     auto *ND = dyn_cast<NamespaceDecl>(DC);
471     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472       return NestedNameSpecifier::Create(Context, nullptr, ND);
473     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475                                          RD->getTypeForDecl());
476     else if (isa<TranslationUnitDecl>(DC))
477       return NestedNameSpecifier::GlobalSpecifier(Context);
478   }
479   llvm_unreachable("something isn't in TU scope?");
480 }
481 
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489     DC = DC->getPrimaryContext();
490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491       if (MD->getParent()->hasAnyDependentBases())
492         return MD->getParent();
493   }
494   return nullptr;
495 }
496 
497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498                                           SourceLocation NameLoc,
499                                           bool IsTemplateTypeArg) {
500   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501 
502   NestedNameSpecifier *NNS = nullptr;
503   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504     // If we weren't able to parse a default template argument, delay lookup
505     // until instantiation time by making a non-dependent DependentTypeName. We
506     // pretend we saw a NestedNameSpecifier referring to the current scope, and
507     // lookup is retried.
508     // FIXME: This hurts our diagnostic quality, since we get errors like "no
509     // type named 'Foo' in 'current_namespace'" when the user didn't write any
510     // name specifiers.
511     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513   } else if (const CXXRecordDecl *RD =
514                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515     // Build a DependentNameType that will perform lookup into RD at
516     // instantiation time.
517     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518                                       RD->getTypeForDecl());
519 
520     // Diagnose that this identifier was undeclared, and retry the lookup during
521     // template instantiation.
522     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523                                                                       << RD;
524   } else {
525     // This is not a situation that we should recover from.
526     return ParsedType();
527   }
528 
529   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530 
531   // Build type location information.  We synthesized the qualifier, so we have
532   // to build a fake NestedNameSpecifierLoc.
533   NestedNameSpecifierLocBuilder NNSLocBuilder;
534   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536 
537   TypeLocBuilder Builder;
538   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539   DepTL.setNameLoc(NameLoc);
540   DepTL.setElaboratedKeywordLoc(SourceLocation());
541   DepTL.setQualifierLoc(QualifierLoc);
542   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543 }
544 
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo").  If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551   // Do a tag name lookup in this scope.
552   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553   LookupName(R, S, false);
554   R.suppressDiagnostics();
555   if (R.getResultKind() == LookupResult::Found)
556     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557       switch (TD->getTagKind()) {
558       case TTK_Struct: return DeclSpec::TST_struct;
559       case TTK_Interface: return DeclSpec::TST_interface;
560       case TTK_Union:  return DeclSpec::TST_union;
561       case TTK_Class:  return DeclSpec::TST_class;
562       case TTK_Enum:   return DeclSpec::TST_enum;
563       }
564     }
565 
566   return DeclSpec::TST_unspecified;
567 }
568 
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
573 /// @code
574 /// template<class T> class A {
575 /// public:
576 ///   typedef int TYPE;
577 /// };
578 /// template<class T> class B : public A<T> {
579 /// public:
580 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
581 /// };
582 /// @endcode
583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584   if (CurContext->isRecord()) {
585     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586       return true;
587 
588     const Type *Ty = SS->getScopeRep()->getAsType();
589 
590     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591     for (const auto &Base : RD->bases())
592       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593         return true;
594     return S->isFunctionPrototypeScope();
595   }
596   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597 }
598 
599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600                                    SourceLocation IILoc,
601                                    Scope *S,
602                                    CXXScopeSpec *SS,
603                                    ParsedType &SuggestedType,
604                                    bool AllowClassTemplates) {
605   // We don't have anything to suggest (yet).
606   SuggestedType = nullptr;
607 
608   // There may have been a typo in the name of the type. Look up typo
609   // results, in case we have something that we can suggest.
610   if (TypoCorrection Corrected =
611           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612                       llvm::make_unique<TypeNameValidatorCCC>(
613                           false, false, AllowClassTemplates),
614                       CTK_ErrorRecovery)) {
615     if (Corrected.isKeyword()) {
616       // We corrected to a keyword.
617       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618       II = Corrected.getCorrectionAsIdentifierInfo();
619     } else {
620       // We found a similarly-named type or interface; suggest that.
621       if (!SS || !SS->isSet()) {
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_typename_suggest) << II);
624       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627                                 II->getName().equals(CorrectedStr);
628         diagnoseTypo(Corrected,
629                      PDiag(diag::err_unknown_nested_typename_suggest)
630                        << II << DC << DroppedSpecifier << SS->getRange());
631       } else {
632         llvm_unreachable("could not have corrected a typo here");
633       }
634 
635       CXXScopeSpec tmpSS;
636       if (Corrected.getCorrectionSpecifier())
637         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638                           SourceRange(IILoc));
639       SuggestedType =
640           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642                       /*IsCtorOrDtorName=*/false,
643                       /*NonTrivialTypeSourceInfo=*/true);
644     }
645     return;
646   }
647 
648   if (getLangOpts().CPlusPlus) {
649     // See if II is a class template that the user forgot to pass arguments to.
650     UnqualifiedId Name;
651     Name.setIdentifier(II, IILoc);
652     CXXScopeSpec EmptySS;
653     TemplateTy TemplateResult;
654     bool MemberOfUnknownSpecialization;
655     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656                        Name, nullptr, true, TemplateResult,
657                        MemberOfUnknownSpecialization) == TNK_Type_template) {
658       TemplateName TplName = TemplateResult.get();
659       Diag(IILoc, diag::err_template_missing_args) << TplName;
660       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662           << TplDecl->getTemplateParameters()->getSourceRange();
663       }
664       return;
665     }
666   }
667 
668   // FIXME: Should we move the logic that tries to recover from a missing tag
669   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670 
671   if (!SS || (!SS->isSet() && !SS->isInvalid()))
672     Diag(IILoc, diag::err_unknown_typename) << II;
673   else if (DeclContext *DC = computeDeclContext(*SS, false))
674     Diag(IILoc, diag::err_typename_nested_not_found)
675       << II << DC << SS->getRange();
676   else if (isDependentScopeSpecifier(*SS)) {
677     unsigned DiagID = diag::err_typename_missing;
678     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679       DiagID = diag::ext_typename_missing;
680 
681     Diag(SS->getRange().getBegin(), DiagID)
682       << SS->getScopeRep() << II->getName()
683       << SourceRange(SS->getRange().getBegin(), IILoc)
684       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685     SuggestedType = ActOnTypenameType(S, SourceLocation(),
686                                       *SS, *II, IILoc).get();
687   } else {
688     assert(SS && SS->isInvalid() &&
689            "Invalid scope specifier has already been diagnosed");
690   }
691 }
692 
693 /// \brief Determine whether the given result set contains either a type name
694 /// or
695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697                        NextToken.is(tok::less);
698 
699   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701       return true;
702 
703     if (CheckTemplate && isa<TemplateDecl>(*I))
704       return true;
705   }
706 
707   return false;
708 }
709 
710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711                                     Scope *S, CXXScopeSpec &SS,
712                                     IdentifierInfo *&Name,
713                                     SourceLocation NameLoc) {
714   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715   SemaRef.LookupParsedName(R, S, &SS);
716   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717     StringRef FixItTagName;
718     switch (Tag->getTagKind()) {
719       case TTK_Class:
720         FixItTagName = "class ";
721         break;
722 
723       case TTK_Enum:
724         FixItTagName = "enum ";
725         break;
726 
727       case TTK_Struct:
728         FixItTagName = "struct ";
729         break;
730 
731       case TTK_Interface:
732         FixItTagName = "__interface ";
733         break;
734 
735       case TTK_Union:
736         FixItTagName = "union ";
737         break;
738     }
739 
740     StringRef TagName = FixItTagName.drop_back();
741     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744 
745     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746          I != IEnd; ++I)
747       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748         << Name << TagName;
749 
750     // Replace lookup results with just the tag decl.
751     Result.clear(Sema::LookupTagName);
752     SemaRef.LookupParsedName(Result, S, &SS);
753     return true;
754   }
755 
756   return false;
757 }
758 
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761                                   QualType T, SourceLocation NameLoc) {
762   ASTContext &Context = S.Context;
763 
764   TypeLocBuilder Builder;
765   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766 
767   T = S.getElaboratedType(ETK_None, SS, T);
768   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769   ElabTL.setElaboratedKeywordLoc(SourceLocation());
770   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772 }
773 
774 Sema::NameClassification
775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776                    SourceLocation NameLoc, const Token &NextToken,
777                    bool IsAddressOfOperand,
778                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
779   DeclarationNameInfo NameInfo(Name, NameLoc);
780   ObjCMethodDecl *CurMethod = getCurMethodDecl();
781 
782   if (NextToken.is(tok::coloncolon)) {
783     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
784     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
785   }
786 
787   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788   LookupParsedName(Result, S, &SS, !CurMethod);
789 
790   // For unqualified lookup in a class template in MSVC mode, look into
791   // dependent base classes where the primary class template is known.
792   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793     if (ParsedType TypeInBase =
794             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795       return TypeInBase;
796   }
797 
798   // Perform lookup for Objective-C instance variables (including automatically
799   // synthesized instance variables), if we're in an Objective-C method.
800   // FIXME: This lookup really, really needs to be folded in to the normal
801   // unqualified lookup mechanism.
802   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804     if (E.get() || E.isInvalid())
805       return E;
806   }
807 
808   bool SecondTry = false;
809   bool IsFilteredTemplateName = false;
810 
811 Corrected:
812   switch (Result.getResultKind()) {
813   case LookupResult::NotFound:
814     // If an unqualified-id is followed by a '(', then we have a function
815     // call.
816     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817       // In C++, this is an ADL-only call.
818       // FIXME: Reference?
819       if (getLangOpts().CPlusPlus)
820         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821 
822       // C90 6.3.2.2:
823       //   If the expression that precedes the parenthesized argument list in a
824       //   function call consists solely of an identifier, and if no
825       //   declaration is visible for this identifier, the identifier is
826       //   implicitly declared exactly as if, in the innermost block containing
827       //   the function call, the declaration
828       //
829       //     extern int identifier ();
830       //
831       //   appeared.
832       //
833       // We also allow this in C99 as an extension.
834       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835         Result.addDecl(D);
836         Result.resolveKind();
837         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838       }
839     }
840 
841     // In C, we first see whether there is a tag type by the same name, in
842     // which case it's likely that the user just forgot to write "enum",
843     // "struct", or "union".
844     if (!getLangOpts().CPlusPlus && !SecondTry &&
845         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846       break;
847     }
848 
849     // Perform typo correction to determine if there is another name that is
850     // close to this name.
851     if (!SecondTry && CCC) {
852       SecondTry = true;
853       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854                                                  Result.getLookupKind(), S,
855                                                  &SS, std::move(CCC),
856                                                  CTK_ErrorRecovery)) {
857         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858         unsigned QualifiedDiag = diag::err_no_member_suggest;
859 
860         NamedDecl *FirstDecl = Corrected.getFoundDecl();
861         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864           UnqualifiedDiag = diag::err_no_template_suggest;
865           QualifiedDiag = diag::err_no_member_template_suggest;
866         } else if (UnderlyingFirstDecl &&
867                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
868                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870           UnqualifiedDiag = diag::err_unknown_typename_suggest;
871           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872         }
873 
874         if (SS.isEmpty()) {
875           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876         } else {// FIXME: is this even reachable? Test it.
877           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879                                   Name->getName().equals(CorrectedStr);
880           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881                                     << Name << computeDeclContext(SS, false)
882                                     << DroppedSpecifier << SS.getRange());
883         }
884 
885         // Update the name, so that the caller has the new name.
886         Name = Corrected.getCorrectionAsIdentifierInfo();
887 
888         // Typo correction corrected to a keyword.
889         if (Corrected.isKeyword())
890           return Name;
891 
892         // Also update the LookupResult...
893         // FIXME: This should probably go away at some point
894         Result.clear();
895         Result.setLookupName(Corrected.getCorrection());
896         if (FirstDecl)
897           Result.addDecl(FirstDecl);
898 
899         // If we found an Objective-C instance variable, let
900         // LookupInObjCMethod build the appropriate expression to
901         // reference the ivar.
902         // FIXME: This is a gross hack.
903         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904           Result.clear();
905           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906           return E;
907         }
908 
909         goto Corrected;
910       }
911     }
912 
913     // We failed to correct; just fall through and let the parser deal with it.
914     Result.suppressDiagnostics();
915     return NameClassification::Unknown();
916 
917   case LookupResult::NotFoundInCurrentInstantiation: {
918     // We performed name lookup into the current instantiation, and there were
919     // dependent bases, so we treat this result the same way as any other
920     // dependent nested-name-specifier.
921 
922     // C++ [temp.res]p2:
923     //   A name used in a template declaration or definition and that is
924     //   dependent on a template-parameter is assumed not to name a type
925     //   unless the applicable name lookup finds a type name or the name is
926     //   qualified by the keyword typename.
927     //
928     // FIXME: If the next token is '<', we might want to ask the parser to
929     // perform some heroics to see if we actually have a
930     // template-argument-list, which would indicate a missing 'template'
931     // keyword here.
932     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933                                       NameInfo, IsAddressOfOperand,
934                                       /*TemplateArgs=*/nullptr);
935   }
936 
937   case LookupResult::Found:
938   case LookupResult::FoundOverloaded:
939   case LookupResult::FoundUnresolvedValue:
940     break;
941 
942   case LookupResult::Ambiguous:
943     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944         hasAnyAcceptableTemplateNames(Result)) {
945       // C++ [temp.local]p3:
946       //   A lookup that finds an injected-class-name (10.2) can result in an
947       //   ambiguity in certain cases (for example, if it is found in more than
948       //   one base class). If all of the injected-class-names that are found
949       //   refer to specializations of the same class template, and if the name
950       //   is followed by a template-argument-list, the reference refers to the
951       //   class template itself and not a specialization thereof, and is not
952       //   ambiguous.
953       //
954       // This filtering can make an ambiguous result into an unambiguous one,
955       // so try again after filtering out template names.
956       FilterAcceptableTemplateNames(Result);
957       if (!Result.isAmbiguous()) {
958         IsFilteredTemplateName = true;
959         break;
960       }
961     }
962 
963     // Diagnose the ambiguity and return an error.
964     return NameClassification::Error();
965   }
966 
967   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969     // C++ [temp.names]p3:
970     //   After name lookup (3.4) finds that a name is a template-name or that
971     //   an operator-function-id or a literal- operator-id refers to a set of
972     //   overloaded functions any member of which is a function template if
973     //   this is followed by a <, the < is always taken as the delimiter of a
974     //   template-argument-list and never as the less-than operator.
975     if (!IsFilteredTemplateName)
976       FilterAcceptableTemplateNames(Result);
977 
978     if (!Result.empty()) {
979       bool IsFunctionTemplate;
980       bool IsVarTemplate;
981       TemplateName Template;
982       if (Result.end() - Result.begin() > 1) {
983         IsFunctionTemplate = true;
984         Template = Context.getOverloadedTemplateName(Result.begin(),
985                                                      Result.end());
986       } else {
987         TemplateDecl *TD
988           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990         IsVarTemplate = isa<VarTemplateDecl>(TD);
991 
992         if (SS.isSet() && !SS.isInvalid())
993           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994                                                     /*TemplateKeyword=*/false,
995                                                       TD);
996         else
997           Template = TemplateName(TD);
998       }
999 
1000       if (IsFunctionTemplate) {
1001         // Function templates always go through overload resolution, at which
1002         // point we'll perform the various checks (e.g., accessibility) we need
1003         // to based on which function we selected.
1004         Result.suppressDiagnostics();
1005 
1006         return NameClassification::FunctionTemplate(Template);
1007       }
1008 
1009       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010                            : NameClassification::TypeTemplate(Template);
1011     }
1012   }
1013 
1014   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023 
1024   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025   if (!Class) {
1026     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027     if (ObjCCompatibleAliasDecl *Alias =
1028             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029       Class = Alias->getClassInterface();
1030   }
1031 
1032   if (Class) {
1033     DiagnoseUseOfDecl(Class, NameLoc);
1034 
1035     if (NextToken.is(tok::period)) {
1036       // Interface. <something> is parsed as a property reference expression.
1037       // Just return "unknown" as a fall-through for now.
1038       Result.suppressDiagnostics();
1039       return NameClassification::Unknown();
1040     }
1041 
1042     QualType T = Context.getObjCInterfaceType(Class);
1043     return ParsedType::make(T);
1044   }
1045 
1046   // We can have a type template here if we're classifying a template argument.
1047   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048     return NameClassification::TypeTemplate(
1049         TemplateName(cast<TemplateDecl>(FirstDecl)));
1050 
1051   // Check for a tag type hidden by a non-type decl in a few cases where it
1052   // seems likely a type is wanted instead of the non-type that was found.
1053   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054   if ((NextToken.is(tok::identifier) ||
1055        (NextIsOp &&
1056         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059     DiagnoseUseOfDecl(Type, NameLoc);
1060     QualType T = Context.getTypeDeclType(Type);
1061     if (SS.isNotEmpty())
1062       return buildNestedType(*this, SS, T, NameLoc);
1063     return ParsedType::make(T);
1064   }
1065 
1066   if (FirstDecl->isCXXClassMember())
1067     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068                                            nullptr, S);
1069 
1070   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071   return BuildDeclarationNameExpr(SS, Result, ADL);
1072 }
1073 
1074 // Determines the context to return to after temporarily entering a
1075 // context.  This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078 
1079   // Functions defined inline within classes aren't parsed until we've
1080   // finished parsing the top-level class, so the top-level class is
1081   // the context we'll need to return to.
1082   // A Lambda call operator whose parent is a class must not be treated
1083   // as an inline member function.  A Lambda can be used legally
1084   // either as an in-class member initializer or a default argument.  These
1085   // are parsed once the class has been marked complete and so the containing
1086   // context would be the nested class (when the lambda is defined in one);
1087   // If the class is not complete, then the lambda is being used in an
1088   // ill-formed fashion (such as to specify the width of a bit-field, or
1089   // in an array-bound) - in which case we still want to return the
1090   // lexically containing DC (which could be a nested class).
1091   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092     DC = DC->getLexicalParent();
1093 
1094     // A function not defined within a class will always return to its
1095     // lexical context.
1096     if (!isa<CXXRecordDecl>(DC))
1097       return DC;
1098 
1099     // A C++ inline method/friend is parsed *after* the topmost class
1100     // it was declared in is fully parsed ("complete");  the topmost
1101     // class is the context we need to return to.
1102     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103       DC = RD;
1104 
1105     // Return the declaration context of the topmost class the inline method is
1106     // declared in.
1107     return DC;
1108   }
1109 
1110   return DC->getLexicalParent();
1111 }
1112 
1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114   assert(getContainingDC(DC) == CurContext &&
1115       "The next DeclContext should be lexically contained in the current one.");
1116   CurContext = DC;
1117   S->setEntity(DC);
1118 }
1119 
1120 void Sema::PopDeclContext() {
1121   assert(CurContext && "DeclContext imbalance!");
1122 
1123   CurContext = getContainingDC(CurContext);
1124   assert(CurContext && "Popped translation unit!");
1125 }
1126 
1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128                                                                     Decl *D) {
1129   // Unlike PushDeclContext, the context to which we return is not necessarily
1130   // the containing DC of TD, because the new context will be some pre-existing
1131   // TagDecl definition instead of a fresh one.
1132   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133   CurContext = cast<TagDecl>(D)->getDefinition();
1134   assert(CurContext && "skipping definition of undefined tag");
1135   // Start lookups from the parent of the current context; we don't want to look
1136   // into the pre-existing complete definition.
1137   S->setEntity(CurContext->getLookupParent());
1138   return Result;
1139 }
1140 
1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142   CurContext = static_cast<decltype(CurContext)>(Context);
1143 }
1144 
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1147 ///
1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149   // C++0x [basic.lookup.unqual]p13:
1150   //   A name used in the definition of a static data member of class
1151   //   X (after the qualified-id of the static member) is looked up as
1152   //   if the name was used in a member function of X.
1153   // C++0x [basic.lookup.unqual]p14:
1154   //   If a variable member of a namespace is defined outside of the
1155   //   scope of its namespace then any name used in the definition of
1156   //   the variable member (after the declarator-id) is looked up as
1157   //   if the definition of the variable member occurred in its
1158   //   namespace.
1159   // Both of these imply that we should push a scope whose context
1160   // is the semantic context of the declaration.  We can't use
1161   // PushDeclContext here because that context is not necessarily
1162   // lexically contained in the current context.  Fortunately,
1163   // the containing scope should have the appropriate information.
1164 
1165   assert(!S->getEntity() && "scope already has entity");
1166 
1167 #ifndef NDEBUG
1168   Scope *Ancestor = S->getParent();
1169   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171 #endif
1172 
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176 
1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178   assert(S->getEntity() == CurContext && "Context imbalance!");
1179 
1180   // Switch back to the lexical context.  The safety of this is
1181   // enforced by an assert in EnterDeclaratorContext.
1182   Scope *Ancestor = S->getParent();
1183   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184   CurContext = Ancestor->getEntity();
1185 
1186   // We don't need to do anything with the scope, which is going to
1187   // disappear.
1188 }
1189 
1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191   // We assume that the caller has already called
1192   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193   FunctionDecl *FD = D->getAsFunction();
1194   if (!FD)
1195     return;
1196 
1197   // Same implementation as PushDeclContext, but enters the context
1198   // from the lexical parent, rather than the top-level class.
1199   assert(CurContext == FD->getLexicalParent() &&
1200     "The next DeclContext should be lexically contained in the current one.");
1201   CurContext = FD;
1202   S->setEntity(CurContext);
1203 
1204   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205     ParmVarDecl *Param = FD->getParamDecl(P);
1206     // If the parameter has an identifier, then add it to the scope
1207     if (Param->getIdentifier()) {
1208       S->AddDecl(Param);
1209       IdResolver.AddDecl(Param);
1210     }
1211   }
1212 }
1213 
1214 void Sema::ActOnExitFunctionContext() {
1215   // Same implementation as PopDeclContext, but returns to the lexical parent,
1216   // rather than the top-level class.
1217   assert(CurContext && "DeclContext imbalance!");
1218   CurContext = CurContext->getLexicalParent();
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221 
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1224 ///
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1230 /// attribute.
1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232                                        ASTContext &Context) {
1233   if (Context.getLangOpts().CPlusPlus)
1234     return true;
1235 
1236   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237     return true;
1238 
1239   return (Previous.getResultKind() == LookupResult::Found
1240           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241 }
1242 
1243 /// Add this decl to the scope shadowed decl chains.
1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245   // Move up the scope chain until we find the nearest enclosing
1246   // non-transparent context. The declaration will be introduced into this
1247   // scope.
1248   while (S->getEntity() && S->getEntity()->isTransparentContext())
1249     S = S->getParent();
1250 
1251   // Add scoped declarations into their context, so that they can be
1252   // found later. Declarations without a context won't be inserted
1253   // into any context.
1254   if (AddToContext)
1255     CurContext->addDecl(D);
1256 
1257   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258   // are function-local declarations.
1259   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260       !D->getDeclContext()->getRedeclContext()->Equals(
1261         D->getLexicalDeclContext()->getRedeclContext()) &&
1262       !D->getLexicalDeclContext()->isFunctionOrMethod())
1263     return;
1264 
1265   // Template instantiations should also not be pushed into scope.
1266   if (isa<FunctionDecl>(D) &&
1267       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268     return;
1269 
1270   // If this replaces anything in the current scope,
1271   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272                                IEnd = IdResolver.end();
1273   for (; I != IEnd; ++I) {
1274     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275       S->RemoveDecl(*I);
1276       IdResolver.RemoveDecl(*I);
1277 
1278       // Should only need to replace one decl.
1279       break;
1280     }
1281   }
1282 
1283   S->AddDecl(D);
1284 
1285   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286     // Implicitly-generated labels may end up getting generated in an order that
1287     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288     // the label at the appropriate place in the identifier chain.
1289     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291       if (IDC == CurContext) {
1292         if (!S->isDeclScope(*I))
1293           continue;
1294       } else if (IDC->Encloses(CurContext))
1295         break;
1296     }
1297 
1298     IdResolver.InsertDeclAfter(I, D);
1299   } else {
1300     IdResolver.AddDecl(D);
1301   }
1302 }
1303 
1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306     TUScope->AddDecl(D);
1307 }
1308 
1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310                          bool AllowInlineNamespace) {
1311   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312 }
1313 
1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315   DeclContext *TargetDC = DC->getPrimaryContext();
1316   do {
1317     if (DeclContext *ScopeDC = S->getEntity())
1318       if (ScopeDC->getPrimaryContext() == TargetDC)
1319         return S;
1320   } while ((S = S->getParent()));
1321 
1322   return nullptr;
1323 }
1324 
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326                                             DeclContext*,
1327                                             ASTContext&);
1328 
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332                                 bool ConsiderLinkage,
1333                                 bool AllowInlineNamespace) {
1334   LookupResult::Filter F = R.makeFilter();
1335   while (F.hasNext()) {
1336     NamedDecl *D = F.next();
1337 
1338     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339       continue;
1340 
1341     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342       continue;
1343 
1344     F.erase();
1345   }
1346 
1347   F.done();
1348 }
1349 
1350 static bool isUsingDecl(NamedDecl *D) {
1351   return isa<UsingShadowDecl>(D) ||
1352          isa<UnresolvedUsingTypenameDecl>(D) ||
1353          isa<UnresolvedUsingValueDecl>(D);
1354 }
1355 
1356 /// Removes using shadow declarations from the lookup results.
1357 static void RemoveUsingDecls(LookupResult &R) {
1358   LookupResult::Filter F = R.makeFilter();
1359   while (F.hasNext())
1360     if (isUsingDecl(F.next()))
1361       F.erase();
1362 
1363   F.done();
1364 }
1365 
1366 /// \brief Check for this common pattern:
1367 /// @code
1368 /// class S {
1369 ///   S(const S&); // DO NOT IMPLEMENT
1370 ///   void operator=(const S&); // DO NOT IMPLEMENT
1371 /// };
1372 /// @endcode
1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374   // FIXME: Should check for private access too but access is set after we get
1375   // the decl here.
1376   if (D->doesThisDeclarationHaveABody())
1377     return false;
1378 
1379   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380     return CD->isCopyConstructor();
1381   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382     return Method->isCopyAssignmentOperator();
1383   return false;
1384 }
1385 
1386 // We need this to handle
1387 //
1388 // typedef struct {
1389 //   void *foo() { return 0; }
1390 // } A;
1391 //
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1397 // not.
1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399   const DeclContext *DC = D->getDeclContext();
1400   while (!DC->isTranslationUnit()) {
1401     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402       if (!RD->hasNameForLinkage())
1403         return true;
1404     }
1405     DC = DC->getParent();
1406   }
1407 
1408   return !D->isExternallyVisible();
1409 }
1410 
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1412 // these semantics.
1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414   if (S.TUKind != TU_Complete)
1415     return false;
1416   return S.SourceMgr.isInMainFile(Loc);
1417 }
1418 
1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420   assert(D);
1421 
1422   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423     return false;
1424 
1425   // Ignore all entities declared within templates, and out-of-line definitions
1426   // of members of class templates.
1427   if (D->getDeclContext()->isDependentContext() ||
1428       D->getLexicalDeclContext()->isDependentContext())
1429     return false;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433       return false;
1434 
1435     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437         return false;
1438     } else {
1439       // 'static inline' functions are defined in headers; don't warn.
1440       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441         return false;
1442     }
1443 
1444     if (FD->doesThisDeclarationHaveABody() &&
1445         Context.DeclMustBeEmitted(FD))
1446       return false;
1447   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448     // Constants and utility variables are defined in headers with internal
1449     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1450     // like "inline".)
1451     if (!isMainFileLoc(*this, VD->getLocation()))
1452       return false;
1453 
1454     if (Context.DeclMustBeEmitted(VD))
1455       return false;
1456 
1457     if (VD->isStaticDataMember() &&
1458         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459       return false;
1460 
1461     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1462       return false;
1463   } else {
1464     return false;
1465   }
1466 
1467   // Only warn for unused decls internal to the translation unit.
1468   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469   // for inline functions defined in the main source file, for instance.
1470   return mightHaveNonExternalLinkage(D);
1471 }
1472 
1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1474   if (!D)
1475     return;
1476 
1477   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478     const FunctionDecl *First = FD->getFirstDecl();
1479     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480       return; // First should already be in the vector.
1481   }
1482 
1483   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484     const VarDecl *First = VD->getFirstDecl();
1485     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486       return; // First should already be in the vector.
1487   }
1488 
1489   if (ShouldWarnIfUnusedFileScopedDecl(D))
1490     UnusedFileScopedDecls.push_back(D);
1491 }
1492 
1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494   if (D->isInvalidDecl())
1495     return false;
1496 
1497   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498       D->hasAttr<ObjCPreciseLifetimeAttr>())
1499     return false;
1500 
1501   if (isa<LabelDecl>(D))
1502     return true;
1503 
1504   // Except for labels, we only care about unused decls that are local to
1505   // functions.
1506   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508     // For dependent types, the diagnostic is deferred.
1509     WithinFunction =
1510         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511   if (!WithinFunction)
1512     return false;
1513 
1514   if (isa<TypedefNameDecl>(D))
1515     return true;
1516 
1517   // White-list anything that isn't a local variable.
1518   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1519     return false;
1520 
1521   // Types of valid local variables should be complete, so this should succeed.
1522   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523 
1524     // White-list anything with an __attribute__((unused)) type.
1525     QualType Ty = VD->getType();
1526 
1527     // Only look at the outermost level of typedef.
1528     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529       if (TT->getDecl()->hasAttr<UnusedAttr>())
1530         return false;
1531     }
1532 
1533     // If we failed to complete the type for some reason, or if the type is
1534     // dependent, don't diagnose the variable.
1535     if (Ty->isIncompleteType() || Ty->isDependentType())
1536       return false;
1537 
1538     if (const TagType *TT = Ty->getAs<TagType>()) {
1539       const TagDecl *Tag = TT->getDecl();
1540       if (Tag->hasAttr<UnusedAttr>())
1541         return false;
1542 
1543       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1544         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1545           return false;
1546 
1547         if (const Expr *Init = VD->getInit()) {
1548           if (const ExprWithCleanups *Cleanups =
1549                   dyn_cast<ExprWithCleanups>(Init))
1550             Init = Cleanups->getSubExpr();
1551           const CXXConstructExpr *Construct =
1552             dyn_cast<CXXConstructExpr>(Init);
1553           if (Construct && !Construct->isElidable()) {
1554             CXXConstructorDecl *CD = Construct->getConstructor();
1555             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1556               return false;
1557           }
1558         }
1559       }
1560     }
1561 
1562     // TODO: __attribute__((unused)) templates?
1563   }
1564 
1565   return true;
1566 }
1567 
1568 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1569                                      FixItHint &Hint) {
1570   if (isa<LabelDecl>(D)) {
1571     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1572                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1573     if (AfterColon.isInvalid())
1574       return;
1575     Hint = FixItHint::CreateRemoval(CharSourceRange::
1576                                     getCharRange(D->getLocStart(), AfterColon));
1577   }
1578 }
1579 
1580 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1581   if (D->getTypeForDecl()->isDependentType())
1582     return;
1583 
1584   for (auto *TmpD : D->decls()) {
1585     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1586       DiagnoseUnusedDecl(T);
1587     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1588       DiagnoseUnusedNestedTypedefs(R);
1589   }
1590 }
1591 
1592 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1593 /// unless they are marked attr(unused).
1594 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1595   if (!ShouldDiagnoseUnusedDecl(D))
1596     return;
1597 
1598   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1599     // typedefs can be referenced later on, so the diagnostics are emitted
1600     // at end-of-translation-unit.
1601     UnusedLocalTypedefNameCandidates.insert(TD);
1602     return;
1603   }
1604 
1605   FixItHint Hint;
1606   GenerateFixForUnusedDecl(D, Context, Hint);
1607 
1608   unsigned DiagID;
1609   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1610     DiagID = diag::warn_unused_exception_param;
1611   else if (isa<LabelDecl>(D))
1612     DiagID = diag::warn_unused_label;
1613   else
1614     DiagID = diag::warn_unused_variable;
1615 
1616   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1617 }
1618 
1619 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1620   // Verify that we have no forward references left.  If so, there was a goto
1621   // or address of a label taken, but no definition of it.  Label fwd
1622   // definitions are indicated with a null substmt which is also not a resolved
1623   // MS inline assembly label name.
1624   bool Diagnose = false;
1625   if (L->isMSAsmLabel())
1626     Diagnose = !L->isResolvedMSAsmLabel();
1627   else
1628     Diagnose = L->getStmt() == nullptr;
1629   if (Diagnose)
1630     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1631 }
1632 
1633 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1634   S->mergeNRVOIntoParent();
1635 
1636   if (S->decl_empty()) return;
1637   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1638          "Scope shouldn't contain decls!");
1639 
1640   for (auto *TmpD : S->decls()) {
1641     assert(TmpD && "This decl didn't get pushed??");
1642 
1643     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1644     NamedDecl *D = cast<NamedDecl>(TmpD);
1645 
1646     if (!D->getDeclName()) continue;
1647 
1648     // Diagnose unused variables in this scope.
1649     if (!S->hasUnrecoverableErrorOccurred()) {
1650       DiagnoseUnusedDecl(D);
1651       if (const auto *RD = dyn_cast<RecordDecl>(D))
1652         DiagnoseUnusedNestedTypedefs(RD);
1653     }
1654 
1655     // If this was a forward reference to a label, verify it was defined.
1656     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1657       CheckPoppedLabel(LD, *this);
1658 
1659     // Remove this name from our lexical scope, and warn on it if we haven't
1660     // already.
1661     IdResolver.RemoveDecl(D);
1662     auto ShadowI = ShadowingDecls.find(D);
1663     if (ShadowI != ShadowingDecls.end()) {
1664       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1665         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1666             << D << FD << FD->getParent();
1667         Diag(FD->getLocation(), diag::note_previous_declaration);
1668       }
1669       ShadowingDecls.erase(ShadowI);
1670     }
1671   }
1672 }
1673 
1674 /// \brief Look for an Objective-C class in the translation unit.
1675 ///
1676 /// \param Id The name of the Objective-C class we're looking for. If
1677 /// typo-correction fixes this name, the Id will be updated
1678 /// to the fixed name.
1679 ///
1680 /// \param IdLoc The location of the name in the translation unit.
1681 ///
1682 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1683 /// if there is no class with the given name.
1684 ///
1685 /// \returns The declaration of the named Objective-C class, or NULL if the
1686 /// class could not be found.
1687 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1688                                               SourceLocation IdLoc,
1689                                               bool DoTypoCorrection) {
1690   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1691   // creation from this context.
1692   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1693 
1694   if (!IDecl && DoTypoCorrection) {
1695     // Perform typo correction at the given location, but only if we
1696     // find an Objective-C class name.
1697     if (TypoCorrection C = CorrectTypo(
1698             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1699             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1700             CTK_ErrorRecovery)) {
1701       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1702       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1703       Id = IDecl->getIdentifier();
1704     }
1705   }
1706   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1707   // This routine must always return a class definition, if any.
1708   if (Def && Def->getDefinition())
1709       Def = Def->getDefinition();
1710   return Def;
1711 }
1712 
1713 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1714 /// from S, where a non-field would be declared. This routine copes
1715 /// with the difference between C and C++ scoping rules in structs and
1716 /// unions. For example, the following code is well-formed in C but
1717 /// ill-formed in C++:
1718 /// @code
1719 /// struct S6 {
1720 ///   enum { BAR } e;
1721 /// };
1722 ///
1723 /// void test_S6() {
1724 ///   struct S6 a;
1725 ///   a.e = BAR;
1726 /// }
1727 /// @endcode
1728 /// For the declaration of BAR, this routine will return a different
1729 /// scope. The scope S will be the scope of the unnamed enumeration
1730 /// within S6. In C++, this routine will return the scope associated
1731 /// with S6, because the enumeration's scope is a transparent
1732 /// context but structures can contain non-field names. In C, this
1733 /// routine will return the translation unit scope, since the
1734 /// enumeration's scope is a transparent context and structures cannot
1735 /// contain non-field names.
1736 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1737   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1738          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1739          (S->isClassScope() && !getLangOpts().CPlusPlus))
1740     S = S->getParent();
1741   return S;
1742 }
1743 
1744 /// \brief Looks up the declaration of "struct objc_super" and
1745 /// saves it for later use in building builtin declaration of
1746 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1747 /// pre-existing declaration exists no action takes place.
1748 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1749                                         IdentifierInfo *II) {
1750   if (!II->isStr("objc_msgSendSuper"))
1751     return;
1752   ASTContext &Context = ThisSema.Context;
1753 
1754   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1755                       SourceLocation(), Sema::LookupTagName);
1756   ThisSema.LookupName(Result, S);
1757   if (Result.getResultKind() == LookupResult::Found)
1758     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1759       Context.setObjCSuperType(Context.getTagDeclType(TD));
1760 }
1761 
1762 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1763   switch (Error) {
1764   case ASTContext::GE_None:
1765     return "";
1766   case ASTContext::GE_Missing_stdio:
1767     return "stdio.h";
1768   case ASTContext::GE_Missing_setjmp:
1769     return "setjmp.h";
1770   case ASTContext::GE_Missing_ucontext:
1771     return "ucontext.h";
1772   }
1773   llvm_unreachable("unhandled error kind");
1774 }
1775 
1776 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1777 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1778 /// if we're creating this built-in in anticipation of redeclaring the
1779 /// built-in.
1780 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1781                                      Scope *S, bool ForRedeclaration,
1782                                      SourceLocation Loc) {
1783   LookupPredefedObjCSuperType(*this, S, II);
1784 
1785   ASTContext::GetBuiltinTypeError Error;
1786   QualType R = Context.GetBuiltinType(ID, Error);
1787   if (Error) {
1788     if (ForRedeclaration)
1789       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1790           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1791     return nullptr;
1792   }
1793 
1794   if (!ForRedeclaration &&
1795       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1796        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1797     Diag(Loc, diag::ext_implicit_lib_function_decl)
1798         << Context.BuiltinInfo.getName(ID) << R;
1799     if (Context.BuiltinInfo.getHeaderName(ID) &&
1800         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1801       Diag(Loc, diag::note_include_header_or_declare)
1802           << Context.BuiltinInfo.getHeaderName(ID)
1803           << Context.BuiltinInfo.getName(ID);
1804   }
1805 
1806   if (R.isNull())
1807     return nullptr;
1808 
1809   DeclContext *Parent = Context.getTranslationUnitDecl();
1810   if (getLangOpts().CPlusPlus) {
1811     LinkageSpecDecl *CLinkageDecl =
1812         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1813                                 LinkageSpecDecl::lang_c, false);
1814     CLinkageDecl->setImplicit();
1815     Parent->addDecl(CLinkageDecl);
1816     Parent = CLinkageDecl;
1817   }
1818 
1819   FunctionDecl *New = FunctionDecl::Create(Context,
1820                                            Parent,
1821                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1822                                            SC_Extern,
1823                                            false,
1824                                            R->isFunctionProtoType());
1825   New->setImplicit();
1826 
1827   // Create Decl objects for each parameter, adding them to the
1828   // FunctionDecl.
1829   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1830     SmallVector<ParmVarDecl*, 16> Params;
1831     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1832       ParmVarDecl *parm =
1833           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1834                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1835                               SC_None, nullptr);
1836       parm->setScopeInfo(0, i);
1837       Params.push_back(parm);
1838     }
1839     New->setParams(Params);
1840   }
1841 
1842   AddKnownFunctionAttributes(New);
1843   RegisterLocallyScopedExternCDecl(New, S);
1844 
1845   // TUScope is the translation-unit scope to insert this function into.
1846   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1847   // relate Scopes to DeclContexts, and probably eliminate CurContext
1848   // entirely, but we're not there yet.
1849   DeclContext *SavedContext = CurContext;
1850   CurContext = Parent;
1851   PushOnScopeChains(New, TUScope);
1852   CurContext = SavedContext;
1853   return New;
1854 }
1855 
1856 /// Typedef declarations don't have linkage, but they still denote the same
1857 /// entity if their types are the same.
1858 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1859 /// isSameEntity.
1860 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1861                                                      TypedefNameDecl *Decl,
1862                                                      LookupResult &Previous) {
1863   // This is only interesting when modules are enabled.
1864   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1865     return;
1866 
1867   // Empty sets are uninteresting.
1868   if (Previous.empty())
1869     return;
1870 
1871   LookupResult::Filter Filter = Previous.makeFilter();
1872   while (Filter.hasNext()) {
1873     NamedDecl *Old = Filter.next();
1874 
1875     // Non-hidden declarations are never ignored.
1876     if (S.isVisible(Old))
1877       continue;
1878 
1879     // Declarations of the same entity are not ignored, even if they have
1880     // different linkages.
1881     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1882       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1883                                 Decl->getUnderlyingType()))
1884         continue;
1885 
1886       // If both declarations give a tag declaration a typedef name for linkage
1887       // purposes, then they declare the same entity.
1888       if (S.getLangOpts().CPlusPlus &&
1889           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1890           Decl->getAnonDeclWithTypedefName())
1891         continue;
1892     }
1893 
1894     Filter.erase();
1895   }
1896 
1897   Filter.done();
1898 }
1899 
1900 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1901   QualType OldType;
1902   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1903     OldType = OldTypedef->getUnderlyingType();
1904   else
1905     OldType = Context.getTypeDeclType(Old);
1906   QualType NewType = New->getUnderlyingType();
1907 
1908   if (NewType->isVariablyModifiedType()) {
1909     // Must not redefine a typedef with a variably-modified type.
1910     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1911     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1912       << Kind << NewType;
1913     if (Old->getLocation().isValid())
1914       Diag(Old->getLocation(), diag::note_previous_definition);
1915     New->setInvalidDecl();
1916     return true;
1917   }
1918 
1919   if (OldType != NewType &&
1920       !OldType->isDependentType() &&
1921       !NewType->isDependentType() &&
1922       !Context.hasSameType(OldType, NewType)) {
1923     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1924     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1925       << Kind << NewType << OldType;
1926     if (Old->getLocation().isValid())
1927       Diag(Old->getLocation(), diag::note_previous_definition);
1928     New->setInvalidDecl();
1929     return true;
1930   }
1931   return false;
1932 }
1933 
1934 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1935 /// same name and scope as a previous declaration 'Old'.  Figure out
1936 /// how to resolve this situation, merging decls or emitting
1937 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1938 ///
1939 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1940                                 LookupResult &OldDecls) {
1941   // If the new decl is known invalid already, don't bother doing any
1942   // merging checks.
1943   if (New->isInvalidDecl()) return;
1944 
1945   // Allow multiple definitions for ObjC built-in typedefs.
1946   // FIXME: Verify the underlying types are equivalent!
1947   if (getLangOpts().ObjC1) {
1948     const IdentifierInfo *TypeID = New->getIdentifier();
1949     switch (TypeID->getLength()) {
1950     default: break;
1951     case 2:
1952       {
1953         if (!TypeID->isStr("id"))
1954           break;
1955         QualType T = New->getUnderlyingType();
1956         if (!T->isPointerType())
1957           break;
1958         if (!T->isVoidPointerType()) {
1959           QualType PT = T->getAs<PointerType>()->getPointeeType();
1960           if (!PT->isStructureType())
1961             break;
1962         }
1963         Context.setObjCIdRedefinitionType(T);
1964         // Install the built-in type for 'id', ignoring the current definition.
1965         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1966         return;
1967       }
1968     case 5:
1969       if (!TypeID->isStr("Class"))
1970         break;
1971       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1972       // Install the built-in type for 'Class', ignoring the current definition.
1973       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1974       return;
1975     case 3:
1976       if (!TypeID->isStr("SEL"))
1977         break;
1978       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1979       // Install the built-in type for 'SEL', ignoring the current definition.
1980       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1981       return;
1982     }
1983     // Fall through - the typedef name was not a builtin type.
1984   }
1985 
1986   // Verify the old decl was also a type.
1987   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1988   if (!Old) {
1989     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1990       << New->getDeclName();
1991 
1992     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1993     if (OldD->getLocation().isValid())
1994       Diag(OldD->getLocation(), diag::note_previous_definition);
1995 
1996     return New->setInvalidDecl();
1997   }
1998 
1999   // If the old declaration is invalid, just give up here.
2000   if (Old->isInvalidDecl())
2001     return New->setInvalidDecl();
2002 
2003   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2004     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2005     auto *NewTag = New->getAnonDeclWithTypedefName();
2006     NamedDecl *Hidden = nullptr;
2007     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2008         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2009         !hasVisibleDefinition(OldTag, &Hidden)) {
2010       // There is a definition of this tag, but it is not visible. Use it
2011       // instead of our tag.
2012       New->setTypeForDecl(OldTD->getTypeForDecl());
2013       if (OldTD->isModed())
2014         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2015                                     OldTD->getUnderlyingType());
2016       else
2017         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2018 
2019       // Make the old tag definition visible.
2020       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2021 
2022       // If this was an unscoped enumeration, yank all of its enumerators
2023       // out of the scope.
2024       if (isa<EnumDecl>(NewTag)) {
2025         Scope *EnumScope = getNonFieldDeclScope(S);
2026         for (auto *D : NewTag->decls()) {
2027           auto *ED = cast<EnumConstantDecl>(D);
2028           assert(EnumScope->isDeclScope(ED));
2029           EnumScope->RemoveDecl(ED);
2030           IdResolver.RemoveDecl(ED);
2031           ED->getLexicalDeclContext()->removeDecl(ED);
2032         }
2033       }
2034     }
2035   }
2036 
2037   // If the typedef types are not identical, reject them in all languages and
2038   // with any extensions enabled.
2039   if (isIncompatibleTypedef(Old, New))
2040     return;
2041 
2042   // The types match.  Link up the redeclaration chain and merge attributes if
2043   // the old declaration was a typedef.
2044   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2045     New->setPreviousDecl(Typedef);
2046     mergeDeclAttributes(New, Old);
2047   }
2048 
2049   if (getLangOpts().MicrosoftExt)
2050     return;
2051 
2052   if (getLangOpts().CPlusPlus) {
2053     // C++ [dcl.typedef]p2:
2054     //   In a given non-class scope, a typedef specifier can be used to
2055     //   redefine the name of any type declared in that scope to refer
2056     //   to the type to which it already refers.
2057     if (!isa<CXXRecordDecl>(CurContext))
2058       return;
2059 
2060     // C++0x [dcl.typedef]p4:
2061     //   In a given class scope, a typedef specifier can be used to redefine
2062     //   any class-name declared in that scope that is not also a typedef-name
2063     //   to refer to the type to which it already refers.
2064     //
2065     // This wording came in via DR424, which was a correction to the
2066     // wording in DR56, which accidentally banned code like:
2067     //
2068     //   struct S {
2069     //     typedef struct A { } A;
2070     //   };
2071     //
2072     // in the C++03 standard. We implement the C++0x semantics, which
2073     // allow the above but disallow
2074     //
2075     //   struct S {
2076     //     typedef int I;
2077     //     typedef int I;
2078     //   };
2079     //
2080     // since that was the intent of DR56.
2081     if (!isa<TypedefNameDecl>(Old))
2082       return;
2083 
2084     Diag(New->getLocation(), diag::err_redefinition)
2085       << New->getDeclName();
2086     Diag(Old->getLocation(), diag::note_previous_definition);
2087     return New->setInvalidDecl();
2088   }
2089 
2090   // Modules always permit redefinition of typedefs, as does C11.
2091   if (getLangOpts().Modules || getLangOpts().C11)
2092     return;
2093 
2094   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2095   // is normally mapped to an error, but can be controlled with
2096   // -Wtypedef-redefinition.  If either the original or the redefinition is
2097   // in a system header, don't emit this for compatibility with GCC.
2098   if (getDiagnostics().getSuppressSystemWarnings() &&
2099       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2100        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2101     return;
2102 
2103   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2104     << New->getDeclName();
2105   Diag(Old->getLocation(), diag::note_previous_definition);
2106 }
2107 
2108 /// DeclhasAttr - returns true if decl Declaration already has the target
2109 /// attribute.
2110 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2111   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2112   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2113   for (const auto *i : D->attrs())
2114     if (i->getKind() == A->getKind()) {
2115       if (Ann) {
2116         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2117           return true;
2118         continue;
2119       }
2120       // FIXME: Don't hardcode this check
2121       if (OA && isa<OwnershipAttr>(i))
2122         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2123       return true;
2124     }
2125 
2126   return false;
2127 }
2128 
2129 static bool isAttributeTargetADefinition(Decl *D) {
2130   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2131     return VD->isThisDeclarationADefinition();
2132   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2133     return TD->isCompleteDefinition() || TD->isBeingDefined();
2134   return true;
2135 }
2136 
2137 /// Merge alignment attributes from \p Old to \p New, taking into account the
2138 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2139 ///
2140 /// \return \c true if any attributes were added to \p New.
2141 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2142   // Look for alignas attributes on Old, and pick out whichever attribute
2143   // specifies the strictest alignment requirement.
2144   AlignedAttr *OldAlignasAttr = nullptr;
2145   AlignedAttr *OldStrictestAlignAttr = nullptr;
2146   unsigned OldAlign = 0;
2147   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2148     // FIXME: We have no way of representing inherited dependent alignments
2149     // in a case like:
2150     //   template<int A, int B> struct alignas(A) X;
2151     //   template<int A, int B> struct alignas(B) X {};
2152     // For now, we just ignore any alignas attributes which are not on the
2153     // definition in such a case.
2154     if (I->isAlignmentDependent())
2155       return false;
2156 
2157     if (I->isAlignas())
2158       OldAlignasAttr = I;
2159 
2160     unsigned Align = I->getAlignment(S.Context);
2161     if (Align > OldAlign) {
2162       OldAlign = Align;
2163       OldStrictestAlignAttr = I;
2164     }
2165   }
2166 
2167   // Look for alignas attributes on New.
2168   AlignedAttr *NewAlignasAttr = nullptr;
2169   unsigned NewAlign = 0;
2170   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2171     if (I->isAlignmentDependent())
2172       return false;
2173 
2174     if (I->isAlignas())
2175       NewAlignasAttr = I;
2176 
2177     unsigned Align = I->getAlignment(S.Context);
2178     if (Align > NewAlign)
2179       NewAlign = Align;
2180   }
2181 
2182   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2183     // Both declarations have 'alignas' attributes. We require them to match.
2184     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2185     // fall short. (If two declarations both have alignas, they must both match
2186     // every definition, and so must match each other if there is a definition.)
2187 
2188     // If either declaration only contains 'alignas(0)' specifiers, then it
2189     // specifies the natural alignment for the type.
2190     if (OldAlign == 0 || NewAlign == 0) {
2191       QualType Ty;
2192       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2193         Ty = VD->getType();
2194       else
2195         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2196 
2197       if (OldAlign == 0)
2198         OldAlign = S.Context.getTypeAlign(Ty);
2199       if (NewAlign == 0)
2200         NewAlign = S.Context.getTypeAlign(Ty);
2201     }
2202 
2203     if (OldAlign != NewAlign) {
2204       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2205         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2206         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2207       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2208     }
2209   }
2210 
2211   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2212     // C++11 [dcl.align]p6:
2213     //   if any declaration of an entity has an alignment-specifier,
2214     //   every defining declaration of that entity shall specify an
2215     //   equivalent alignment.
2216     // C11 6.7.5/7:
2217     //   If the definition of an object does not have an alignment
2218     //   specifier, any other declaration of that object shall also
2219     //   have no alignment specifier.
2220     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2221       << OldAlignasAttr;
2222     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2223       << OldAlignasAttr;
2224   }
2225 
2226   bool AnyAdded = false;
2227 
2228   // Ensure we have an attribute representing the strictest alignment.
2229   if (OldAlign > NewAlign) {
2230     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2231     Clone->setInherited(true);
2232     New->addAttr(Clone);
2233     AnyAdded = true;
2234   }
2235 
2236   // Ensure we have an alignas attribute if the old declaration had one.
2237   if (OldAlignasAttr && !NewAlignasAttr &&
2238       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2239     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2240     Clone->setInherited(true);
2241     New->addAttr(Clone);
2242     AnyAdded = true;
2243   }
2244 
2245   return AnyAdded;
2246 }
2247 
2248 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2249                                const InheritableAttr *Attr,
2250                                Sema::AvailabilityMergeKind AMK) {
2251   // This function copies an attribute Attr from a previous declaration to the
2252   // new declaration D if the new declaration doesn't itself have that attribute
2253   // yet or if that attribute allows duplicates.
2254   // If you're adding a new attribute that requires logic different from
2255   // "use explicit attribute on decl if present, else use attribute from
2256   // previous decl", for example if the attribute needs to be consistent
2257   // between redeclarations, you need to call a custom merge function here.
2258   InheritableAttr *NewAttr = nullptr;
2259   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2260   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2261     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2262                                       AA->isImplicit(), AA->getIntroduced(),
2263                                       AA->getDeprecated(),
2264                                       AA->getObsoleted(), AA->getUnavailable(),
2265                                       AA->getMessage(), AA->getStrict(),
2266                                       AA->getReplacement(), AMK,
2267                                       AttrSpellingListIndex);
2268   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2269     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2270                                     AttrSpellingListIndex);
2271   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2272     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2273                                         AttrSpellingListIndex);
2274   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2275     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2276                                    AttrSpellingListIndex);
2277   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2278     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2279                                    AttrSpellingListIndex);
2280   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2281     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2282                                 FA->getFormatIdx(), FA->getFirstArg(),
2283                                 AttrSpellingListIndex);
2284   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2285     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2286                                  AttrSpellingListIndex);
2287   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2288     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2289                                        AttrSpellingListIndex,
2290                                        IA->getSemanticSpelling());
2291   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2292     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2293                                       &S.Context.Idents.get(AA->getSpelling()),
2294                                       AttrSpellingListIndex);
2295   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2296            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2297             isa<CUDAGlobalAttr>(Attr))) {
2298     // CUDA target attributes are part of function signature for
2299     // overloading purposes and must not be merged.
2300     return false;
2301   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2302     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2303   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2304     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2305   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2306     NewAttr = S.mergeInternalLinkageAttr(
2307         D, InternalLinkageA->getRange(),
2308         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2309         AttrSpellingListIndex);
2310   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2311     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2312                                 &S.Context.Idents.get(CommonA->getSpelling()),
2313                                 AttrSpellingListIndex);
2314   else if (isa<AlignedAttr>(Attr))
2315     // AlignedAttrs are handled separately, because we need to handle all
2316     // such attributes on a declaration at the same time.
2317     NewAttr = nullptr;
2318   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2319            (AMK == Sema::AMK_Override ||
2320             AMK == Sema::AMK_ProtocolImplementation))
2321     NewAttr = nullptr;
2322   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2323     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2324                               UA->getGuid());
2325   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2326     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2327 
2328   if (NewAttr) {
2329     NewAttr->setInherited(true);
2330     D->addAttr(NewAttr);
2331     if (isa<MSInheritanceAttr>(NewAttr))
2332       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2333     return true;
2334   }
2335 
2336   return false;
2337 }
2338 
2339 static const Decl *getDefinition(const Decl *D) {
2340   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2341     return TD->getDefinition();
2342   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2343     const VarDecl *Def = VD->getDefinition();
2344     if (Def)
2345       return Def;
2346     return VD->getActingDefinition();
2347   }
2348   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2349     return FD->getDefinition();
2350   return nullptr;
2351 }
2352 
2353 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2354   for (const auto *Attribute : D->attrs())
2355     if (Attribute->getKind() == Kind)
2356       return true;
2357   return false;
2358 }
2359 
2360 /// checkNewAttributesAfterDef - If we already have a definition, check that
2361 /// there are no new attributes in this declaration.
2362 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2363   if (!New->hasAttrs())
2364     return;
2365 
2366   const Decl *Def = getDefinition(Old);
2367   if (!Def || Def == New)
2368     return;
2369 
2370   AttrVec &NewAttributes = New->getAttrs();
2371   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2372     const Attr *NewAttribute = NewAttributes[I];
2373 
2374     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2375       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2376         Sema::SkipBodyInfo SkipBody;
2377         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2378 
2379         // If we're skipping this definition, drop the "alias" attribute.
2380         if (SkipBody.ShouldSkip) {
2381           NewAttributes.erase(NewAttributes.begin() + I);
2382           --E;
2383           continue;
2384         }
2385       } else {
2386         VarDecl *VD = cast<VarDecl>(New);
2387         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2388                                 VarDecl::TentativeDefinition
2389                             ? diag::err_alias_after_tentative
2390                             : diag::err_redefinition;
2391         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2392         S.Diag(Def->getLocation(), diag::note_previous_definition);
2393         VD->setInvalidDecl();
2394       }
2395       ++I;
2396       continue;
2397     }
2398 
2399     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2400       // Tentative definitions are only interesting for the alias check above.
2401       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2402         ++I;
2403         continue;
2404       }
2405     }
2406 
2407     if (hasAttribute(Def, NewAttribute->getKind())) {
2408       ++I;
2409       continue; // regular attr merging will take care of validating this.
2410     }
2411 
2412     if (isa<C11NoReturnAttr>(NewAttribute)) {
2413       // C's _Noreturn is allowed to be added to a function after it is defined.
2414       ++I;
2415       continue;
2416     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2417       if (AA->isAlignas()) {
2418         // C++11 [dcl.align]p6:
2419         //   if any declaration of an entity has an alignment-specifier,
2420         //   every defining declaration of that entity shall specify an
2421         //   equivalent alignment.
2422         // C11 6.7.5/7:
2423         //   If the definition of an object does not have an alignment
2424         //   specifier, any other declaration of that object shall also
2425         //   have no alignment specifier.
2426         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2427           << AA;
2428         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2429           << AA;
2430         NewAttributes.erase(NewAttributes.begin() + I);
2431         --E;
2432         continue;
2433       }
2434     }
2435 
2436     S.Diag(NewAttribute->getLocation(),
2437            diag::warn_attribute_precede_definition);
2438     S.Diag(Def->getLocation(), diag::note_previous_definition);
2439     NewAttributes.erase(NewAttributes.begin() + I);
2440     --E;
2441   }
2442 }
2443 
2444 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2445 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2446                                AvailabilityMergeKind AMK) {
2447   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2448     UsedAttr *NewAttr = OldAttr->clone(Context);
2449     NewAttr->setInherited(true);
2450     New->addAttr(NewAttr);
2451   }
2452 
2453   if (!Old->hasAttrs() && !New->hasAttrs())
2454     return;
2455 
2456   // Attributes declared post-definition are currently ignored.
2457   checkNewAttributesAfterDef(*this, New, Old);
2458 
2459   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2460     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2461       if (OldA->getLabel() != NewA->getLabel()) {
2462         // This redeclaration changes __asm__ label.
2463         Diag(New->getLocation(), diag::err_different_asm_label);
2464         Diag(OldA->getLocation(), diag::note_previous_declaration);
2465       }
2466     } else if (Old->isUsed()) {
2467       // This redeclaration adds an __asm__ label to a declaration that has
2468       // already been ODR-used.
2469       Diag(New->getLocation(), diag::err_late_asm_label_name)
2470         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2471     }
2472   }
2473 
2474   // Re-declaration cannot add abi_tag's.
2475   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2476     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2477       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2478         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2479                       NewTag) == OldAbiTagAttr->tags_end()) {
2480           Diag(NewAbiTagAttr->getLocation(),
2481                diag::err_new_abi_tag_on_redeclaration)
2482               << NewTag;
2483           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2484         }
2485       }
2486     } else {
2487       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2488       Diag(Old->getLocation(), diag::note_previous_declaration);
2489     }
2490   }
2491 
2492   if (!Old->hasAttrs())
2493     return;
2494 
2495   bool foundAny = New->hasAttrs();
2496 
2497   // Ensure that any moving of objects within the allocated map is done before
2498   // we process them.
2499   if (!foundAny) New->setAttrs(AttrVec());
2500 
2501   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2502     // Ignore deprecated/unavailable/availability attributes if requested.
2503     AvailabilityMergeKind LocalAMK = AMK_None;
2504     if (isa<DeprecatedAttr>(I) ||
2505         isa<UnavailableAttr>(I) ||
2506         isa<AvailabilityAttr>(I)) {
2507       switch (AMK) {
2508       case AMK_None:
2509         continue;
2510 
2511       case AMK_Redeclaration:
2512       case AMK_Override:
2513       case AMK_ProtocolImplementation:
2514         LocalAMK = AMK;
2515         break;
2516       }
2517     }
2518 
2519     // Already handled.
2520     if (isa<UsedAttr>(I))
2521       continue;
2522 
2523     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2524       foundAny = true;
2525   }
2526 
2527   if (mergeAlignedAttrs(*this, New, Old))
2528     foundAny = true;
2529 
2530   if (!foundAny) New->dropAttrs();
2531 }
2532 
2533 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2534 /// to the new one.
2535 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2536                                      const ParmVarDecl *oldDecl,
2537                                      Sema &S) {
2538   // C++11 [dcl.attr.depend]p2:
2539   //   The first declaration of a function shall specify the
2540   //   carries_dependency attribute for its declarator-id if any declaration
2541   //   of the function specifies the carries_dependency attribute.
2542   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2543   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2544     S.Diag(CDA->getLocation(),
2545            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2546     // Find the first declaration of the parameter.
2547     // FIXME: Should we build redeclaration chains for function parameters?
2548     const FunctionDecl *FirstFD =
2549       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2550     const ParmVarDecl *FirstVD =
2551       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2552     S.Diag(FirstVD->getLocation(),
2553            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2554   }
2555 
2556   if (!oldDecl->hasAttrs())
2557     return;
2558 
2559   bool foundAny = newDecl->hasAttrs();
2560 
2561   // Ensure that any moving of objects within the allocated map is
2562   // done before we process them.
2563   if (!foundAny) newDecl->setAttrs(AttrVec());
2564 
2565   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2566     if (!DeclHasAttr(newDecl, I)) {
2567       InheritableAttr *newAttr =
2568         cast<InheritableParamAttr>(I->clone(S.Context));
2569       newAttr->setInherited(true);
2570       newDecl->addAttr(newAttr);
2571       foundAny = true;
2572     }
2573   }
2574 
2575   if (!foundAny) newDecl->dropAttrs();
2576 }
2577 
2578 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2579                                 const ParmVarDecl *OldParam,
2580                                 Sema &S) {
2581   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2582     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2583       if (*Oldnullability != *Newnullability) {
2584         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2585           << DiagNullabilityKind(
2586                *Newnullability,
2587                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2588                 != 0))
2589           << DiagNullabilityKind(
2590                *Oldnullability,
2591                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2592                 != 0));
2593         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2594       }
2595     } else {
2596       QualType NewT = NewParam->getType();
2597       NewT = S.Context.getAttributedType(
2598                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2599                          NewT, NewT);
2600       NewParam->setType(NewT);
2601     }
2602   }
2603 }
2604 
2605 namespace {
2606 
2607 /// Used in MergeFunctionDecl to keep track of function parameters in
2608 /// C.
2609 struct GNUCompatibleParamWarning {
2610   ParmVarDecl *OldParm;
2611   ParmVarDecl *NewParm;
2612   QualType PromotedType;
2613 };
2614 
2615 } // end anonymous namespace
2616 
2617 /// getSpecialMember - get the special member enum for a method.
2618 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2619   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2620     if (Ctor->isDefaultConstructor())
2621       return Sema::CXXDefaultConstructor;
2622 
2623     if (Ctor->isCopyConstructor())
2624       return Sema::CXXCopyConstructor;
2625 
2626     if (Ctor->isMoveConstructor())
2627       return Sema::CXXMoveConstructor;
2628   } else if (isa<CXXDestructorDecl>(MD)) {
2629     return Sema::CXXDestructor;
2630   } else if (MD->isCopyAssignmentOperator()) {
2631     return Sema::CXXCopyAssignment;
2632   } else if (MD->isMoveAssignmentOperator()) {
2633     return Sema::CXXMoveAssignment;
2634   }
2635 
2636   return Sema::CXXInvalid;
2637 }
2638 
2639 // Determine whether the previous declaration was a definition, implicit
2640 // declaration, or a declaration.
2641 template <typename T>
2642 static std::pair<diag::kind, SourceLocation>
2643 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2644   diag::kind PrevDiag;
2645   SourceLocation OldLocation = Old->getLocation();
2646   if (Old->isThisDeclarationADefinition())
2647     PrevDiag = diag::note_previous_definition;
2648   else if (Old->isImplicit()) {
2649     PrevDiag = diag::note_previous_implicit_declaration;
2650     if (OldLocation.isInvalid())
2651       OldLocation = New->getLocation();
2652   } else
2653     PrevDiag = diag::note_previous_declaration;
2654   return std::make_pair(PrevDiag, OldLocation);
2655 }
2656 
2657 /// canRedefineFunction - checks if a function can be redefined. Currently,
2658 /// only extern inline functions can be redefined, and even then only in
2659 /// GNU89 mode.
2660 static bool canRedefineFunction(const FunctionDecl *FD,
2661                                 const LangOptions& LangOpts) {
2662   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2663           !LangOpts.CPlusPlus &&
2664           FD->isInlineSpecified() &&
2665           FD->getStorageClass() == SC_Extern);
2666 }
2667 
2668 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2669   const AttributedType *AT = T->getAs<AttributedType>();
2670   while (AT && !AT->isCallingConv())
2671     AT = AT->getModifiedType()->getAs<AttributedType>();
2672   return AT;
2673 }
2674 
2675 template <typename T>
2676 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2677   const DeclContext *DC = Old->getDeclContext();
2678   if (DC->isRecord())
2679     return false;
2680 
2681   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2682   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2683     return true;
2684   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2685     return true;
2686   return false;
2687 }
2688 
2689 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2690 static bool isExternC(VarTemplateDecl *) { return false; }
2691 
2692 /// \brief Check whether a redeclaration of an entity introduced by a
2693 /// using-declaration is valid, given that we know it's not an overload
2694 /// (nor a hidden tag declaration).
2695 template<typename ExpectedDecl>
2696 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2697                                    ExpectedDecl *New) {
2698   // C++11 [basic.scope.declarative]p4:
2699   //   Given a set of declarations in a single declarative region, each of
2700   //   which specifies the same unqualified name,
2701   //   -- they shall all refer to the same entity, or all refer to functions
2702   //      and function templates; or
2703   //   -- exactly one declaration shall declare a class name or enumeration
2704   //      name that is not a typedef name and the other declarations shall all
2705   //      refer to the same variable or enumerator, or all refer to functions
2706   //      and function templates; in this case the class name or enumeration
2707   //      name is hidden (3.3.10).
2708 
2709   // C++11 [namespace.udecl]p14:
2710   //   If a function declaration in namespace scope or block scope has the
2711   //   same name and the same parameter-type-list as a function introduced
2712   //   by a using-declaration, and the declarations do not declare the same
2713   //   function, the program is ill-formed.
2714 
2715   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2716   if (Old &&
2717       !Old->getDeclContext()->getRedeclContext()->Equals(
2718           New->getDeclContext()->getRedeclContext()) &&
2719       !(isExternC(Old) && isExternC(New)))
2720     Old = nullptr;
2721 
2722   if (!Old) {
2723     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2724     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2725     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2726     return true;
2727   }
2728   return false;
2729 }
2730 
2731 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2732                                             const FunctionDecl *B) {
2733   assert(A->getNumParams() == B->getNumParams());
2734 
2735   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2736     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2737     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2738     if (AttrA == AttrB)
2739       return true;
2740     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2741   };
2742 
2743   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2744 }
2745 
2746 /// MergeFunctionDecl - We just parsed a function 'New' from
2747 /// declarator D which has the same name and scope as a previous
2748 /// declaration 'Old'.  Figure out how to resolve this situation,
2749 /// merging decls or emitting diagnostics as appropriate.
2750 ///
2751 /// In C++, New and Old must be declarations that are not
2752 /// overloaded. Use IsOverload to determine whether New and Old are
2753 /// overloaded, and to select the Old declaration that New should be
2754 /// merged with.
2755 ///
2756 /// Returns true if there was an error, false otherwise.
2757 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2758                              Scope *S, bool MergeTypeWithOld) {
2759   // Verify the old decl was also a function.
2760   FunctionDecl *Old = OldD->getAsFunction();
2761   if (!Old) {
2762     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2763       if (New->getFriendObjectKind()) {
2764         Diag(New->getLocation(), diag::err_using_decl_friend);
2765         Diag(Shadow->getTargetDecl()->getLocation(),
2766              diag::note_using_decl_target);
2767         Diag(Shadow->getUsingDecl()->getLocation(),
2768              diag::note_using_decl) << 0;
2769         return true;
2770       }
2771 
2772       // Check whether the two declarations might declare the same function.
2773       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2774         return true;
2775       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2776     } else {
2777       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2778         << New->getDeclName();
2779       Diag(OldD->getLocation(), diag::note_previous_definition);
2780       return true;
2781     }
2782   }
2783 
2784   // If the old declaration is invalid, just give up here.
2785   if (Old->isInvalidDecl())
2786     return true;
2787 
2788   diag::kind PrevDiag;
2789   SourceLocation OldLocation;
2790   std::tie(PrevDiag, OldLocation) =
2791       getNoteDiagForInvalidRedeclaration(Old, New);
2792 
2793   // Don't complain about this if we're in GNU89 mode and the old function
2794   // is an extern inline function.
2795   // Don't complain about specializations. They are not supposed to have
2796   // storage classes.
2797   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2798       New->getStorageClass() == SC_Static &&
2799       Old->hasExternalFormalLinkage() &&
2800       !New->getTemplateSpecializationInfo() &&
2801       !canRedefineFunction(Old, getLangOpts())) {
2802     if (getLangOpts().MicrosoftExt) {
2803       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2804       Diag(OldLocation, PrevDiag);
2805     } else {
2806       Diag(New->getLocation(), diag::err_static_non_static) << New;
2807       Diag(OldLocation, PrevDiag);
2808       return true;
2809     }
2810   }
2811 
2812   if (New->hasAttr<InternalLinkageAttr>() &&
2813       !Old->hasAttr<InternalLinkageAttr>()) {
2814     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2815         << New->getDeclName();
2816     Diag(Old->getLocation(), diag::note_previous_definition);
2817     New->dropAttr<InternalLinkageAttr>();
2818   }
2819 
2820   // If a function is first declared with a calling convention, but is later
2821   // declared or defined without one, all following decls assume the calling
2822   // convention of the first.
2823   //
2824   // It's OK if a function is first declared without a calling convention,
2825   // but is later declared or defined with the default calling convention.
2826   //
2827   // To test if either decl has an explicit calling convention, we look for
2828   // AttributedType sugar nodes on the type as written.  If they are missing or
2829   // were canonicalized away, we assume the calling convention was implicit.
2830   //
2831   // Note also that we DO NOT return at this point, because we still have
2832   // other tests to run.
2833   QualType OldQType = Context.getCanonicalType(Old->getType());
2834   QualType NewQType = Context.getCanonicalType(New->getType());
2835   const FunctionType *OldType = cast<FunctionType>(OldQType);
2836   const FunctionType *NewType = cast<FunctionType>(NewQType);
2837   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2838   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2839   bool RequiresAdjustment = false;
2840 
2841   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2842     FunctionDecl *First = Old->getFirstDecl();
2843     const FunctionType *FT =
2844         First->getType().getCanonicalType()->castAs<FunctionType>();
2845     FunctionType::ExtInfo FI = FT->getExtInfo();
2846     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2847     if (!NewCCExplicit) {
2848       // Inherit the CC from the previous declaration if it was specified
2849       // there but not here.
2850       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2851       RequiresAdjustment = true;
2852     } else {
2853       // Calling conventions aren't compatible, so complain.
2854       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2855       Diag(New->getLocation(), diag::err_cconv_change)
2856         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2857         << !FirstCCExplicit
2858         << (!FirstCCExplicit ? "" :
2859             FunctionType::getNameForCallConv(FI.getCC()));
2860 
2861       // Put the note on the first decl, since it is the one that matters.
2862       Diag(First->getLocation(), diag::note_previous_declaration);
2863       return true;
2864     }
2865   }
2866 
2867   // FIXME: diagnose the other way around?
2868   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2869     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2870     RequiresAdjustment = true;
2871   }
2872 
2873   // Merge regparm attribute.
2874   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2875       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2876     if (NewTypeInfo.getHasRegParm()) {
2877       Diag(New->getLocation(), diag::err_regparm_mismatch)
2878         << NewType->getRegParmType()
2879         << OldType->getRegParmType();
2880       Diag(OldLocation, diag::note_previous_declaration);
2881       return true;
2882     }
2883 
2884     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2885     RequiresAdjustment = true;
2886   }
2887 
2888   // Merge ns_returns_retained attribute.
2889   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2890     if (NewTypeInfo.getProducesResult()) {
2891       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2892       Diag(OldLocation, diag::note_previous_declaration);
2893       return true;
2894     }
2895 
2896     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2897     RequiresAdjustment = true;
2898   }
2899 
2900   if (RequiresAdjustment) {
2901     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2902     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2903     New->setType(QualType(AdjustedType, 0));
2904     NewQType = Context.getCanonicalType(New->getType());
2905     NewType = cast<FunctionType>(NewQType);
2906   }
2907 
2908   // If this redeclaration makes the function inline, we may need to add it to
2909   // UndefinedButUsed.
2910   if (!Old->isInlined() && New->isInlined() &&
2911       !New->hasAttr<GNUInlineAttr>() &&
2912       !getLangOpts().GNUInline &&
2913       Old->isUsed(false) &&
2914       !Old->isDefined() && !New->isThisDeclarationADefinition())
2915     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2916                                            SourceLocation()));
2917 
2918   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2919   // about it.
2920   if (New->hasAttr<GNUInlineAttr>() &&
2921       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2922     UndefinedButUsed.erase(Old->getCanonicalDecl());
2923   }
2924 
2925   // If pass_object_size params don't match up perfectly, this isn't a valid
2926   // redeclaration.
2927   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2928       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2929     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2930         << New->getDeclName();
2931     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2932     return true;
2933   }
2934 
2935   if (getLangOpts().CPlusPlus) {
2936     // (C++98 13.1p2):
2937     //   Certain function declarations cannot be overloaded:
2938     //     -- Function declarations that differ only in the return type
2939     //        cannot be overloaded.
2940 
2941     // Go back to the type source info to compare the declared return types,
2942     // per C++1y [dcl.type.auto]p13:
2943     //   Redeclarations or specializations of a function or function template
2944     //   with a declared return type that uses a placeholder type shall also
2945     //   use that placeholder, not a deduced type.
2946     QualType OldDeclaredReturnType =
2947         (Old->getTypeSourceInfo()
2948              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2949              : OldType)->getReturnType();
2950     QualType NewDeclaredReturnType =
2951         (New->getTypeSourceInfo()
2952              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2953              : NewType)->getReturnType();
2954     QualType ResQT;
2955     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2956         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2957           New->isLocalExternDecl())) {
2958       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2959           OldDeclaredReturnType->isObjCObjectPointerType())
2960         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2961       if (ResQT.isNull()) {
2962         if (New->isCXXClassMember() && New->isOutOfLine())
2963           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2964               << New << New->getReturnTypeSourceRange();
2965         else
2966           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2967               << New->getReturnTypeSourceRange();
2968         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2969                                     << Old->getReturnTypeSourceRange();
2970         return true;
2971       }
2972       else
2973         NewQType = ResQT;
2974     }
2975 
2976     QualType OldReturnType = OldType->getReturnType();
2977     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2978     if (OldReturnType != NewReturnType) {
2979       // If this function has a deduced return type and has already been
2980       // defined, copy the deduced value from the old declaration.
2981       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2982       if (OldAT && OldAT->isDeduced()) {
2983         New->setType(
2984             SubstAutoType(New->getType(),
2985                           OldAT->isDependentType() ? Context.DependentTy
2986                                                    : OldAT->getDeducedType()));
2987         NewQType = Context.getCanonicalType(
2988             SubstAutoType(NewQType,
2989                           OldAT->isDependentType() ? Context.DependentTy
2990                                                    : OldAT->getDeducedType()));
2991       }
2992     }
2993 
2994     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2995     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2996     if (OldMethod && NewMethod) {
2997       // Preserve triviality.
2998       NewMethod->setTrivial(OldMethod->isTrivial());
2999 
3000       // MSVC allows explicit template specialization at class scope:
3001       // 2 CXXMethodDecls referring to the same function will be injected.
3002       // We don't want a redeclaration error.
3003       bool IsClassScopeExplicitSpecialization =
3004                               OldMethod->isFunctionTemplateSpecialization() &&
3005                               NewMethod->isFunctionTemplateSpecialization();
3006       bool isFriend = NewMethod->getFriendObjectKind();
3007 
3008       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3009           !IsClassScopeExplicitSpecialization) {
3010         //    -- Member function declarations with the same name and the
3011         //       same parameter types cannot be overloaded if any of them
3012         //       is a static member function declaration.
3013         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3014           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3015           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3016           return true;
3017         }
3018 
3019         // C++ [class.mem]p1:
3020         //   [...] A member shall not be declared twice in the
3021         //   member-specification, except that a nested class or member
3022         //   class template can be declared and then later defined.
3023         if (ActiveTemplateInstantiations.empty()) {
3024           unsigned NewDiag;
3025           if (isa<CXXConstructorDecl>(OldMethod))
3026             NewDiag = diag::err_constructor_redeclared;
3027           else if (isa<CXXDestructorDecl>(NewMethod))
3028             NewDiag = diag::err_destructor_redeclared;
3029           else if (isa<CXXConversionDecl>(NewMethod))
3030             NewDiag = diag::err_conv_function_redeclared;
3031           else
3032             NewDiag = diag::err_member_redeclared;
3033 
3034           Diag(New->getLocation(), NewDiag);
3035         } else {
3036           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3037             << New << New->getType();
3038         }
3039         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3040         return true;
3041 
3042       // Complain if this is an explicit declaration of a special
3043       // member that was initially declared implicitly.
3044       //
3045       // As an exception, it's okay to befriend such methods in order
3046       // to permit the implicit constructor/destructor/operator calls.
3047       } else if (OldMethod->isImplicit()) {
3048         if (isFriend) {
3049           NewMethod->setImplicit();
3050         } else {
3051           Diag(NewMethod->getLocation(),
3052                diag::err_definition_of_implicitly_declared_member)
3053             << New << getSpecialMember(OldMethod);
3054           return true;
3055         }
3056       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3057         Diag(NewMethod->getLocation(),
3058              diag::err_definition_of_explicitly_defaulted_member)
3059           << getSpecialMember(OldMethod);
3060         return true;
3061       }
3062     }
3063 
3064     // C++11 [dcl.attr.noreturn]p1:
3065     //   The first declaration of a function shall specify the noreturn
3066     //   attribute if any declaration of that function specifies the noreturn
3067     //   attribute.
3068     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3069     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3070       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3071       Diag(Old->getFirstDecl()->getLocation(),
3072            diag::note_noreturn_missing_first_decl);
3073     }
3074 
3075     // C++11 [dcl.attr.depend]p2:
3076     //   The first declaration of a function shall specify the
3077     //   carries_dependency attribute for its declarator-id if any declaration
3078     //   of the function specifies the carries_dependency attribute.
3079     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3080     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3081       Diag(CDA->getLocation(),
3082            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3083       Diag(Old->getFirstDecl()->getLocation(),
3084            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3085     }
3086 
3087     // (C++98 8.3.5p3):
3088     //   All declarations for a function shall agree exactly in both the
3089     //   return type and the parameter-type-list.
3090     // We also want to respect all the extended bits except noreturn.
3091 
3092     // noreturn should now match unless the old type info didn't have it.
3093     QualType OldQTypeForComparison = OldQType;
3094     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3095       assert(OldQType == QualType(OldType, 0));
3096       const FunctionType *OldTypeForComparison
3097         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3098       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3099       assert(OldQTypeForComparison.isCanonical());
3100     }
3101 
3102     if (haveIncompatibleLanguageLinkages(Old, New)) {
3103       // As a special case, retain the language linkage from previous
3104       // declarations of a friend function as an extension.
3105       //
3106       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3107       // and is useful because there's otherwise no way to specify language
3108       // linkage within class scope.
3109       //
3110       // Check cautiously as the friend object kind isn't yet complete.
3111       if (New->getFriendObjectKind() != Decl::FOK_None) {
3112         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3113         Diag(OldLocation, PrevDiag);
3114       } else {
3115         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3116         Diag(OldLocation, PrevDiag);
3117         return true;
3118       }
3119     }
3120 
3121     if (OldQTypeForComparison == NewQType)
3122       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3123 
3124     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3125         New->isLocalExternDecl()) {
3126       // It's OK if we couldn't merge types for a local function declaraton
3127       // if either the old or new type is dependent. We'll merge the types
3128       // when we instantiate the function.
3129       return false;
3130     }
3131 
3132     // Fall through for conflicting redeclarations and redefinitions.
3133   }
3134 
3135   // C: Function types need to be compatible, not identical. This handles
3136   // duplicate function decls like "void f(int); void f(enum X);" properly.
3137   if (!getLangOpts().CPlusPlus &&
3138       Context.typesAreCompatible(OldQType, NewQType)) {
3139     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3140     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3141     const FunctionProtoType *OldProto = nullptr;
3142     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3143         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3144       // The old declaration provided a function prototype, but the
3145       // new declaration does not. Merge in the prototype.
3146       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3147       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3148       NewQType =
3149           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3150                                   OldProto->getExtProtoInfo());
3151       New->setType(NewQType);
3152       New->setHasInheritedPrototype();
3153 
3154       // Synthesize parameters with the same types.
3155       SmallVector<ParmVarDecl*, 16> Params;
3156       for (const auto &ParamType : OldProto->param_types()) {
3157         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3158                                                  SourceLocation(), nullptr,
3159                                                  ParamType, /*TInfo=*/nullptr,
3160                                                  SC_None, nullptr);
3161         Param->setScopeInfo(0, Params.size());
3162         Param->setImplicit();
3163         Params.push_back(Param);
3164       }
3165 
3166       New->setParams(Params);
3167     }
3168 
3169     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3170   }
3171 
3172   // GNU C permits a K&R definition to follow a prototype declaration
3173   // if the declared types of the parameters in the K&R definition
3174   // match the types in the prototype declaration, even when the
3175   // promoted types of the parameters from the K&R definition differ
3176   // from the types in the prototype. GCC then keeps the types from
3177   // the prototype.
3178   //
3179   // If a variadic prototype is followed by a non-variadic K&R definition,
3180   // the K&R definition becomes variadic.  This is sort of an edge case, but
3181   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3182   // C99 6.9.1p8.
3183   if (!getLangOpts().CPlusPlus &&
3184       Old->hasPrototype() && !New->hasPrototype() &&
3185       New->getType()->getAs<FunctionProtoType>() &&
3186       Old->getNumParams() == New->getNumParams()) {
3187     SmallVector<QualType, 16> ArgTypes;
3188     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3189     const FunctionProtoType *OldProto
3190       = Old->getType()->getAs<FunctionProtoType>();
3191     const FunctionProtoType *NewProto
3192       = New->getType()->getAs<FunctionProtoType>();
3193 
3194     // Determine whether this is the GNU C extension.
3195     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3196                                                NewProto->getReturnType());
3197     bool LooseCompatible = !MergedReturn.isNull();
3198     for (unsigned Idx = 0, End = Old->getNumParams();
3199          LooseCompatible && Idx != End; ++Idx) {
3200       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3201       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3202       if (Context.typesAreCompatible(OldParm->getType(),
3203                                      NewProto->getParamType(Idx))) {
3204         ArgTypes.push_back(NewParm->getType());
3205       } else if (Context.typesAreCompatible(OldParm->getType(),
3206                                             NewParm->getType(),
3207                                             /*CompareUnqualified=*/true)) {
3208         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3209                                            NewProto->getParamType(Idx) };
3210         Warnings.push_back(Warn);
3211         ArgTypes.push_back(NewParm->getType());
3212       } else
3213         LooseCompatible = false;
3214     }
3215 
3216     if (LooseCompatible) {
3217       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3218         Diag(Warnings[Warn].NewParm->getLocation(),
3219              diag::ext_param_promoted_not_compatible_with_prototype)
3220           << Warnings[Warn].PromotedType
3221           << Warnings[Warn].OldParm->getType();
3222         if (Warnings[Warn].OldParm->getLocation().isValid())
3223           Diag(Warnings[Warn].OldParm->getLocation(),
3224                diag::note_previous_declaration);
3225       }
3226 
3227       if (MergeTypeWithOld)
3228         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3229                                              OldProto->getExtProtoInfo()));
3230       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3231     }
3232 
3233     // Fall through to diagnose conflicting types.
3234   }
3235 
3236   // A function that has already been declared has been redeclared or
3237   // defined with a different type; show an appropriate diagnostic.
3238 
3239   // If the previous declaration was an implicitly-generated builtin
3240   // declaration, then at the very least we should use a specialized note.
3241   unsigned BuiltinID;
3242   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3243     // If it's actually a library-defined builtin function like 'malloc'
3244     // or 'printf', just warn about the incompatible redeclaration.
3245     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3246       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3247       Diag(OldLocation, diag::note_previous_builtin_declaration)
3248         << Old << Old->getType();
3249 
3250       // If this is a global redeclaration, just forget hereafter
3251       // about the "builtin-ness" of the function.
3252       //
3253       // Doing this for local extern declarations is problematic.  If
3254       // the builtin declaration remains visible, a second invalid
3255       // local declaration will produce a hard error; if it doesn't
3256       // remain visible, a single bogus local redeclaration (which is
3257       // actually only a warning) could break all the downstream code.
3258       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3259         New->getIdentifier()->revertBuiltin();
3260 
3261       return false;
3262     }
3263 
3264     PrevDiag = diag::note_previous_builtin_declaration;
3265   }
3266 
3267   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3268   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3269   return true;
3270 }
3271 
3272 /// \brief Completes the merge of two function declarations that are
3273 /// known to be compatible.
3274 ///
3275 /// This routine handles the merging of attributes and other
3276 /// properties of function declarations from the old declaration to
3277 /// the new declaration, once we know that New is in fact a
3278 /// redeclaration of Old.
3279 ///
3280 /// \returns false
3281 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3282                                         Scope *S, bool MergeTypeWithOld) {
3283   // Merge the attributes
3284   mergeDeclAttributes(New, Old);
3285 
3286   // Merge "pure" flag.
3287   if (Old->isPure())
3288     New->setPure();
3289 
3290   // Merge "used" flag.
3291   if (Old->getMostRecentDecl()->isUsed(false))
3292     New->setIsUsed();
3293 
3294   // Merge attributes from the parameters.  These can mismatch with K&R
3295   // declarations.
3296   if (New->getNumParams() == Old->getNumParams())
3297       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3298         ParmVarDecl *NewParam = New->getParamDecl(i);
3299         ParmVarDecl *OldParam = Old->getParamDecl(i);
3300         mergeParamDeclAttributes(NewParam, OldParam, *this);
3301         mergeParamDeclTypes(NewParam, OldParam, *this);
3302       }
3303 
3304   if (getLangOpts().CPlusPlus)
3305     return MergeCXXFunctionDecl(New, Old, S);
3306 
3307   // Merge the function types so the we get the composite types for the return
3308   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3309   // was visible.
3310   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3311   if (!Merged.isNull() && MergeTypeWithOld)
3312     New->setType(Merged);
3313 
3314   return false;
3315 }
3316 
3317 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3318                                 ObjCMethodDecl *oldMethod) {
3319   // Merge the attributes, including deprecated/unavailable
3320   AvailabilityMergeKind MergeKind =
3321     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3322       ? AMK_ProtocolImplementation
3323       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3324                                                        : AMK_Override;
3325 
3326   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3327 
3328   // Merge attributes from the parameters.
3329   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3330                                        oe = oldMethod->param_end();
3331   for (ObjCMethodDecl::param_iterator
3332          ni = newMethod->param_begin(), ne = newMethod->param_end();
3333        ni != ne && oi != oe; ++ni, ++oi)
3334     mergeParamDeclAttributes(*ni, *oi, *this);
3335 
3336   CheckObjCMethodOverride(newMethod, oldMethod);
3337 }
3338 
3339 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3340   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3341 
3342   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3343          ? diag::err_redefinition_different_type
3344          : diag::err_redeclaration_different_type)
3345     << New->getDeclName() << New->getType() << Old->getType();
3346 
3347   diag::kind PrevDiag;
3348   SourceLocation OldLocation;
3349   std::tie(PrevDiag, OldLocation)
3350     = getNoteDiagForInvalidRedeclaration(Old, New);
3351   S.Diag(OldLocation, PrevDiag);
3352   New->setInvalidDecl();
3353 }
3354 
3355 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3356 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3357 /// emitting diagnostics as appropriate.
3358 ///
3359 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3360 /// to here in AddInitializerToDecl. We can't check them before the initializer
3361 /// is attached.
3362 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3363                              bool MergeTypeWithOld) {
3364   if (New->isInvalidDecl() || Old->isInvalidDecl())
3365     return;
3366 
3367   QualType MergedT;
3368   if (getLangOpts().CPlusPlus) {
3369     if (New->getType()->isUndeducedType()) {
3370       // We don't know what the new type is until the initializer is attached.
3371       return;
3372     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3373       // These could still be something that needs exception specs checked.
3374       return MergeVarDeclExceptionSpecs(New, Old);
3375     }
3376     // C++ [basic.link]p10:
3377     //   [...] the types specified by all declarations referring to a given
3378     //   object or function shall be identical, except that declarations for an
3379     //   array object can specify array types that differ by the presence or
3380     //   absence of a major array bound (8.3.4).
3381     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3382       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3383       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3384 
3385       // We are merging a variable declaration New into Old. If it has an array
3386       // bound, and that bound differs from Old's bound, we should diagnose the
3387       // mismatch.
3388       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3389         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3390              PrevVD = PrevVD->getPreviousDecl()) {
3391           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3392           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3393             continue;
3394 
3395           if (!Context.hasSameType(NewArray, PrevVDTy))
3396             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3397         }
3398       }
3399 
3400       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3401         if (Context.hasSameType(OldArray->getElementType(),
3402                                 NewArray->getElementType()))
3403           MergedT = New->getType();
3404       }
3405       // FIXME: Check visibility. New is hidden but has a complete type. If New
3406       // has no array bound, it should not inherit one from Old, if Old is not
3407       // visible.
3408       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3409         if (Context.hasSameType(OldArray->getElementType(),
3410                                 NewArray->getElementType()))
3411           MergedT = Old->getType();
3412       }
3413     }
3414     else if (New->getType()->isObjCObjectPointerType() &&
3415                Old->getType()->isObjCObjectPointerType()) {
3416       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3417                                               Old->getType());
3418     }
3419   } else {
3420     // C 6.2.7p2:
3421     //   All declarations that refer to the same object or function shall have
3422     //   compatible type.
3423     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3424   }
3425   if (MergedT.isNull()) {
3426     // It's OK if we couldn't merge types if either type is dependent, for a
3427     // block-scope variable. In other cases (static data members of class
3428     // templates, variable templates, ...), we require the types to be
3429     // equivalent.
3430     // FIXME: The C++ standard doesn't say anything about this.
3431     if ((New->getType()->isDependentType() ||
3432          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3433       // If the old type was dependent, we can't merge with it, so the new type
3434       // becomes dependent for now. We'll reproduce the original type when we
3435       // instantiate the TypeSourceInfo for the variable.
3436       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3437         New->setType(Context.DependentTy);
3438       return;
3439     }
3440     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3441   }
3442 
3443   // Don't actually update the type on the new declaration if the old
3444   // declaration was an extern declaration in a different scope.
3445   if (MergeTypeWithOld)
3446     New->setType(MergedT);
3447 }
3448 
3449 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3450                                   LookupResult &Previous) {
3451   // C11 6.2.7p4:
3452   //   For an identifier with internal or external linkage declared
3453   //   in a scope in which a prior declaration of that identifier is
3454   //   visible, if the prior declaration specifies internal or
3455   //   external linkage, the type of the identifier at the later
3456   //   declaration becomes the composite type.
3457   //
3458   // If the variable isn't visible, we do not merge with its type.
3459   if (Previous.isShadowed())
3460     return false;
3461 
3462   if (S.getLangOpts().CPlusPlus) {
3463     // C++11 [dcl.array]p3:
3464     //   If there is a preceding declaration of the entity in the same
3465     //   scope in which the bound was specified, an omitted array bound
3466     //   is taken to be the same as in that earlier declaration.
3467     return NewVD->isPreviousDeclInSameBlockScope() ||
3468            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3469             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3470   } else {
3471     // If the old declaration was function-local, don't merge with its
3472     // type unless we're in the same function.
3473     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3474            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3475   }
3476 }
3477 
3478 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3479 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3480 /// situation, merging decls or emitting diagnostics as appropriate.
3481 ///
3482 /// Tentative definition rules (C99 6.9.2p2) are checked by
3483 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3484 /// definitions here, since the initializer hasn't been attached.
3485 ///
3486 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3487   // If the new decl is already invalid, don't do any other checking.
3488   if (New->isInvalidDecl())
3489     return;
3490 
3491   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3492     return;
3493 
3494   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3495 
3496   // Verify the old decl was also a variable or variable template.
3497   VarDecl *Old = nullptr;
3498   VarTemplateDecl *OldTemplate = nullptr;
3499   if (Previous.isSingleResult()) {
3500     if (NewTemplate) {
3501       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3502       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3503 
3504       if (auto *Shadow =
3505               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3506         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3507           return New->setInvalidDecl();
3508     } else {
3509       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3510 
3511       if (auto *Shadow =
3512               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3513         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3514           return New->setInvalidDecl();
3515     }
3516   }
3517   if (!Old) {
3518     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3519       << New->getDeclName();
3520     Diag(Previous.getRepresentativeDecl()->getLocation(),
3521          diag::note_previous_definition);
3522     return New->setInvalidDecl();
3523   }
3524 
3525   // Ensure the template parameters are compatible.
3526   if (NewTemplate &&
3527       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3528                                       OldTemplate->getTemplateParameters(),
3529                                       /*Complain=*/true, TPL_TemplateMatch))
3530     return New->setInvalidDecl();
3531 
3532   // C++ [class.mem]p1:
3533   //   A member shall not be declared twice in the member-specification [...]
3534   //
3535   // Here, we need only consider static data members.
3536   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3537     Diag(New->getLocation(), diag::err_duplicate_member)
3538       << New->getIdentifier();
3539     Diag(Old->getLocation(), diag::note_previous_declaration);
3540     New->setInvalidDecl();
3541   }
3542 
3543   mergeDeclAttributes(New, Old);
3544   // Warn if an already-declared variable is made a weak_import in a subsequent
3545   // declaration
3546   if (New->hasAttr<WeakImportAttr>() &&
3547       Old->getStorageClass() == SC_None &&
3548       !Old->hasAttr<WeakImportAttr>()) {
3549     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3550     Diag(Old->getLocation(), diag::note_previous_definition);
3551     // Remove weak_import attribute on new declaration.
3552     New->dropAttr<WeakImportAttr>();
3553   }
3554 
3555   if (New->hasAttr<InternalLinkageAttr>() &&
3556       !Old->hasAttr<InternalLinkageAttr>()) {
3557     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3558         << New->getDeclName();
3559     Diag(Old->getLocation(), diag::note_previous_definition);
3560     New->dropAttr<InternalLinkageAttr>();
3561   }
3562 
3563   // Merge the types.
3564   VarDecl *MostRecent = Old->getMostRecentDecl();
3565   if (MostRecent != Old) {
3566     MergeVarDeclTypes(New, MostRecent,
3567                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3568     if (New->isInvalidDecl())
3569       return;
3570   }
3571 
3572   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3573   if (New->isInvalidDecl())
3574     return;
3575 
3576   diag::kind PrevDiag;
3577   SourceLocation OldLocation;
3578   std::tie(PrevDiag, OldLocation) =
3579       getNoteDiagForInvalidRedeclaration(Old, New);
3580 
3581   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3582   if (New->getStorageClass() == SC_Static &&
3583       !New->isStaticDataMember() &&
3584       Old->hasExternalFormalLinkage()) {
3585     if (getLangOpts().MicrosoftExt) {
3586       Diag(New->getLocation(), diag::ext_static_non_static)
3587           << New->getDeclName();
3588       Diag(OldLocation, PrevDiag);
3589     } else {
3590       Diag(New->getLocation(), diag::err_static_non_static)
3591           << New->getDeclName();
3592       Diag(OldLocation, PrevDiag);
3593       return New->setInvalidDecl();
3594     }
3595   }
3596   // C99 6.2.2p4:
3597   //   For an identifier declared with the storage-class specifier
3598   //   extern in a scope in which a prior declaration of that
3599   //   identifier is visible,23) if the prior declaration specifies
3600   //   internal or external linkage, the linkage of the identifier at
3601   //   the later declaration is the same as the linkage specified at
3602   //   the prior declaration. If no prior declaration is visible, or
3603   //   if the prior declaration specifies no linkage, then the
3604   //   identifier has external linkage.
3605   if (New->hasExternalStorage() && Old->hasLinkage())
3606     /* Okay */;
3607   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3608            !New->isStaticDataMember() &&
3609            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3610     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3611     Diag(OldLocation, PrevDiag);
3612     return New->setInvalidDecl();
3613   }
3614 
3615   // Check if extern is followed by non-extern and vice-versa.
3616   if (New->hasExternalStorage() &&
3617       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3618     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3619     Diag(OldLocation, PrevDiag);
3620     return New->setInvalidDecl();
3621   }
3622   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3623       !New->hasExternalStorage()) {
3624     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3625     Diag(OldLocation, PrevDiag);
3626     return New->setInvalidDecl();
3627   }
3628 
3629   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3630 
3631   // FIXME: The test for external storage here seems wrong? We still
3632   // need to check for mismatches.
3633   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3634       // Don't complain about out-of-line definitions of static members.
3635       !(Old->getLexicalDeclContext()->isRecord() &&
3636         !New->getLexicalDeclContext()->isRecord())) {
3637     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3638     Diag(OldLocation, PrevDiag);
3639     return New->setInvalidDecl();
3640   }
3641 
3642   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3643     if (VarDecl *Def = Old->getDefinition()) {
3644       // C++1z [dcl.fcn.spec]p4:
3645       //   If the definition of a variable appears in a translation unit before
3646       //   its first declaration as inline, the program is ill-formed.
3647       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3648       Diag(Def->getLocation(), diag::note_previous_definition);
3649     }
3650   }
3651 
3652   // If this redeclaration makes the function inline, we may need to add it to
3653   // UndefinedButUsed.
3654   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3655       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3656     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3657                                            SourceLocation()));
3658 
3659   if (New->getTLSKind() != Old->getTLSKind()) {
3660     if (!Old->getTLSKind()) {
3661       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3662       Diag(OldLocation, PrevDiag);
3663     } else if (!New->getTLSKind()) {
3664       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3665       Diag(OldLocation, PrevDiag);
3666     } else {
3667       // Do not allow redeclaration to change the variable between requiring
3668       // static and dynamic initialization.
3669       // FIXME: GCC allows this, but uses the TLS keyword on the first
3670       // declaration to determine the kind. Do we need to be compatible here?
3671       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3672         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3673       Diag(OldLocation, PrevDiag);
3674     }
3675   }
3676 
3677   // C++ doesn't have tentative definitions, so go right ahead and check here.
3678   VarDecl *Def;
3679   if (getLangOpts().CPlusPlus &&
3680       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3681       (Def = Old->getDefinition())) {
3682     NamedDecl *Hidden = nullptr;
3683     if (!hasVisibleDefinition(Def, &Hidden) &&
3684         (New->getFormalLinkage() == InternalLinkage ||
3685          New->getDescribedVarTemplate() ||
3686          New->getNumTemplateParameterLists() ||
3687          New->getDeclContext()->isDependentContext())) {
3688       // The previous definition is hidden, and multiple definitions are
3689       // permitted (in separate TUs). Form another definition of it.
3690     } else if (Old->isStaticDataMember() &&
3691                Old->getCanonicalDecl()->isInline() &&
3692                Old->getCanonicalDecl()->isConstexpr()) {
3693       // This definition won't be a definition any more once it's been merged.
3694       Diag(New->getLocation(),
3695            diag::warn_deprecated_redundant_constexpr_static_def);
3696     } else {
3697       Diag(New->getLocation(), diag::err_redefinition) << New;
3698       Diag(Def->getLocation(), diag::note_previous_definition);
3699       New->setInvalidDecl();
3700       return;
3701     }
3702   }
3703 
3704   if (haveIncompatibleLanguageLinkages(Old, New)) {
3705     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3706     Diag(OldLocation, PrevDiag);
3707     New->setInvalidDecl();
3708     return;
3709   }
3710 
3711   // Merge "used" flag.
3712   if (Old->getMostRecentDecl()->isUsed(false))
3713     New->setIsUsed();
3714 
3715   // Keep a chain of previous declarations.
3716   New->setPreviousDecl(Old);
3717   if (NewTemplate)
3718     NewTemplate->setPreviousDecl(OldTemplate);
3719 
3720   // Inherit access appropriately.
3721   New->setAccess(Old->getAccess());
3722   if (NewTemplate)
3723     NewTemplate->setAccess(New->getAccess());
3724 
3725   if (Old->isInline())
3726     New->setImplicitlyInline();
3727 }
3728 
3729 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3730 /// no declarator (e.g. "struct foo;") is parsed.
3731 Decl *
3732 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3733                                  RecordDecl *&AnonRecord) {
3734   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3735                                     AnonRecord);
3736 }
3737 
3738 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3739 // disambiguate entities defined in different scopes.
3740 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3741 // compatibility.
3742 // We will pick our mangling number depending on which version of MSVC is being
3743 // targeted.
3744 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3745   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3746              ? S->getMSCurManglingNumber()
3747              : S->getMSLastManglingNumber();
3748 }
3749 
3750 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3751   if (!Context.getLangOpts().CPlusPlus)
3752     return;
3753 
3754   if (isa<CXXRecordDecl>(Tag->getParent())) {
3755     // If this tag is the direct child of a class, number it if
3756     // it is anonymous.
3757     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3758       return;
3759     MangleNumberingContext &MCtx =
3760         Context.getManglingNumberContext(Tag->getParent());
3761     Context.setManglingNumber(
3762         Tag, MCtx.getManglingNumber(
3763                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3764     return;
3765   }
3766 
3767   // If this tag isn't a direct child of a class, number it if it is local.
3768   Decl *ManglingContextDecl;
3769   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3770           Tag->getDeclContext(), ManglingContextDecl)) {
3771     Context.setManglingNumber(
3772         Tag, MCtx->getManglingNumber(
3773                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3774   }
3775 }
3776 
3777 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3778                                         TypedefNameDecl *NewTD) {
3779   if (TagFromDeclSpec->isInvalidDecl())
3780     return;
3781 
3782   // Do nothing if the tag already has a name for linkage purposes.
3783   if (TagFromDeclSpec->hasNameForLinkage())
3784     return;
3785 
3786   // A well-formed anonymous tag must always be a TUK_Definition.
3787   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3788 
3789   // The type must match the tag exactly;  no qualifiers allowed.
3790   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3791                            Context.getTagDeclType(TagFromDeclSpec))) {
3792     if (getLangOpts().CPlusPlus)
3793       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3794     return;
3795   }
3796 
3797   // If we've already computed linkage for the anonymous tag, then
3798   // adding a typedef name for the anonymous decl can change that
3799   // linkage, which might be a serious problem.  Diagnose this as
3800   // unsupported and ignore the typedef name.  TODO: we should
3801   // pursue this as a language defect and establish a formal rule
3802   // for how to handle it.
3803   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3804     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3805 
3806     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3807     tagLoc = getLocForEndOfToken(tagLoc);
3808 
3809     llvm::SmallString<40> textToInsert;
3810     textToInsert += ' ';
3811     textToInsert += NewTD->getIdentifier()->getName();
3812     Diag(tagLoc, diag::note_typedef_changes_linkage)
3813         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3814     return;
3815   }
3816 
3817   // Otherwise, set this is the anon-decl typedef for the tag.
3818   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3819 }
3820 
3821 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3822   switch (T) {
3823   case DeclSpec::TST_class:
3824     return 0;
3825   case DeclSpec::TST_struct:
3826     return 1;
3827   case DeclSpec::TST_interface:
3828     return 2;
3829   case DeclSpec::TST_union:
3830     return 3;
3831   case DeclSpec::TST_enum:
3832     return 4;
3833   default:
3834     llvm_unreachable("unexpected type specifier");
3835   }
3836 }
3837 
3838 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3839 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3840 /// parameters to cope with template friend declarations.
3841 Decl *
3842 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3843                                  MultiTemplateParamsArg TemplateParams,
3844                                  bool IsExplicitInstantiation,
3845                                  RecordDecl *&AnonRecord) {
3846   Decl *TagD = nullptr;
3847   TagDecl *Tag = nullptr;
3848   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3849       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3850       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3851       DS.getTypeSpecType() == DeclSpec::TST_union ||
3852       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3853     TagD = DS.getRepAsDecl();
3854 
3855     if (!TagD) // We probably had an error
3856       return nullptr;
3857 
3858     // Note that the above type specs guarantee that the
3859     // type rep is a Decl, whereas in many of the others
3860     // it's a Type.
3861     if (isa<TagDecl>(TagD))
3862       Tag = cast<TagDecl>(TagD);
3863     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3864       Tag = CTD->getTemplatedDecl();
3865   }
3866 
3867   if (Tag) {
3868     handleTagNumbering(Tag, S);
3869     Tag->setFreeStanding();
3870     if (Tag->isInvalidDecl())
3871       return Tag;
3872   }
3873 
3874   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3875     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3876     // or incomplete types shall not be restrict-qualified."
3877     if (TypeQuals & DeclSpec::TQ_restrict)
3878       Diag(DS.getRestrictSpecLoc(),
3879            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3880            << DS.getSourceRange();
3881   }
3882 
3883   if (DS.isInlineSpecified())
3884     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3885         << getLangOpts().CPlusPlus1z;
3886 
3887   if (DS.isConstexprSpecified()) {
3888     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3889     // and definitions of functions and variables.
3890     if (Tag)
3891       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3892           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3893     else
3894       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3895     // Don't emit warnings after this error.
3896     return TagD;
3897   }
3898 
3899   if (DS.isConceptSpecified()) {
3900     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3901     // either a function concept and its definition or a variable concept and
3902     // its initializer.
3903     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3904     return TagD;
3905   }
3906 
3907   DiagnoseFunctionSpecifiers(DS);
3908 
3909   if (DS.isFriendSpecified()) {
3910     // If we're dealing with a decl but not a TagDecl, assume that
3911     // whatever routines created it handled the friendship aspect.
3912     if (TagD && !Tag)
3913       return nullptr;
3914     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3915   }
3916 
3917   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3918   bool IsExplicitSpecialization =
3919     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3920   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3921       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3922       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3923     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3924     // nested-name-specifier unless it is an explicit instantiation
3925     // or an explicit specialization.
3926     //
3927     // FIXME: We allow class template partial specializations here too, per the
3928     // obvious intent of DR1819.
3929     //
3930     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3931     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3932         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3933     return nullptr;
3934   }
3935 
3936   // Track whether this decl-specifier declares anything.
3937   bool DeclaresAnything = true;
3938 
3939   // Handle anonymous struct definitions.
3940   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3941     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3942         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3943       if (getLangOpts().CPlusPlus ||
3944           Record->getDeclContext()->isRecord()) {
3945         // If CurContext is a DeclContext that can contain statements,
3946         // RecursiveASTVisitor won't visit the decls that
3947         // BuildAnonymousStructOrUnion() will put into CurContext.
3948         // Also store them here so that they can be part of the
3949         // DeclStmt that gets created in this case.
3950         // FIXME: Also return the IndirectFieldDecls created by
3951         // BuildAnonymousStructOr union, for the same reason?
3952         if (CurContext->isFunctionOrMethod())
3953           AnonRecord = Record;
3954         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3955                                            Context.getPrintingPolicy());
3956       }
3957 
3958       DeclaresAnything = false;
3959     }
3960   }
3961 
3962   // C11 6.7.2.1p2:
3963   //   A struct-declaration that does not declare an anonymous structure or
3964   //   anonymous union shall contain a struct-declarator-list.
3965   //
3966   // This rule also existed in C89 and C99; the grammar for struct-declaration
3967   // did not permit a struct-declaration without a struct-declarator-list.
3968   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3969       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3970     // Check for Microsoft C extension: anonymous struct/union member.
3971     // Handle 2 kinds of anonymous struct/union:
3972     //   struct STRUCT;
3973     //   union UNION;
3974     // and
3975     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3976     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3977     if ((Tag && Tag->getDeclName()) ||
3978         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3979       RecordDecl *Record = nullptr;
3980       if (Tag)
3981         Record = dyn_cast<RecordDecl>(Tag);
3982       else if (const RecordType *RT =
3983                    DS.getRepAsType().get()->getAsStructureType())
3984         Record = RT->getDecl();
3985       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3986         Record = UT->getDecl();
3987 
3988       if (Record && getLangOpts().MicrosoftExt) {
3989         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3990           << Record->isUnion() << DS.getSourceRange();
3991         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3992       }
3993 
3994       DeclaresAnything = false;
3995     }
3996   }
3997 
3998   // Skip all the checks below if we have a type error.
3999   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4000       (TagD && TagD->isInvalidDecl()))
4001     return TagD;
4002 
4003   if (getLangOpts().CPlusPlus &&
4004       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4005     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4006       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4007           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4008         DeclaresAnything = false;
4009 
4010   if (!DS.isMissingDeclaratorOk()) {
4011     // Customize diagnostic for a typedef missing a name.
4012     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4013       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4014         << DS.getSourceRange();
4015     else
4016       DeclaresAnything = false;
4017   }
4018 
4019   if (DS.isModulePrivateSpecified() &&
4020       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4021     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4022       << Tag->getTagKind()
4023       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4024 
4025   ActOnDocumentableDecl(TagD);
4026 
4027   // C 6.7/2:
4028   //   A declaration [...] shall declare at least a declarator [...], a tag,
4029   //   or the members of an enumeration.
4030   // C++ [dcl.dcl]p3:
4031   //   [If there are no declarators], and except for the declaration of an
4032   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4033   //   names into the program, or shall redeclare a name introduced by a
4034   //   previous declaration.
4035   if (!DeclaresAnything) {
4036     // In C, we allow this as a (popular) extension / bug. Don't bother
4037     // producing further diagnostics for redundant qualifiers after this.
4038     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4039     return TagD;
4040   }
4041 
4042   // C++ [dcl.stc]p1:
4043   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4044   //   init-declarator-list of the declaration shall not be empty.
4045   // C++ [dcl.fct.spec]p1:
4046   //   If a cv-qualifier appears in a decl-specifier-seq, the
4047   //   init-declarator-list of the declaration shall not be empty.
4048   //
4049   // Spurious qualifiers here appear to be valid in C.
4050   unsigned DiagID = diag::warn_standalone_specifier;
4051   if (getLangOpts().CPlusPlus)
4052     DiagID = diag::ext_standalone_specifier;
4053 
4054   // Note that a linkage-specification sets a storage class, but
4055   // 'extern "C" struct foo;' is actually valid and not theoretically
4056   // useless.
4057   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4058     if (SCS == DeclSpec::SCS_mutable)
4059       // Since mutable is not a viable storage class specifier in C, there is
4060       // no reason to treat it as an extension. Instead, diagnose as an error.
4061       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4062     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4063       Diag(DS.getStorageClassSpecLoc(), DiagID)
4064         << DeclSpec::getSpecifierName(SCS);
4065   }
4066 
4067   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4068     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4069       << DeclSpec::getSpecifierName(TSCS);
4070   if (DS.getTypeQualifiers()) {
4071     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4072       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4073     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4074       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4075     // Restrict is covered above.
4076     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4077       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4078     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4079       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4080   }
4081 
4082   // Warn about ignored type attributes, for example:
4083   // __attribute__((aligned)) struct A;
4084   // Attributes should be placed after tag to apply to type declaration.
4085   if (!DS.getAttributes().empty()) {
4086     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4087     if (TypeSpecType == DeclSpec::TST_class ||
4088         TypeSpecType == DeclSpec::TST_struct ||
4089         TypeSpecType == DeclSpec::TST_interface ||
4090         TypeSpecType == DeclSpec::TST_union ||
4091         TypeSpecType == DeclSpec::TST_enum) {
4092       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4093            attrs = attrs->getNext())
4094         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4095             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4096     }
4097   }
4098 
4099   return TagD;
4100 }
4101 
4102 /// We are trying to inject an anonymous member into the given scope;
4103 /// check if there's an existing declaration that can't be overloaded.
4104 ///
4105 /// \return true if this is a forbidden redeclaration
4106 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4107                                          Scope *S,
4108                                          DeclContext *Owner,
4109                                          DeclarationName Name,
4110                                          SourceLocation NameLoc,
4111                                          bool IsUnion) {
4112   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4113                  Sema::ForRedeclaration);
4114   if (!SemaRef.LookupName(R, S)) return false;
4115 
4116   // Pick a representative declaration.
4117   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4118   assert(PrevDecl && "Expected a non-null Decl");
4119 
4120   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4121     return false;
4122 
4123   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4124     << IsUnion << Name;
4125   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4126 
4127   return true;
4128 }
4129 
4130 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4131 /// anonymous struct or union AnonRecord into the owning context Owner
4132 /// and scope S. This routine will be invoked just after we realize
4133 /// that an unnamed union or struct is actually an anonymous union or
4134 /// struct, e.g.,
4135 ///
4136 /// @code
4137 /// union {
4138 ///   int i;
4139 ///   float f;
4140 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4141 ///    // f into the surrounding scope.x
4142 /// @endcode
4143 ///
4144 /// This routine is recursive, injecting the names of nested anonymous
4145 /// structs/unions into the owning context and scope as well.
4146 static bool
4147 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4148                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4149                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4150   bool Invalid = false;
4151 
4152   // Look every FieldDecl and IndirectFieldDecl with a name.
4153   for (auto *D : AnonRecord->decls()) {
4154     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4155         cast<NamedDecl>(D)->getDeclName()) {
4156       ValueDecl *VD = cast<ValueDecl>(D);
4157       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4158                                        VD->getLocation(),
4159                                        AnonRecord->isUnion())) {
4160         // C++ [class.union]p2:
4161         //   The names of the members of an anonymous union shall be
4162         //   distinct from the names of any other entity in the
4163         //   scope in which the anonymous union is declared.
4164         Invalid = true;
4165       } else {
4166         // C++ [class.union]p2:
4167         //   For the purpose of name lookup, after the anonymous union
4168         //   definition, the members of the anonymous union are
4169         //   considered to have been defined in the scope in which the
4170         //   anonymous union is declared.
4171         unsigned OldChainingSize = Chaining.size();
4172         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4173           Chaining.append(IF->chain_begin(), IF->chain_end());
4174         else
4175           Chaining.push_back(VD);
4176 
4177         assert(Chaining.size() >= 2);
4178         NamedDecl **NamedChain =
4179           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4180         for (unsigned i = 0; i < Chaining.size(); i++)
4181           NamedChain[i] = Chaining[i];
4182 
4183         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4184             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4185             VD->getType(), {NamedChain, Chaining.size()});
4186 
4187         for (const auto *Attr : VD->attrs())
4188           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4189 
4190         IndirectField->setAccess(AS);
4191         IndirectField->setImplicit();
4192         SemaRef.PushOnScopeChains(IndirectField, S);
4193 
4194         // That includes picking up the appropriate access specifier.
4195         if (AS != AS_none) IndirectField->setAccess(AS);
4196 
4197         Chaining.resize(OldChainingSize);
4198       }
4199     }
4200   }
4201 
4202   return Invalid;
4203 }
4204 
4205 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4206 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4207 /// illegal input values are mapped to SC_None.
4208 static StorageClass
4209 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4210   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4211   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4212          "Parser allowed 'typedef' as storage class VarDecl.");
4213   switch (StorageClassSpec) {
4214   case DeclSpec::SCS_unspecified:    return SC_None;
4215   case DeclSpec::SCS_extern:
4216     if (DS.isExternInLinkageSpec())
4217       return SC_None;
4218     return SC_Extern;
4219   case DeclSpec::SCS_static:         return SC_Static;
4220   case DeclSpec::SCS_auto:           return SC_Auto;
4221   case DeclSpec::SCS_register:       return SC_Register;
4222   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4223     // Illegal SCSs map to None: error reporting is up to the caller.
4224   case DeclSpec::SCS_mutable:        // Fall through.
4225   case DeclSpec::SCS_typedef:        return SC_None;
4226   }
4227   llvm_unreachable("unknown storage class specifier");
4228 }
4229 
4230 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4231   assert(Record->hasInClassInitializer());
4232 
4233   for (const auto *I : Record->decls()) {
4234     const auto *FD = dyn_cast<FieldDecl>(I);
4235     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4236       FD = IFD->getAnonField();
4237     if (FD && FD->hasInClassInitializer())
4238       return FD->getLocation();
4239   }
4240 
4241   llvm_unreachable("couldn't find in-class initializer");
4242 }
4243 
4244 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4245                                       SourceLocation DefaultInitLoc) {
4246   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4247     return;
4248 
4249   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4250   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4251 }
4252 
4253 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4254                                       CXXRecordDecl *AnonUnion) {
4255   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4256     return;
4257 
4258   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4259 }
4260 
4261 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4262 /// anonymous structure or union. Anonymous unions are a C++ feature
4263 /// (C++ [class.union]) and a C11 feature; anonymous structures
4264 /// are a C11 feature and GNU C++ extension.
4265 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4266                                         AccessSpecifier AS,
4267                                         RecordDecl *Record,
4268                                         const PrintingPolicy &Policy) {
4269   DeclContext *Owner = Record->getDeclContext();
4270 
4271   // Diagnose whether this anonymous struct/union is an extension.
4272   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4273     Diag(Record->getLocation(), diag::ext_anonymous_union);
4274   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4275     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4276   else if (!Record->isUnion() && !getLangOpts().C11)
4277     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4278 
4279   // C and C++ require different kinds of checks for anonymous
4280   // structs/unions.
4281   bool Invalid = false;
4282   if (getLangOpts().CPlusPlus) {
4283     const char *PrevSpec = nullptr;
4284     unsigned DiagID;
4285     if (Record->isUnion()) {
4286       // C++ [class.union]p6:
4287       //   Anonymous unions declared in a named namespace or in the
4288       //   global namespace shall be declared static.
4289       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4290           (isa<TranslationUnitDecl>(Owner) ||
4291            (isa<NamespaceDecl>(Owner) &&
4292             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4293         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4294           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4295 
4296         // Recover by adding 'static'.
4297         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4298                                PrevSpec, DiagID, Policy);
4299       }
4300       // C++ [class.union]p6:
4301       //   A storage class is not allowed in a declaration of an
4302       //   anonymous union in a class scope.
4303       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4304                isa<RecordDecl>(Owner)) {
4305         Diag(DS.getStorageClassSpecLoc(),
4306              diag::err_anonymous_union_with_storage_spec)
4307           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4308 
4309         // Recover by removing the storage specifier.
4310         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4311                                SourceLocation(),
4312                                PrevSpec, DiagID, Context.getPrintingPolicy());
4313       }
4314     }
4315 
4316     // Ignore const/volatile/restrict qualifiers.
4317     if (DS.getTypeQualifiers()) {
4318       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4319         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4320           << Record->isUnion() << "const"
4321           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4322       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4323         Diag(DS.getVolatileSpecLoc(),
4324              diag::ext_anonymous_struct_union_qualified)
4325           << Record->isUnion() << "volatile"
4326           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4327       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4328         Diag(DS.getRestrictSpecLoc(),
4329              diag::ext_anonymous_struct_union_qualified)
4330           << Record->isUnion() << "restrict"
4331           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4332       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4333         Diag(DS.getAtomicSpecLoc(),
4334              diag::ext_anonymous_struct_union_qualified)
4335           << Record->isUnion() << "_Atomic"
4336           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4337       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4338         Diag(DS.getUnalignedSpecLoc(),
4339              diag::ext_anonymous_struct_union_qualified)
4340           << Record->isUnion() << "__unaligned"
4341           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4342 
4343       DS.ClearTypeQualifiers();
4344     }
4345 
4346     // C++ [class.union]p2:
4347     //   The member-specification of an anonymous union shall only
4348     //   define non-static data members. [Note: nested types and
4349     //   functions cannot be declared within an anonymous union. ]
4350     for (auto *Mem : Record->decls()) {
4351       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4352         // C++ [class.union]p3:
4353         //   An anonymous union shall not have private or protected
4354         //   members (clause 11).
4355         assert(FD->getAccess() != AS_none);
4356         if (FD->getAccess() != AS_public) {
4357           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4358             << Record->isUnion() << (FD->getAccess() == AS_protected);
4359           Invalid = true;
4360         }
4361 
4362         // C++ [class.union]p1
4363         //   An object of a class with a non-trivial constructor, a non-trivial
4364         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4365         //   assignment operator cannot be a member of a union, nor can an
4366         //   array of such objects.
4367         if (CheckNontrivialField(FD))
4368           Invalid = true;
4369       } else if (Mem->isImplicit()) {
4370         // Any implicit members are fine.
4371       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4372         // This is a type that showed up in an
4373         // elaborated-type-specifier inside the anonymous struct or
4374         // union, but which actually declares a type outside of the
4375         // anonymous struct or union. It's okay.
4376       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4377         if (!MemRecord->isAnonymousStructOrUnion() &&
4378             MemRecord->getDeclName()) {
4379           // Visual C++ allows type definition in anonymous struct or union.
4380           if (getLangOpts().MicrosoftExt)
4381             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4382               << Record->isUnion();
4383           else {
4384             // This is a nested type declaration.
4385             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4386               << Record->isUnion();
4387             Invalid = true;
4388           }
4389         } else {
4390           // This is an anonymous type definition within another anonymous type.
4391           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4392           // not part of standard C++.
4393           Diag(MemRecord->getLocation(),
4394                diag::ext_anonymous_record_with_anonymous_type)
4395             << Record->isUnion();
4396         }
4397       } else if (isa<AccessSpecDecl>(Mem)) {
4398         // Any access specifier is fine.
4399       } else if (isa<StaticAssertDecl>(Mem)) {
4400         // In C++1z, static_assert declarations are also fine.
4401       } else {
4402         // We have something that isn't a non-static data
4403         // member. Complain about it.
4404         unsigned DK = diag::err_anonymous_record_bad_member;
4405         if (isa<TypeDecl>(Mem))
4406           DK = diag::err_anonymous_record_with_type;
4407         else if (isa<FunctionDecl>(Mem))
4408           DK = diag::err_anonymous_record_with_function;
4409         else if (isa<VarDecl>(Mem))
4410           DK = diag::err_anonymous_record_with_static;
4411 
4412         // Visual C++ allows type definition in anonymous struct or union.
4413         if (getLangOpts().MicrosoftExt &&
4414             DK == diag::err_anonymous_record_with_type)
4415           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4416             << Record->isUnion();
4417         else {
4418           Diag(Mem->getLocation(), DK) << Record->isUnion();
4419           Invalid = true;
4420         }
4421       }
4422     }
4423 
4424     // C++11 [class.union]p8 (DR1460):
4425     //   At most one variant member of a union may have a
4426     //   brace-or-equal-initializer.
4427     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4428         Owner->isRecord())
4429       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4430                                 cast<CXXRecordDecl>(Record));
4431   }
4432 
4433   if (!Record->isUnion() && !Owner->isRecord()) {
4434     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4435       << getLangOpts().CPlusPlus;
4436     Invalid = true;
4437   }
4438 
4439   // Mock up a declarator.
4440   Declarator Dc(DS, Declarator::MemberContext);
4441   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4442   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4443 
4444   // Create a declaration for this anonymous struct/union.
4445   NamedDecl *Anon = nullptr;
4446   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4447     Anon = FieldDecl::Create(Context, OwningClass,
4448                              DS.getLocStart(),
4449                              Record->getLocation(),
4450                              /*IdentifierInfo=*/nullptr,
4451                              Context.getTypeDeclType(Record),
4452                              TInfo,
4453                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4454                              /*InitStyle=*/ICIS_NoInit);
4455     Anon->setAccess(AS);
4456     if (getLangOpts().CPlusPlus)
4457       FieldCollector->Add(cast<FieldDecl>(Anon));
4458   } else {
4459     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4460     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4461     if (SCSpec == DeclSpec::SCS_mutable) {
4462       // mutable can only appear on non-static class members, so it's always
4463       // an error here
4464       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4465       Invalid = true;
4466       SC = SC_None;
4467     }
4468 
4469     Anon = VarDecl::Create(Context, Owner,
4470                            DS.getLocStart(),
4471                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4472                            Context.getTypeDeclType(Record),
4473                            TInfo, SC);
4474 
4475     // Default-initialize the implicit variable. This initialization will be
4476     // trivial in almost all cases, except if a union member has an in-class
4477     // initializer:
4478     //   union { int n = 0; };
4479     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4480   }
4481   Anon->setImplicit();
4482 
4483   // Mark this as an anonymous struct/union type.
4484   Record->setAnonymousStructOrUnion(true);
4485 
4486   // Add the anonymous struct/union object to the current
4487   // context. We'll be referencing this object when we refer to one of
4488   // its members.
4489   Owner->addDecl(Anon);
4490 
4491   // Inject the members of the anonymous struct/union into the owning
4492   // context and into the identifier resolver chain for name lookup
4493   // purposes.
4494   SmallVector<NamedDecl*, 2> Chain;
4495   Chain.push_back(Anon);
4496 
4497   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4498     Invalid = true;
4499 
4500   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4501     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4502       Decl *ManglingContextDecl;
4503       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4504               NewVD->getDeclContext(), ManglingContextDecl)) {
4505         Context.setManglingNumber(
4506             NewVD, MCtx->getManglingNumber(
4507                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4508         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4509       }
4510     }
4511   }
4512 
4513   if (Invalid)
4514     Anon->setInvalidDecl();
4515 
4516   return Anon;
4517 }
4518 
4519 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4520 /// Microsoft C anonymous structure.
4521 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4522 /// Example:
4523 ///
4524 /// struct A { int a; };
4525 /// struct B { struct A; int b; };
4526 ///
4527 /// void foo() {
4528 ///   B var;
4529 ///   var.a = 3;
4530 /// }
4531 ///
4532 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4533                                            RecordDecl *Record) {
4534   assert(Record && "expected a record!");
4535 
4536   // Mock up a declarator.
4537   Declarator Dc(DS, Declarator::TypeNameContext);
4538   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4539   assert(TInfo && "couldn't build declarator info for anonymous struct");
4540 
4541   auto *ParentDecl = cast<RecordDecl>(CurContext);
4542   QualType RecTy = Context.getTypeDeclType(Record);
4543 
4544   // Create a declaration for this anonymous struct.
4545   NamedDecl *Anon = FieldDecl::Create(Context,
4546                              ParentDecl,
4547                              DS.getLocStart(),
4548                              DS.getLocStart(),
4549                              /*IdentifierInfo=*/nullptr,
4550                              RecTy,
4551                              TInfo,
4552                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4553                              /*InitStyle=*/ICIS_NoInit);
4554   Anon->setImplicit();
4555 
4556   // Add the anonymous struct object to the current context.
4557   CurContext->addDecl(Anon);
4558 
4559   // Inject the members of the anonymous struct into the current
4560   // context and into the identifier resolver chain for name lookup
4561   // purposes.
4562   SmallVector<NamedDecl*, 2> Chain;
4563   Chain.push_back(Anon);
4564 
4565   RecordDecl *RecordDef = Record->getDefinition();
4566   if (RequireCompleteType(Anon->getLocation(), RecTy,
4567                           diag::err_field_incomplete) ||
4568       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4569                                           AS_none, Chain)) {
4570     Anon->setInvalidDecl();
4571     ParentDecl->setInvalidDecl();
4572   }
4573 
4574   return Anon;
4575 }
4576 
4577 /// GetNameForDeclarator - Determine the full declaration name for the
4578 /// given Declarator.
4579 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4580   return GetNameFromUnqualifiedId(D.getName());
4581 }
4582 
4583 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4584 DeclarationNameInfo
4585 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4586   DeclarationNameInfo NameInfo;
4587   NameInfo.setLoc(Name.StartLocation);
4588 
4589   switch (Name.getKind()) {
4590 
4591   case UnqualifiedId::IK_ImplicitSelfParam:
4592   case UnqualifiedId::IK_Identifier:
4593     NameInfo.setName(Name.Identifier);
4594     NameInfo.setLoc(Name.StartLocation);
4595     return NameInfo;
4596 
4597   case UnqualifiedId::IK_OperatorFunctionId:
4598     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4599                                            Name.OperatorFunctionId.Operator));
4600     NameInfo.setLoc(Name.StartLocation);
4601     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4602       = Name.OperatorFunctionId.SymbolLocations[0];
4603     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4604       = Name.EndLocation.getRawEncoding();
4605     return NameInfo;
4606 
4607   case UnqualifiedId::IK_LiteralOperatorId:
4608     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4609                                                            Name.Identifier));
4610     NameInfo.setLoc(Name.StartLocation);
4611     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4612     return NameInfo;
4613 
4614   case UnqualifiedId::IK_ConversionFunctionId: {
4615     TypeSourceInfo *TInfo;
4616     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4617     if (Ty.isNull())
4618       return DeclarationNameInfo();
4619     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4620                                                Context.getCanonicalType(Ty)));
4621     NameInfo.setLoc(Name.StartLocation);
4622     NameInfo.setNamedTypeInfo(TInfo);
4623     return NameInfo;
4624   }
4625 
4626   case UnqualifiedId::IK_ConstructorName: {
4627     TypeSourceInfo *TInfo;
4628     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4629     if (Ty.isNull())
4630       return DeclarationNameInfo();
4631     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4632                                               Context.getCanonicalType(Ty)));
4633     NameInfo.setLoc(Name.StartLocation);
4634     NameInfo.setNamedTypeInfo(TInfo);
4635     return NameInfo;
4636   }
4637 
4638   case UnqualifiedId::IK_ConstructorTemplateId: {
4639     // In well-formed code, we can only have a constructor
4640     // template-id that refers to the current context, so go there
4641     // to find the actual type being constructed.
4642     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4643     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4644       return DeclarationNameInfo();
4645 
4646     // Determine the type of the class being constructed.
4647     QualType CurClassType = Context.getTypeDeclType(CurClass);
4648 
4649     // FIXME: Check two things: that the template-id names the same type as
4650     // CurClassType, and that the template-id does not occur when the name
4651     // was qualified.
4652 
4653     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4654                                     Context.getCanonicalType(CurClassType)));
4655     NameInfo.setLoc(Name.StartLocation);
4656     // FIXME: should we retrieve TypeSourceInfo?
4657     NameInfo.setNamedTypeInfo(nullptr);
4658     return NameInfo;
4659   }
4660 
4661   case UnqualifiedId::IK_DestructorName: {
4662     TypeSourceInfo *TInfo;
4663     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4664     if (Ty.isNull())
4665       return DeclarationNameInfo();
4666     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4667                                               Context.getCanonicalType(Ty)));
4668     NameInfo.setLoc(Name.StartLocation);
4669     NameInfo.setNamedTypeInfo(TInfo);
4670     return NameInfo;
4671   }
4672 
4673   case UnqualifiedId::IK_TemplateId: {
4674     TemplateName TName = Name.TemplateId->Template.get();
4675     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4676     return Context.getNameForTemplate(TName, TNameLoc);
4677   }
4678 
4679   } // switch (Name.getKind())
4680 
4681   llvm_unreachable("Unknown name kind");
4682 }
4683 
4684 static QualType getCoreType(QualType Ty) {
4685   do {
4686     if (Ty->isPointerType() || Ty->isReferenceType())
4687       Ty = Ty->getPointeeType();
4688     else if (Ty->isArrayType())
4689       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4690     else
4691       return Ty.withoutLocalFastQualifiers();
4692   } while (true);
4693 }
4694 
4695 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4696 /// and Definition have "nearly" matching parameters. This heuristic is
4697 /// used to improve diagnostics in the case where an out-of-line function
4698 /// definition doesn't match any declaration within the class or namespace.
4699 /// Also sets Params to the list of indices to the parameters that differ
4700 /// between the declaration and the definition. If hasSimilarParameters
4701 /// returns true and Params is empty, then all of the parameters match.
4702 static bool hasSimilarParameters(ASTContext &Context,
4703                                      FunctionDecl *Declaration,
4704                                      FunctionDecl *Definition,
4705                                      SmallVectorImpl<unsigned> &Params) {
4706   Params.clear();
4707   if (Declaration->param_size() != Definition->param_size())
4708     return false;
4709   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4710     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4711     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4712 
4713     // The parameter types are identical
4714     if (Context.hasSameType(DefParamTy, DeclParamTy))
4715       continue;
4716 
4717     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4718     QualType DefParamBaseTy = getCoreType(DefParamTy);
4719     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4720     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4721 
4722     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4723         (DeclTyName && DeclTyName == DefTyName))
4724       Params.push_back(Idx);
4725     else  // The two parameters aren't even close
4726       return false;
4727   }
4728 
4729   return true;
4730 }
4731 
4732 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4733 /// declarator needs to be rebuilt in the current instantiation.
4734 /// Any bits of declarator which appear before the name are valid for
4735 /// consideration here.  That's specifically the type in the decl spec
4736 /// and the base type in any member-pointer chunks.
4737 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4738                                                     DeclarationName Name) {
4739   // The types we specifically need to rebuild are:
4740   //   - typenames, typeofs, and decltypes
4741   //   - types which will become injected class names
4742   // Of course, we also need to rebuild any type referencing such a
4743   // type.  It's safest to just say "dependent", but we call out a
4744   // few cases here.
4745 
4746   DeclSpec &DS = D.getMutableDeclSpec();
4747   switch (DS.getTypeSpecType()) {
4748   case DeclSpec::TST_typename:
4749   case DeclSpec::TST_typeofType:
4750   case DeclSpec::TST_underlyingType:
4751   case DeclSpec::TST_atomic: {
4752     // Grab the type from the parser.
4753     TypeSourceInfo *TSI = nullptr;
4754     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4755     if (T.isNull() || !T->isDependentType()) break;
4756 
4757     // Make sure there's a type source info.  This isn't really much
4758     // of a waste; most dependent types should have type source info
4759     // attached already.
4760     if (!TSI)
4761       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4762 
4763     // Rebuild the type in the current instantiation.
4764     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4765     if (!TSI) return true;
4766 
4767     // Store the new type back in the decl spec.
4768     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4769     DS.UpdateTypeRep(LocType);
4770     break;
4771   }
4772 
4773   case DeclSpec::TST_decltype:
4774   case DeclSpec::TST_typeofExpr: {
4775     Expr *E = DS.getRepAsExpr();
4776     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4777     if (Result.isInvalid()) return true;
4778     DS.UpdateExprRep(Result.get());
4779     break;
4780   }
4781 
4782   default:
4783     // Nothing to do for these decl specs.
4784     break;
4785   }
4786 
4787   // It doesn't matter what order we do this in.
4788   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4789     DeclaratorChunk &Chunk = D.getTypeObject(I);
4790 
4791     // The only type information in the declarator which can come
4792     // before the declaration name is the base type of a member
4793     // pointer.
4794     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4795       continue;
4796 
4797     // Rebuild the scope specifier in-place.
4798     CXXScopeSpec &SS = Chunk.Mem.Scope();
4799     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4800       return true;
4801   }
4802 
4803   return false;
4804 }
4805 
4806 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4807   D.setFunctionDefinitionKind(FDK_Declaration);
4808   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4809 
4810   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4811       Dcl && Dcl->getDeclContext()->isFileContext())
4812     Dcl->setTopLevelDeclInObjCContainer();
4813 
4814   return Dcl;
4815 }
4816 
4817 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4818 ///   If T is the name of a class, then each of the following shall have a
4819 ///   name different from T:
4820 ///     - every static data member of class T;
4821 ///     - every member function of class T
4822 ///     - every member of class T that is itself a type;
4823 /// \returns true if the declaration name violates these rules.
4824 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4825                                    DeclarationNameInfo NameInfo) {
4826   DeclarationName Name = NameInfo.getName();
4827 
4828   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4829   while (Record && Record->isAnonymousStructOrUnion())
4830     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4831   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4832     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4833     return true;
4834   }
4835 
4836   return false;
4837 }
4838 
4839 /// \brief Diagnose a declaration whose declarator-id has the given
4840 /// nested-name-specifier.
4841 ///
4842 /// \param SS The nested-name-specifier of the declarator-id.
4843 ///
4844 /// \param DC The declaration context to which the nested-name-specifier
4845 /// resolves.
4846 ///
4847 /// \param Name The name of the entity being declared.
4848 ///
4849 /// \param Loc The location of the name of the entity being declared.
4850 ///
4851 /// \returns true if we cannot safely recover from this error, false otherwise.
4852 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4853                                         DeclarationName Name,
4854                                         SourceLocation Loc) {
4855   DeclContext *Cur = CurContext;
4856   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4857     Cur = Cur->getParent();
4858 
4859   // If the user provided a superfluous scope specifier that refers back to the
4860   // class in which the entity is already declared, diagnose and ignore it.
4861   //
4862   // class X {
4863   //   void X::f();
4864   // };
4865   //
4866   // Note, it was once ill-formed to give redundant qualification in all
4867   // contexts, but that rule was removed by DR482.
4868   if (Cur->Equals(DC)) {
4869     if (Cur->isRecord()) {
4870       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4871                                       : diag::err_member_extra_qualification)
4872         << Name << FixItHint::CreateRemoval(SS.getRange());
4873       SS.clear();
4874     } else {
4875       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4876     }
4877     return false;
4878   }
4879 
4880   // Check whether the qualifying scope encloses the scope of the original
4881   // declaration.
4882   if (!Cur->Encloses(DC)) {
4883     if (Cur->isRecord())
4884       Diag(Loc, diag::err_member_qualification)
4885         << Name << SS.getRange();
4886     else if (isa<TranslationUnitDecl>(DC))
4887       Diag(Loc, diag::err_invalid_declarator_global_scope)
4888         << Name << SS.getRange();
4889     else if (isa<FunctionDecl>(Cur))
4890       Diag(Loc, diag::err_invalid_declarator_in_function)
4891         << Name << SS.getRange();
4892     else if (isa<BlockDecl>(Cur))
4893       Diag(Loc, diag::err_invalid_declarator_in_block)
4894         << Name << SS.getRange();
4895     else
4896       Diag(Loc, diag::err_invalid_declarator_scope)
4897       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4898 
4899     return true;
4900   }
4901 
4902   if (Cur->isRecord()) {
4903     // Cannot qualify members within a class.
4904     Diag(Loc, diag::err_member_qualification)
4905       << Name << SS.getRange();
4906     SS.clear();
4907 
4908     // C++ constructors and destructors with incorrect scopes can break
4909     // our AST invariants by having the wrong underlying types. If
4910     // that's the case, then drop this declaration entirely.
4911     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4912          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4913         !Context.hasSameType(Name.getCXXNameType(),
4914                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4915       return true;
4916 
4917     return false;
4918   }
4919 
4920   // C++11 [dcl.meaning]p1:
4921   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4922   //   not begin with a decltype-specifer"
4923   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4924   while (SpecLoc.getPrefix())
4925     SpecLoc = SpecLoc.getPrefix();
4926   if (dyn_cast_or_null<DecltypeType>(
4927         SpecLoc.getNestedNameSpecifier()->getAsType()))
4928     Diag(Loc, diag::err_decltype_in_declarator)
4929       << SpecLoc.getTypeLoc().getSourceRange();
4930 
4931   return false;
4932 }
4933 
4934 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4935                                   MultiTemplateParamsArg TemplateParamLists) {
4936   // TODO: consider using NameInfo for diagnostic.
4937   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4938   DeclarationName Name = NameInfo.getName();
4939 
4940   // All of these full declarators require an identifier.  If it doesn't have
4941   // one, the ParsedFreeStandingDeclSpec action should be used.
4942   if (D.isDecompositionDeclarator()) {
4943     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
4944   } else if (!Name) {
4945     if (!D.isInvalidType())  // Reject this if we think it is valid.
4946       Diag(D.getDeclSpec().getLocStart(),
4947            diag::err_declarator_need_ident)
4948         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4949     return nullptr;
4950   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4951     return nullptr;
4952 
4953   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4954   // we find one that is.
4955   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4956          (S->getFlags() & Scope::TemplateParamScope) != 0)
4957     S = S->getParent();
4958 
4959   DeclContext *DC = CurContext;
4960   if (D.getCXXScopeSpec().isInvalid())
4961     D.setInvalidType();
4962   else if (D.getCXXScopeSpec().isSet()) {
4963     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4964                                         UPPC_DeclarationQualifier))
4965       return nullptr;
4966 
4967     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4968     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4969     if (!DC || isa<EnumDecl>(DC)) {
4970       // If we could not compute the declaration context, it's because the
4971       // declaration context is dependent but does not refer to a class,
4972       // class template, or class template partial specialization. Complain
4973       // and return early, to avoid the coming semantic disaster.
4974       Diag(D.getIdentifierLoc(),
4975            diag::err_template_qualified_declarator_no_match)
4976         << D.getCXXScopeSpec().getScopeRep()
4977         << D.getCXXScopeSpec().getRange();
4978       return nullptr;
4979     }
4980     bool IsDependentContext = DC->isDependentContext();
4981 
4982     if (!IsDependentContext &&
4983         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4984       return nullptr;
4985 
4986     // If a class is incomplete, do not parse entities inside it.
4987     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4988       Diag(D.getIdentifierLoc(),
4989            diag::err_member_def_undefined_record)
4990         << Name << DC << D.getCXXScopeSpec().getRange();
4991       return nullptr;
4992     }
4993     if (!D.getDeclSpec().isFriendSpecified()) {
4994       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4995                                       Name, D.getIdentifierLoc())) {
4996         if (DC->isRecord())
4997           return nullptr;
4998 
4999         D.setInvalidType();
5000       }
5001     }
5002 
5003     // Check whether we need to rebuild the type of the given
5004     // declaration in the current instantiation.
5005     if (EnteringContext && IsDependentContext &&
5006         TemplateParamLists.size() != 0) {
5007       ContextRAII SavedContext(*this, DC);
5008       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5009         D.setInvalidType();
5010     }
5011   }
5012 
5013   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5014   QualType R = TInfo->getType();
5015 
5016   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5017     // If this is a typedef, we'll end up spewing multiple diagnostics.
5018     // Just return early; it's safer. If this is a function, let the
5019     // "constructor cannot have a return type" diagnostic handle it.
5020     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5021       return nullptr;
5022 
5023   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5024                                       UPPC_DeclarationType))
5025     D.setInvalidType();
5026 
5027   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5028                         ForRedeclaration);
5029 
5030   // See if this is a redefinition of a variable in the same scope.
5031   if (!D.getCXXScopeSpec().isSet()) {
5032     bool IsLinkageLookup = false;
5033     bool CreateBuiltins = false;
5034 
5035     // If the declaration we're planning to build will be a function
5036     // or object with linkage, then look for another declaration with
5037     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5038     //
5039     // If the declaration we're planning to build will be declared with
5040     // external linkage in the translation unit, create any builtin with
5041     // the same name.
5042     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5043       /* Do nothing*/;
5044     else if (CurContext->isFunctionOrMethod() &&
5045              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5046               R->isFunctionType())) {
5047       IsLinkageLookup = true;
5048       CreateBuiltins =
5049           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5050     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5051                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5052       CreateBuiltins = true;
5053 
5054     if (IsLinkageLookup)
5055       Previous.clear(LookupRedeclarationWithLinkage);
5056 
5057     LookupName(Previous, S, CreateBuiltins);
5058   } else { // Something like "int foo::x;"
5059     LookupQualifiedName(Previous, DC);
5060 
5061     // C++ [dcl.meaning]p1:
5062     //   When the declarator-id is qualified, the declaration shall refer to a
5063     //  previously declared member of the class or namespace to which the
5064     //  qualifier refers (or, in the case of a namespace, of an element of the
5065     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5066     //  thereof; [...]
5067     //
5068     // Note that we already checked the context above, and that we do not have
5069     // enough information to make sure that Previous contains the declaration
5070     // we want to match. For example, given:
5071     //
5072     //   class X {
5073     //     void f();
5074     //     void f(float);
5075     //   };
5076     //
5077     //   void X::f(int) { } // ill-formed
5078     //
5079     // In this case, Previous will point to the overload set
5080     // containing the two f's declared in X, but neither of them
5081     // matches.
5082 
5083     // C++ [dcl.meaning]p1:
5084     //   [...] the member shall not merely have been introduced by a
5085     //   using-declaration in the scope of the class or namespace nominated by
5086     //   the nested-name-specifier of the declarator-id.
5087     RemoveUsingDecls(Previous);
5088   }
5089 
5090   if (Previous.isSingleResult() &&
5091       Previous.getFoundDecl()->isTemplateParameter()) {
5092     // Maybe we will complain about the shadowed template parameter.
5093     if (!D.isInvalidType())
5094       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5095                                       Previous.getFoundDecl());
5096 
5097     // Just pretend that we didn't see the previous declaration.
5098     Previous.clear();
5099   }
5100 
5101   // In C++, the previous declaration we find might be a tag type
5102   // (class or enum). In this case, the new declaration will hide the
5103   // tag type. Note that this does does not apply if we're declaring a
5104   // typedef (C++ [dcl.typedef]p4).
5105   if (Previous.isSingleTagDecl() &&
5106       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5107     Previous.clear();
5108 
5109   // Check that there are no default arguments other than in the parameters
5110   // of a function declaration (C++ only).
5111   if (getLangOpts().CPlusPlus)
5112     CheckExtraCXXDefaultArguments(D);
5113 
5114   if (D.getDeclSpec().isConceptSpecified()) {
5115     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5116     // applied only to the definition of a function template or variable
5117     // template, declared in namespace scope
5118     if (!TemplateParamLists.size()) {
5119       Diag(D.getDeclSpec().getConceptSpecLoc(),
5120            diag:: err_concept_wrong_decl_kind);
5121       return nullptr;
5122     }
5123 
5124     if (!DC->getRedeclContext()->isFileContext()) {
5125       Diag(D.getIdentifierLoc(),
5126            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5127       return nullptr;
5128     }
5129   }
5130 
5131   NamedDecl *New;
5132 
5133   bool AddToScope = true;
5134   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5135     if (TemplateParamLists.size()) {
5136       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5137       return nullptr;
5138     }
5139 
5140     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5141   } else if (R->isFunctionType()) {
5142     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5143                                   TemplateParamLists,
5144                                   AddToScope);
5145   } else {
5146     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5147                                   AddToScope);
5148   }
5149 
5150   if (!New)
5151     return nullptr;
5152 
5153   // If this has an identifier and is not a function template specialization,
5154   // add it to the scope stack.
5155   if (New->getDeclName() && AddToScope) {
5156     // Only make a locally-scoped extern declaration visible if it is the first
5157     // declaration of this entity. Qualified lookup for such an entity should
5158     // only find this declaration if there is no visible declaration of it.
5159     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5160     PushOnScopeChains(New, S, AddToContext);
5161     if (!AddToContext)
5162       CurContext->addHiddenDecl(New);
5163   }
5164 
5165   if (isInOpenMPDeclareTargetContext())
5166     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5167 
5168   return New;
5169 }
5170 
5171 /// Helper method to turn variable array types into constant array
5172 /// types in certain situations which would otherwise be errors (for
5173 /// GCC compatibility).
5174 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5175                                                     ASTContext &Context,
5176                                                     bool &SizeIsNegative,
5177                                                     llvm::APSInt &Oversized) {
5178   // This method tries to turn a variable array into a constant
5179   // array even when the size isn't an ICE.  This is necessary
5180   // for compatibility with code that depends on gcc's buggy
5181   // constant expression folding, like struct {char x[(int)(char*)2];}
5182   SizeIsNegative = false;
5183   Oversized = 0;
5184 
5185   if (T->isDependentType())
5186     return QualType();
5187 
5188   QualifierCollector Qs;
5189   const Type *Ty = Qs.strip(T);
5190 
5191   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5192     QualType Pointee = PTy->getPointeeType();
5193     QualType FixedType =
5194         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5195                                             Oversized);
5196     if (FixedType.isNull()) return FixedType;
5197     FixedType = Context.getPointerType(FixedType);
5198     return Qs.apply(Context, FixedType);
5199   }
5200   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5201     QualType Inner = PTy->getInnerType();
5202     QualType FixedType =
5203         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5204                                             Oversized);
5205     if (FixedType.isNull()) return FixedType;
5206     FixedType = Context.getParenType(FixedType);
5207     return Qs.apply(Context, FixedType);
5208   }
5209 
5210   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5211   if (!VLATy)
5212     return QualType();
5213   // FIXME: We should probably handle this case
5214   if (VLATy->getElementType()->isVariablyModifiedType())
5215     return QualType();
5216 
5217   llvm::APSInt Res;
5218   if (!VLATy->getSizeExpr() ||
5219       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5220     return QualType();
5221 
5222   // Check whether the array size is negative.
5223   if (Res.isSigned() && Res.isNegative()) {
5224     SizeIsNegative = true;
5225     return QualType();
5226   }
5227 
5228   // Check whether the array is too large to be addressed.
5229   unsigned ActiveSizeBits
5230     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5231                                               Res);
5232   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5233     Oversized = Res;
5234     return QualType();
5235   }
5236 
5237   return Context.getConstantArrayType(VLATy->getElementType(),
5238                                       Res, ArrayType::Normal, 0);
5239 }
5240 
5241 static void
5242 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5243   SrcTL = SrcTL.getUnqualifiedLoc();
5244   DstTL = DstTL.getUnqualifiedLoc();
5245   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5246     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5247     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5248                                       DstPTL.getPointeeLoc());
5249     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5250     return;
5251   }
5252   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5253     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5254     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5255                                       DstPTL.getInnerLoc());
5256     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5257     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5258     return;
5259   }
5260   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5261   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5262   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5263   TypeLoc DstElemTL = DstATL.getElementLoc();
5264   DstElemTL.initializeFullCopy(SrcElemTL);
5265   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5266   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5267   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5268 }
5269 
5270 /// Helper method to turn variable array types into constant array
5271 /// types in certain situations which would otherwise be errors (for
5272 /// GCC compatibility).
5273 static TypeSourceInfo*
5274 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5275                                               ASTContext &Context,
5276                                               bool &SizeIsNegative,
5277                                               llvm::APSInt &Oversized) {
5278   QualType FixedTy
5279     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5280                                           SizeIsNegative, Oversized);
5281   if (FixedTy.isNull())
5282     return nullptr;
5283   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5284   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5285                                     FixedTInfo->getTypeLoc());
5286   return FixedTInfo;
5287 }
5288 
5289 /// \brief Register the given locally-scoped extern "C" declaration so
5290 /// that it can be found later for redeclarations. We include any extern "C"
5291 /// declaration that is not visible in the translation unit here, not just
5292 /// function-scope declarations.
5293 void
5294 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5295   if (!getLangOpts().CPlusPlus &&
5296       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5297     // Don't need to track declarations in the TU in C.
5298     return;
5299 
5300   // Note that we have a locally-scoped external with this name.
5301   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5302 }
5303 
5304 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5305   // FIXME: We can have multiple results via __attribute__((overloadable)).
5306   auto Result = Context.getExternCContextDecl()->lookup(Name);
5307   return Result.empty() ? nullptr : *Result.begin();
5308 }
5309 
5310 /// \brief Diagnose function specifiers on a declaration of an identifier that
5311 /// does not identify a function.
5312 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5313   // FIXME: We should probably indicate the identifier in question to avoid
5314   // confusion for constructs like "virtual int a(), b;"
5315   if (DS.isVirtualSpecified())
5316     Diag(DS.getVirtualSpecLoc(),
5317          diag::err_virtual_non_function);
5318 
5319   if (DS.isExplicitSpecified())
5320     Diag(DS.getExplicitSpecLoc(),
5321          diag::err_explicit_non_function);
5322 
5323   if (DS.isNoreturnSpecified())
5324     Diag(DS.getNoreturnSpecLoc(),
5325          diag::err_noreturn_non_function);
5326 }
5327 
5328 NamedDecl*
5329 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5330                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5331   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5332   if (D.getCXXScopeSpec().isSet()) {
5333     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5334       << D.getCXXScopeSpec().getRange();
5335     D.setInvalidType();
5336     // Pretend we didn't see the scope specifier.
5337     DC = CurContext;
5338     Previous.clear();
5339   }
5340 
5341   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5342 
5343   if (D.getDeclSpec().isInlineSpecified())
5344     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5345         << getLangOpts().CPlusPlus1z;
5346   if (D.getDeclSpec().isConstexprSpecified())
5347     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5348       << 1;
5349   if (D.getDeclSpec().isConceptSpecified())
5350     Diag(D.getDeclSpec().getConceptSpecLoc(),
5351          diag::err_concept_wrong_decl_kind);
5352 
5353   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5354     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5355       << D.getName().getSourceRange();
5356     return nullptr;
5357   }
5358 
5359   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5360   if (!NewTD) return nullptr;
5361 
5362   // Handle attributes prior to checking for duplicates in MergeVarDecl
5363   ProcessDeclAttributes(S, NewTD, D);
5364 
5365   CheckTypedefForVariablyModifiedType(S, NewTD);
5366 
5367   bool Redeclaration = D.isRedeclaration();
5368   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5369   D.setRedeclaration(Redeclaration);
5370   return ND;
5371 }
5372 
5373 void
5374 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5375   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5376   // then it shall have block scope.
5377   // Note that variably modified types must be fixed before merging the decl so
5378   // that redeclarations will match.
5379   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5380   QualType T = TInfo->getType();
5381   if (T->isVariablyModifiedType()) {
5382     getCurFunction()->setHasBranchProtectedScope();
5383 
5384     if (S->getFnParent() == nullptr) {
5385       bool SizeIsNegative;
5386       llvm::APSInt Oversized;
5387       TypeSourceInfo *FixedTInfo =
5388         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5389                                                       SizeIsNegative,
5390                                                       Oversized);
5391       if (FixedTInfo) {
5392         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5393         NewTD->setTypeSourceInfo(FixedTInfo);
5394       } else {
5395         if (SizeIsNegative)
5396           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5397         else if (T->isVariableArrayType())
5398           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5399         else if (Oversized.getBoolValue())
5400           Diag(NewTD->getLocation(), diag::err_array_too_large)
5401             << Oversized.toString(10);
5402         else
5403           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5404         NewTD->setInvalidDecl();
5405       }
5406     }
5407   }
5408 }
5409 
5410 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5411 /// declares a typedef-name, either using the 'typedef' type specifier or via
5412 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5413 NamedDecl*
5414 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5415                            LookupResult &Previous, bool &Redeclaration) {
5416   // Merge the decl with the existing one if appropriate. If the decl is
5417   // in an outer scope, it isn't the same thing.
5418   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5419                        /*AllowInlineNamespace*/false);
5420   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5421   if (!Previous.empty()) {
5422     Redeclaration = true;
5423     MergeTypedefNameDecl(S, NewTD, Previous);
5424   }
5425 
5426   // If this is the C FILE type, notify the AST context.
5427   if (IdentifierInfo *II = NewTD->getIdentifier())
5428     if (!NewTD->isInvalidDecl() &&
5429         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5430       if (II->isStr("FILE"))
5431         Context.setFILEDecl(NewTD);
5432       else if (II->isStr("jmp_buf"))
5433         Context.setjmp_bufDecl(NewTD);
5434       else if (II->isStr("sigjmp_buf"))
5435         Context.setsigjmp_bufDecl(NewTD);
5436       else if (II->isStr("ucontext_t"))
5437         Context.setucontext_tDecl(NewTD);
5438     }
5439 
5440   return NewTD;
5441 }
5442 
5443 /// \brief Determines whether the given declaration is an out-of-scope
5444 /// previous declaration.
5445 ///
5446 /// This routine should be invoked when name lookup has found a
5447 /// previous declaration (PrevDecl) that is not in the scope where a
5448 /// new declaration by the same name is being introduced. If the new
5449 /// declaration occurs in a local scope, previous declarations with
5450 /// linkage may still be considered previous declarations (C99
5451 /// 6.2.2p4-5, C++ [basic.link]p6).
5452 ///
5453 /// \param PrevDecl the previous declaration found by name
5454 /// lookup
5455 ///
5456 /// \param DC the context in which the new declaration is being
5457 /// declared.
5458 ///
5459 /// \returns true if PrevDecl is an out-of-scope previous declaration
5460 /// for a new delcaration with the same name.
5461 static bool
5462 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5463                                 ASTContext &Context) {
5464   if (!PrevDecl)
5465     return false;
5466 
5467   if (!PrevDecl->hasLinkage())
5468     return false;
5469 
5470   if (Context.getLangOpts().CPlusPlus) {
5471     // C++ [basic.link]p6:
5472     //   If there is a visible declaration of an entity with linkage
5473     //   having the same name and type, ignoring entities declared
5474     //   outside the innermost enclosing namespace scope, the block
5475     //   scope declaration declares that same entity and receives the
5476     //   linkage of the previous declaration.
5477     DeclContext *OuterContext = DC->getRedeclContext();
5478     if (!OuterContext->isFunctionOrMethod())
5479       // This rule only applies to block-scope declarations.
5480       return false;
5481 
5482     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5483     if (PrevOuterContext->isRecord())
5484       // We found a member function: ignore it.
5485       return false;
5486 
5487     // Find the innermost enclosing namespace for the new and
5488     // previous declarations.
5489     OuterContext = OuterContext->getEnclosingNamespaceContext();
5490     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5491 
5492     // The previous declaration is in a different namespace, so it
5493     // isn't the same function.
5494     if (!OuterContext->Equals(PrevOuterContext))
5495       return false;
5496   }
5497 
5498   return true;
5499 }
5500 
5501 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5502   CXXScopeSpec &SS = D.getCXXScopeSpec();
5503   if (!SS.isSet()) return;
5504   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5505 }
5506 
5507 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5508   QualType type = decl->getType();
5509   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5510   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5511     // Various kinds of declaration aren't allowed to be __autoreleasing.
5512     unsigned kind = -1U;
5513     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5514       if (var->hasAttr<BlocksAttr>())
5515         kind = 0; // __block
5516       else if (!var->hasLocalStorage())
5517         kind = 1; // global
5518     } else if (isa<ObjCIvarDecl>(decl)) {
5519       kind = 3; // ivar
5520     } else if (isa<FieldDecl>(decl)) {
5521       kind = 2; // field
5522     }
5523 
5524     if (kind != -1U) {
5525       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5526         << kind;
5527     }
5528   } else if (lifetime == Qualifiers::OCL_None) {
5529     // Try to infer lifetime.
5530     if (!type->isObjCLifetimeType())
5531       return false;
5532 
5533     lifetime = type->getObjCARCImplicitLifetime();
5534     type = Context.getLifetimeQualifiedType(type, lifetime);
5535     decl->setType(type);
5536   }
5537 
5538   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5539     // Thread-local variables cannot have lifetime.
5540     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5541         var->getTLSKind()) {
5542       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5543         << var->getType();
5544       return true;
5545     }
5546   }
5547 
5548   return false;
5549 }
5550 
5551 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5552   // Ensure that an auto decl is deduced otherwise the checks below might cache
5553   // the wrong linkage.
5554   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5555 
5556   // 'weak' only applies to declarations with external linkage.
5557   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5558     if (!ND.isExternallyVisible()) {
5559       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5560       ND.dropAttr<WeakAttr>();
5561     }
5562   }
5563   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5564     if (ND.isExternallyVisible()) {
5565       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5566       ND.dropAttr<WeakRefAttr>();
5567       ND.dropAttr<AliasAttr>();
5568     }
5569   }
5570 
5571   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5572     if (VD->hasInit()) {
5573       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5574         assert(VD->isThisDeclarationADefinition() &&
5575                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5576         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5577         VD->dropAttr<AliasAttr>();
5578       }
5579     }
5580   }
5581 
5582   // 'selectany' only applies to externally visible variable declarations.
5583   // It does not apply to functions.
5584   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5585     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5586       S.Diag(Attr->getLocation(),
5587              diag::err_attribute_selectany_non_extern_data);
5588       ND.dropAttr<SelectAnyAttr>();
5589     }
5590   }
5591 
5592   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5593     // dll attributes require external linkage. Static locals may have external
5594     // linkage but still cannot be explicitly imported or exported.
5595     auto *VD = dyn_cast<VarDecl>(&ND);
5596     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5597       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5598         << &ND << Attr;
5599       ND.setInvalidDecl();
5600     }
5601   }
5602 
5603   // Virtual functions cannot be marked as 'notail'.
5604   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5605     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5606       if (MD->isVirtual()) {
5607         S.Diag(ND.getLocation(),
5608                diag::err_invalid_attribute_on_virtual_function)
5609             << Attr;
5610         ND.dropAttr<NotTailCalledAttr>();
5611       }
5612 }
5613 
5614 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5615                                            NamedDecl *NewDecl,
5616                                            bool IsSpecialization,
5617                                            bool IsDefinition) {
5618   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5619     OldDecl = OldTD->getTemplatedDecl();
5620     if (!IsSpecialization)
5621       IsDefinition = false;
5622   }
5623   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5624     NewDecl = NewTD->getTemplatedDecl();
5625 
5626   if (!OldDecl || !NewDecl)
5627     return;
5628 
5629   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5630   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5631   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5632   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5633 
5634   // dllimport and dllexport are inheritable attributes so we have to exclude
5635   // inherited attribute instances.
5636   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5637                     (NewExportAttr && !NewExportAttr->isInherited());
5638 
5639   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5640   // the only exception being explicit specializations.
5641   // Implicitly generated declarations are also excluded for now because there
5642   // is no other way to switch these to use dllimport or dllexport.
5643   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5644 
5645   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5646     // Allow with a warning for free functions and global variables.
5647     bool JustWarn = false;
5648     if (!OldDecl->isCXXClassMember()) {
5649       auto *VD = dyn_cast<VarDecl>(OldDecl);
5650       if (VD && !VD->getDescribedVarTemplate())
5651         JustWarn = true;
5652       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5653       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5654         JustWarn = true;
5655     }
5656 
5657     // We cannot change a declaration that's been used because IR has already
5658     // been emitted. Dllimported functions will still work though (modulo
5659     // address equality) as they can use the thunk.
5660     if (OldDecl->isUsed())
5661       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5662         JustWarn = false;
5663 
5664     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5665                                : diag::err_attribute_dll_redeclaration;
5666     S.Diag(NewDecl->getLocation(), DiagID)
5667         << NewDecl
5668         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5669     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5670     if (!JustWarn) {
5671       NewDecl->setInvalidDecl();
5672       return;
5673     }
5674   }
5675 
5676   // A redeclaration is not allowed to drop a dllimport attribute, the only
5677   // exceptions being inline function definitions, local extern declarations,
5678   // qualified friend declarations or special MSVC extension: in the last case,
5679   // the declaration is treated as if it were marked dllexport.
5680   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5681   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5682   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5683     // Ignore static data because out-of-line definitions are diagnosed
5684     // separately.
5685     IsStaticDataMember = VD->isStaticDataMember();
5686     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5687                    VarDecl::DeclarationOnly;
5688   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5689     IsInline = FD->isInlined();
5690     IsQualifiedFriend = FD->getQualifier() &&
5691                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5692   }
5693 
5694   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5695       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5696     if (IsMicrosoft && IsDefinition) {
5697       S.Diag(NewDecl->getLocation(),
5698              diag::warn_redeclaration_without_import_attribute)
5699           << NewDecl;
5700       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5701       NewDecl->dropAttr<DLLImportAttr>();
5702       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5703           NewImportAttr->getRange(), S.Context,
5704           NewImportAttr->getSpellingListIndex()));
5705     } else {
5706       S.Diag(NewDecl->getLocation(),
5707              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5708           << NewDecl << OldImportAttr;
5709       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5710       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5711       OldDecl->dropAttr<DLLImportAttr>();
5712       NewDecl->dropAttr<DLLImportAttr>();
5713     }
5714   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5715     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5716     OldDecl->dropAttr<DLLImportAttr>();
5717     NewDecl->dropAttr<DLLImportAttr>();
5718     S.Diag(NewDecl->getLocation(),
5719            diag::warn_dllimport_dropped_from_inline_function)
5720         << NewDecl << OldImportAttr;
5721   }
5722 }
5723 
5724 /// Given that we are within the definition of the given function,
5725 /// will that definition behave like C99's 'inline', where the
5726 /// definition is discarded except for optimization purposes?
5727 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5728   // Try to avoid calling GetGVALinkageForFunction.
5729 
5730   // All cases of this require the 'inline' keyword.
5731   if (!FD->isInlined()) return false;
5732 
5733   // This is only possible in C++ with the gnu_inline attribute.
5734   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5735     return false;
5736 
5737   // Okay, go ahead and call the relatively-more-expensive function.
5738 
5739 #ifndef NDEBUG
5740   // AST quite reasonably asserts that it's working on a function
5741   // definition.  We don't really have a way to tell it that we're
5742   // currently defining the function, so just lie to it in +Asserts
5743   // builds.  This is an awful hack.
5744   FD->setLazyBody(1);
5745 #endif
5746 
5747   bool isC99Inline =
5748       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5749 
5750 #ifndef NDEBUG
5751   FD->setLazyBody(0);
5752 #endif
5753 
5754   return isC99Inline;
5755 }
5756 
5757 /// Determine whether a variable is extern "C" prior to attaching
5758 /// an initializer. We can't just call isExternC() here, because that
5759 /// will also compute and cache whether the declaration is externally
5760 /// visible, which might change when we attach the initializer.
5761 ///
5762 /// This can only be used if the declaration is known to not be a
5763 /// redeclaration of an internal linkage declaration.
5764 ///
5765 /// For instance:
5766 ///
5767 ///   auto x = []{};
5768 ///
5769 /// Attaching the initializer here makes this declaration not externally
5770 /// visible, because its type has internal linkage.
5771 ///
5772 /// FIXME: This is a hack.
5773 template<typename T>
5774 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5775   if (S.getLangOpts().CPlusPlus) {
5776     // In C++, the overloadable attribute negates the effects of extern "C".
5777     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5778       return false;
5779 
5780     // So do CUDA's host/device attributes.
5781     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5782                                  D->template hasAttr<CUDAHostAttr>()))
5783       return false;
5784   }
5785   return D->isExternC();
5786 }
5787 
5788 static bool shouldConsiderLinkage(const VarDecl *VD) {
5789   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5790   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5791     return VD->hasExternalStorage();
5792   if (DC->isFileContext())
5793     return true;
5794   if (DC->isRecord())
5795     return false;
5796   llvm_unreachable("Unexpected context");
5797 }
5798 
5799 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5800   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5801   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5802       isa<OMPDeclareReductionDecl>(DC))
5803     return true;
5804   if (DC->isRecord())
5805     return false;
5806   llvm_unreachable("Unexpected context");
5807 }
5808 
5809 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5810                           AttributeList::Kind Kind) {
5811   for (const AttributeList *L = AttrList; L; L = L->getNext())
5812     if (L->getKind() == Kind)
5813       return true;
5814   return false;
5815 }
5816 
5817 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5818                           AttributeList::Kind Kind) {
5819   // Check decl attributes on the DeclSpec.
5820   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5821     return true;
5822 
5823   // Walk the declarator structure, checking decl attributes that were in a type
5824   // position to the decl itself.
5825   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5826     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5827       return true;
5828   }
5829 
5830   // Finally, check attributes on the decl itself.
5831   return hasParsedAttr(S, PD.getAttributes(), Kind);
5832 }
5833 
5834 /// Adjust the \c DeclContext for a function or variable that might be a
5835 /// function-local external declaration.
5836 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5837   if (!DC->isFunctionOrMethod())
5838     return false;
5839 
5840   // If this is a local extern function or variable declared within a function
5841   // template, don't add it into the enclosing namespace scope until it is
5842   // instantiated; it might have a dependent type right now.
5843   if (DC->isDependentContext())
5844     return true;
5845 
5846   // C++11 [basic.link]p7:
5847   //   When a block scope declaration of an entity with linkage is not found to
5848   //   refer to some other declaration, then that entity is a member of the
5849   //   innermost enclosing namespace.
5850   //
5851   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5852   // semantically-enclosing namespace, not a lexically-enclosing one.
5853   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5854     DC = DC->getParent();
5855   return true;
5856 }
5857 
5858 /// \brief Returns true if given declaration has external C language linkage.
5859 static bool isDeclExternC(const Decl *D) {
5860   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5861     return FD->isExternC();
5862   if (const auto *VD = dyn_cast<VarDecl>(D))
5863     return VD->isExternC();
5864 
5865   llvm_unreachable("Unknown type of decl!");
5866 }
5867 
5868 NamedDecl *Sema::ActOnVariableDeclarator(
5869     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5870     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5871     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5872   QualType R = TInfo->getType();
5873   DeclarationName Name = GetNameForDeclarator(D).getName();
5874 
5875   IdentifierInfo *II = Name.getAsIdentifierInfo();
5876 
5877   if (D.isDecompositionDeclarator()) {
5878     AddToScope = false;
5879     // Take the name of the first declarator as our name for diagnostic
5880     // purposes.
5881     auto &Decomp = D.getDecompositionDeclarator();
5882     if (!Decomp.bindings().empty()) {
5883       II = Decomp.bindings()[0].Name;
5884       Name = II;
5885     }
5886   } else if (!II) {
5887     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5888       << Name;
5889     return nullptr;
5890   }
5891 
5892   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5893   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5894   // argument.
5895   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5896     Diag(D.getIdentifierLoc(),
5897          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5898         << R;
5899     D.setInvalidType();
5900     return nullptr;
5901   }
5902 
5903   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5904   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5905 
5906   // dllimport globals without explicit storage class are treated as extern. We
5907   // have to change the storage class this early to get the right DeclContext.
5908   if (SC == SC_None && !DC->isRecord() &&
5909       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5910       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5911     SC = SC_Extern;
5912 
5913   DeclContext *OriginalDC = DC;
5914   bool IsLocalExternDecl = SC == SC_Extern &&
5915                            adjustContextForLocalExternDecl(DC);
5916 
5917   if (getLangOpts().OpenCL) {
5918     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5919     QualType NR = R;
5920     while (NR->isPointerType()) {
5921       if (NR->isFunctionPointerType()) {
5922         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5923         D.setInvalidType();
5924         break;
5925       }
5926       NR = NR->getPointeeType();
5927     }
5928 
5929     if (!getOpenCLOptions().cl_khr_fp16) {
5930       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5931       // half array type (unless the cl_khr_fp16 extension is enabled).
5932       if (Context.getBaseElementType(R)->isHalfType()) {
5933         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5934         D.setInvalidType();
5935       }
5936     }
5937   }
5938 
5939   if (SCSpec == DeclSpec::SCS_mutable) {
5940     // mutable can only appear on non-static class members, so it's always
5941     // an error here
5942     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5943     D.setInvalidType();
5944     SC = SC_None;
5945   }
5946 
5947   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5948       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5949                               D.getDeclSpec().getStorageClassSpecLoc())) {
5950     // In C++11, the 'register' storage class specifier is deprecated.
5951     // Suppress the warning in system macros, it's used in macros in some
5952     // popular C system headers, such as in glibc's htonl() macro.
5953     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5954          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5955                                    : diag::warn_deprecated_register)
5956       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5957   }
5958 
5959   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5960 
5961   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5962     // C99 6.9p2: The storage-class specifiers auto and register shall not
5963     // appear in the declaration specifiers in an external declaration.
5964     // Global Register+Asm is a GNU extension we support.
5965     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5966       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5967       D.setInvalidType();
5968     }
5969   }
5970 
5971   if (getLangOpts().OpenCL) {
5972     // OpenCL v1.2 s6.9.b p4:
5973     // The sampler type cannot be used with the __local and __global address
5974     // space qualifiers.
5975     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5976       R.getAddressSpace() == LangAS::opencl_global)) {
5977       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5978     }
5979 
5980     // OpenCL 1.2 spec, p6.9 r:
5981     // The event type cannot be used to declare a program scope variable.
5982     // The event type cannot be used with the __local, __constant and __global
5983     // address space qualifiers.
5984     if (R->isEventT()) {
5985       if (S->getParent() == nullptr) {
5986         Diag(D.getLocStart(), diag::err_event_t_global_var);
5987         D.setInvalidType();
5988       }
5989 
5990       if (R.getAddressSpace()) {
5991         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5992         D.setInvalidType();
5993       }
5994     }
5995   }
5996 
5997   bool IsExplicitSpecialization = false;
5998   bool IsVariableTemplateSpecialization = false;
5999   bool IsPartialSpecialization = false;
6000   bool IsVariableTemplate = false;
6001   VarDecl *NewVD = nullptr;
6002   VarTemplateDecl *NewTemplate = nullptr;
6003   TemplateParameterList *TemplateParams = nullptr;
6004   if (!getLangOpts().CPlusPlus) {
6005     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6006                             D.getIdentifierLoc(), II,
6007                             R, TInfo, SC);
6008 
6009     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6010       ParsingInitForAutoVars.insert(NewVD);
6011 
6012     if (D.isInvalidType())
6013       NewVD->setInvalidDecl();
6014   } else {
6015     bool Invalid = false;
6016 
6017     if (DC->isRecord() && !CurContext->isRecord()) {
6018       // This is an out-of-line definition of a static data member.
6019       switch (SC) {
6020       case SC_None:
6021         break;
6022       case SC_Static:
6023         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6024              diag::err_static_out_of_line)
6025           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6026         break;
6027       case SC_Auto:
6028       case SC_Register:
6029       case SC_Extern:
6030         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6031         // to names of variables declared in a block or to function parameters.
6032         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6033         // of class members
6034 
6035         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6036              diag::err_storage_class_for_static_member)
6037           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6038         break;
6039       case SC_PrivateExtern:
6040         llvm_unreachable("C storage class in c++!");
6041       }
6042     }
6043 
6044     if (SC == SC_Static && CurContext->isRecord()) {
6045       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6046         if (RD->isLocalClass())
6047           Diag(D.getIdentifierLoc(),
6048                diag::err_static_data_member_not_allowed_in_local_class)
6049             << Name << RD->getDeclName();
6050 
6051         // C++98 [class.union]p1: If a union contains a static data member,
6052         // the program is ill-formed. C++11 drops this restriction.
6053         if (RD->isUnion())
6054           Diag(D.getIdentifierLoc(),
6055                getLangOpts().CPlusPlus11
6056                  ? diag::warn_cxx98_compat_static_data_member_in_union
6057                  : diag::ext_static_data_member_in_union) << Name;
6058         // We conservatively disallow static data members in anonymous structs.
6059         else if (!RD->getDeclName())
6060           Diag(D.getIdentifierLoc(),
6061                diag::err_static_data_member_not_allowed_in_anon_struct)
6062             << Name << RD->isUnion();
6063       }
6064     }
6065 
6066     // Match up the template parameter lists with the scope specifier, then
6067     // determine whether we have a template or a template specialization.
6068     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6069         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6070         D.getCXXScopeSpec(),
6071         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6072             ? D.getName().TemplateId
6073             : nullptr,
6074         TemplateParamLists,
6075         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6076 
6077     if (TemplateParams) {
6078       if (!TemplateParams->size() &&
6079           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6080         // There is an extraneous 'template<>' for this variable. Complain
6081         // about it, but allow the declaration of the variable.
6082         Diag(TemplateParams->getTemplateLoc(),
6083              diag::err_template_variable_noparams)
6084           << II
6085           << SourceRange(TemplateParams->getTemplateLoc(),
6086                          TemplateParams->getRAngleLoc());
6087         TemplateParams = nullptr;
6088       } else {
6089         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6090           // This is an explicit specialization or a partial specialization.
6091           // FIXME: Check that we can declare a specialization here.
6092           IsVariableTemplateSpecialization = true;
6093           IsPartialSpecialization = TemplateParams->size() > 0;
6094         } else { // if (TemplateParams->size() > 0)
6095           // This is a template declaration.
6096           IsVariableTemplate = true;
6097 
6098           // Check that we can declare a template here.
6099           if (CheckTemplateDeclScope(S, TemplateParams))
6100             return nullptr;
6101 
6102           // Only C++1y supports variable templates (N3651).
6103           Diag(D.getIdentifierLoc(),
6104                getLangOpts().CPlusPlus14
6105                    ? diag::warn_cxx11_compat_variable_template
6106                    : diag::ext_variable_template);
6107         }
6108       }
6109     } else {
6110       assert(
6111           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6112           "should have a 'template<>' for this decl");
6113     }
6114 
6115     if (IsVariableTemplateSpecialization) {
6116       SourceLocation TemplateKWLoc =
6117           TemplateParamLists.size() > 0
6118               ? TemplateParamLists[0]->getTemplateLoc()
6119               : SourceLocation();
6120       DeclResult Res = ActOnVarTemplateSpecialization(
6121           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6122           IsPartialSpecialization);
6123       if (Res.isInvalid())
6124         return nullptr;
6125       NewVD = cast<VarDecl>(Res.get());
6126       AddToScope = false;
6127     } else if (D.isDecompositionDeclarator()) {
6128       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6129                                         D.getIdentifierLoc(), R, TInfo, SC,
6130                                         Bindings);
6131     } else
6132       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6133                               D.getIdentifierLoc(), II, R, TInfo, SC);
6134 
6135     // If this is supposed to be a variable template, create it as such.
6136     if (IsVariableTemplate) {
6137       NewTemplate =
6138           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6139                                   TemplateParams, NewVD);
6140       NewVD->setDescribedVarTemplate(NewTemplate);
6141     }
6142 
6143     // If this decl has an auto type in need of deduction, make a note of the
6144     // Decl so we can diagnose uses of it in its own initializer.
6145     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6146       ParsingInitForAutoVars.insert(NewVD);
6147 
6148     if (D.isInvalidType() || Invalid) {
6149       NewVD->setInvalidDecl();
6150       if (NewTemplate)
6151         NewTemplate->setInvalidDecl();
6152     }
6153 
6154     SetNestedNameSpecifier(NewVD, D);
6155 
6156     // If we have any template parameter lists that don't directly belong to
6157     // the variable (matching the scope specifier), store them.
6158     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6159     if (TemplateParamLists.size() > VDTemplateParamLists)
6160       NewVD->setTemplateParameterListsInfo(
6161           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6162 
6163     if (D.getDeclSpec().isConstexprSpecified()) {
6164       NewVD->setConstexpr(true);
6165       // C++1z [dcl.spec.constexpr]p1:
6166       //   A static data member declared with the constexpr specifier is
6167       //   implicitly an inline variable.
6168       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6169         NewVD->setImplicitlyInline();
6170     }
6171 
6172     if (D.getDeclSpec().isConceptSpecified()) {
6173       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6174         VTD->setConcept();
6175 
6176       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6177       // be declared with the thread_local, inline, friend, or constexpr
6178       // specifiers, [...]
6179       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6180         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6181              diag::err_concept_decl_invalid_specifiers)
6182             << 0 << 0;
6183         NewVD->setInvalidDecl(true);
6184       }
6185 
6186       if (D.getDeclSpec().isConstexprSpecified()) {
6187         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6188              diag::err_concept_decl_invalid_specifiers)
6189             << 0 << 3;
6190         NewVD->setInvalidDecl(true);
6191       }
6192 
6193       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6194       // applied only to the definition of a function template or variable
6195       // template, declared in namespace scope.
6196       if (IsVariableTemplateSpecialization) {
6197         Diag(D.getDeclSpec().getConceptSpecLoc(),
6198              diag::err_concept_specified_specialization)
6199             << (IsPartialSpecialization ? 2 : 1);
6200       }
6201 
6202       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6203       // following restrictions:
6204       // - The declared type shall have the type bool.
6205       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6206           !NewVD->isInvalidDecl()) {
6207         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6208         NewVD->setInvalidDecl(true);
6209       }
6210     }
6211   }
6212 
6213   if (D.getDeclSpec().isInlineSpecified()) {
6214     if (!getLangOpts().CPlusPlus) {
6215       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6216           << 0;
6217     } else if (CurContext->isFunctionOrMethod()) {
6218       // 'inline' is not allowed on block scope variable declaration.
6219       Diag(D.getDeclSpec().getInlineSpecLoc(),
6220            diag::err_inline_declaration_block_scope) << Name
6221         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6222     } else {
6223       Diag(D.getDeclSpec().getInlineSpecLoc(),
6224            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6225                                      : diag::ext_inline_variable);
6226       NewVD->setInlineSpecified();
6227     }
6228   }
6229 
6230   // Set the lexical context. If the declarator has a C++ scope specifier, the
6231   // lexical context will be different from the semantic context.
6232   NewVD->setLexicalDeclContext(CurContext);
6233   if (NewTemplate)
6234     NewTemplate->setLexicalDeclContext(CurContext);
6235 
6236   if (IsLocalExternDecl) {
6237     if (D.isDecompositionDeclarator())
6238       for (auto *B : Bindings)
6239         B->setLocalExternDecl();
6240     else
6241       NewVD->setLocalExternDecl();
6242   }
6243 
6244   bool EmitTLSUnsupportedError = false;
6245   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6246     // C++11 [dcl.stc]p4:
6247     //   When thread_local is applied to a variable of block scope the
6248     //   storage-class-specifier static is implied if it does not appear
6249     //   explicitly.
6250     // Core issue: 'static' is not implied if the variable is declared
6251     //   'extern'.
6252     if (NewVD->hasLocalStorage() &&
6253         (SCSpec != DeclSpec::SCS_unspecified ||
6254          TSCS != DeclSpec::TSCS_thread_local ||
6255          !DC->isFunctionOrMethod()))
6256       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6257            diag::err_thread_non_global)
6258         << DeclSpec::getSpecifierName(TSCS);
6259     else if (!Context.getTargetInfo().isTLSSupported()) {
6260       if (getLangOpts().CUDA) {
6261         // Postpone error emission until we've collected attributes required to
6262         // figure out whether it's a host or device variable and whether the
6263         // error should be ignored.
6264         EmitTLSUnsupportedError = true;
6265         // We still need to mark the variable as TLS so it shows up in AST with
6266         // proper storage class for other tools to use even if we're not going
6267         // to emit any code for it.
6268         NewVD->setTSCSpec(TSCS);
6269       } else
6270         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6271              diag::err_thread_unsupported);
6272     } else
6273       NewVD->setTSCSpec(TSCS);
6274   }
6275 
6276   // C99 6.7.4p3
6277   //   An inline definition of a function with external linkage shall
6278   //   not contain a definition of a modifiable object with static or
6279   //   thread storage duration...
6280   // We only apply this when the function is required to be defined
6281   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6282   // that a local variable with thread storage duration still has to
6283   // be marked 'static'.  Also note that it's possible to get these
6284   // semantics in C++ using __attribute__((gnu_inline)).
6285   if (SC == SC_Static && S->getFnParent() != nullptr &&
6286       !NewVD->getType().isConstQualified()) {
6287     FunctionDecl *CurFD = getCurFunctionDecl();
6288     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6289       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6290            diag::warn_static_local_in_extern_inline);
6291       MaybeSuggestAddingStaticToDecl(CurFD);
6292     }
6293   }
6294 
6295   if (D.getDeclSpec().isModulePrivateSpecified()) {
6296     if (IsVariableTemplateSpecialization)
6297       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6298           << (IsPartialSpecialization ? 1 : 0)
6299           << FixItHint::CreateRemoval(
6300                  D.getDeclSpec().getModulePrivateSpecLoc());
6301     else if (IsExplicitSpecialization)
6302       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6303         << 2
6304         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6305     else if (NewVD->hasLocalStorage())
6306       Diag(NewVD->getLocation(), diag::err_module_private_local)
6307         << 0 << NewVD->getDeclName()
6308         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6309         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6310     else {
6311       NewVD->setModulePrivate();
6312       if (NewTemplate)
6313         NewTemplate->setModulePrivate();
6314       for (auto *B : Bindings)
6315         B->setModulePrivate();
6316     }
6317   }
6318 
6319   // Handle attributes prior to checking for duplicates in MergeVarDecl
6320   ProcessDeclAttributes(S, NewVD, D);
6321 
6322   if (getLangOpts().CUDA) {
6323     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6324       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6325            diag::err_thread_unsupported);
6326     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6327     // storage [duration]."
6328     if (SC == SC_None && S->getFnParent() != nullptr &&
6329         (NewVD->hasAttr<CUDASharedAttr>() ||
6330          NewVD->hasAttr<CUDAConstantAttr>())) {
6331       NewVD->setStorageClass(SC_Static);
6332     }
6333   }
6334 
6335   // Ensure that dllimport globals without explicit storage class are treated as
6336   // extern. The storage class is set above using parsed attributes. Now we can
6337   // check the VarDecl itself.
6338   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6339          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6340          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6341 
6342   // In auto-retain/release, infer strong retension for variables of
6343   // retainable type.
6344   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6345     NewVD->setInvalidDecl();
6346 
6347   // Handle GNU asm-label extension (encoded as an attribute).
6348   if (Expr *E = (Expr*)D.getAsmLabel()) {
6349     // The parser guarantees this is a string.
6350     StringLiteral *SE = cast<StringLiteral>(E);
6351     StringRef Label = SE->getString();
6352     if (S->getFnParent() != nullptr) {
6353       switch (SC) {
6354       case SC_None:
6355       case SC_Auto:
6356         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6357         break;
6358       case SC_Register:
6359         // Local Named register
6360         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6361             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6362           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6363         break;
6364       case SC_Static:
6365       case SC_Extern:
6366       case SC_PrivateExtern:
6367         break;
6368       }
6369     } else if (SC == SC_Register) {
6370       // Global Named register
6371       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6372         const auto &TI = Context.getTargetInfo();
6373         bool HasSizeMismatch;
6374 
6375         if (!TI.isValidGCCRegisterName(Label))
6376           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6377         else if (!TI.validateGlobalRegisterVariable(Label,
6378                                                     Context.getTypeSize(R),
6379                                                     HasSizeMismatch))
6380           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6381         else if (HasSizeMismatch)
6382           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6383       }
6384 
6385       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6386         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6387         NewVD->setInvalidDecl(true);
6388       }
6389     }
6390 
6391     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6392                                                 Context, Label, 0));
6393   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6394     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6395       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6396     if (I != ExtnameUndeclaredIdentifiers.end()) {
6397       if (isDeclExternC(NewVD)) {
6398         NewVD->addAttr(I->second);
6399         ExtnameUndeclaredIdentifiers.erase(I);
6400       } else
6401         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6402             << /*Variable*/1 << NewVD;
6403     }
6404   }
6405 
6406   // Diagnose shadowed variables before filtering for scope.
6407   if (D.getCXXScopeSpec().isEmpty())
6408     CheckShadow(S, NewVD, Previous);
6409 
6410   // Don't consider existing declarations that are in a different
6411   // scope and are out-of-semantic-context declarations (if the new
6412   // declaration has linkage).
6413   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6414                        D.getCXXScopeSpec().isNotEmpty() ||
6415                        IsExplicitSpecialization ||
6416                        IsVariableTemplateSpecialization);
6417 
6418   // Check whether the previous declaration is in the same block scope. This
6419   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6420   if (getLangOpts().CPlusPlus &&
6421       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6422     NewVD->setPreviousDeclInSameBlockScope(
6423         Previous.isSingleResult() && !Previous.isShadowed() &&
6424         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6425 
6426   if (!getLangOpts().CPlusPlus) {
6427     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6428   } else {
6429     // If this is an explicit specialization of a static data member, check it.
6430     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6431         CheckMemberSpecialization(NewVD, Previous))
6432       NewVD->setInvalidDecl();
6433 
6434     // Merge the decl with the existing one if appropriate.
6435     if (!Previous.empty()) {
6436       if (Previous.isSingleResult() &&
6437           isa<FieldDecl>(Previous.getFoundDecl()) &&
6438           D.getCXXScopeSpec().isSet()) {
6439         // The user tried to define a non-static data member
6440         // out-of-line (C++ [dcl.meaning]p1).
6441         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6442           << D.getCXXScopeSpec().getRange();
6443         Previous.clear();
6444         NewVD->setInvalidDecl();
6445       }
6446     } else if (D.getCXXScopeSpec().isSet()) {
6447       // No previous declaration in the qualifying scope.
6448       Diag(D.getIdentifierLoc(), diag::err_no_member)
6449         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6450         << D.getCXXScopeSpec().getRange();
6451       NewVD->setInvalidDecl();
6452     }
6453 
6454     if (!IsVariableTemplateSpecialization)
6455       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6456 
6457     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6458     // an explicit specialization (14.8.3) or a partial specialization of a
6459     // concept definition.
6460     if (IsVariableTemplateSpecialization &&
6461         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6462         Previous.isSingleResult()) {
6463       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6464       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6465         if (VarTmpl->isConcept()) {
6466           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6467               << 1                            /*variable*/
6468               << (IsPartialSpecialization ? 2 /*partially specialized*/
6469                                           : 1 /*explicitly specialized*/);
6470           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6471           NewVD->setInvalidDecl();
6472         }
6473       }
6474     }
6475 
6476     if (NewTemplate) {
6477       VarTemplateDecl *PrevVarTemplate =
6478           NewVD->getPreviousDecl()
6479               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6480               : nullptr;
6481 
6482       // Check the template parameter list of this declaration, possibly
6483       // merging in the template parameter list from the previous variable
6484       // template declaration.
6485       if (CheckTemplateParameterList(
6486               TemplateParams,
6487               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6488                               : nullptr,
6489               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6490                DC->isDependentContext())
6491                   ? TPC_ClassTemplateMember
6492                   : TPC_VarTemplate))
6493         NewVD->setInvalidDecl();
6494 
6495       // If we are providing an explicit specialization of a static variable
6496       // template, make a note of that.
6497       if (PrevVarTemplate &&
6498           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6499         PrevVarTemplate->setMemberSpecialization();
6500     }
6501   }
6502 
6503   ProcessPragmaWeak(S, NewVD);
6504 
6505   // If this is the first declaration of an extern C variable, update
6506   // the map of such variables.
6507   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6508       isIncompleteDeclExternC(*this, NewVD))
6509     RegisterLocallyScopedExternCDecl(NewVD, S);
6510 
6511   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6512     Decl *ManglingContextDecl;
6513     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6514             NewVD->getDeclContext(), ManglingContextDecl)) {
6515       Context.setManglingNumber(
6516           NewVD, MCtx->getManglingNumber(
6517                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6518       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6519     }
6520   }
6521 
6522   // Special handling of variable named 'main'.
6523   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6524       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6525       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6526 
6527     // C++ [basic.start.main]p3
6528     // A program that declares a variable main at global scope is ill-formed.
6529     if (getLangOpts().CPlusPlus)
6530       Diag(D.getLocStart(), diag::err_main_global_variable);
6531 
6532     // In C, and external-linkage variable named main results in undefined
6533     // behavior.
6534     else if (NewVD->hasExternalFormalLinkage())
6535       Diag(D.getLocStart(), diag::warn_main_redefined);
6536   }
6537 
6538   if (D.isRedeclaration() && !Previous.empty()) {
6539     checkDLLAttributeRedeclaration(
6540         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6541         IsExplicitSpecialization, D.isFunctionDefinition());
6542   }
6543 
6544   if (NewTemplate) {
6545     if (NewVD->isInvalidDecl())
6546       NewTemplate->setInvalidDecl();
6547     ActOnDocumentableDecl(NewTemplate);
6548     return NewTemplate;
6549   }
6550 
6551   return NewVD;
6552 }
6553 
6554 /// Enum describing the %select options in diag::warn_decl_shadow.
6555 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6556 
6557 /// Determine what kind of declaration we're shadowing.
6558 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6559                                                 const DeclContext *OldDC) {
6560   if (isa<RecordDecl>(OldDC))
6561     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6562   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6563 }
6564 
6565 /// \brief Diagnose variable or built-in function shadowing.  Implements
6566 /// -Wshadow.
6567 ///
6568 /// This method is called whenever a VarDecl is added to a "useful"
6569 /// scope.
6570 ///
6571 /// \param S the scope in which the shadowing name is being declared
6572 /// \param R the lookup of the name
6573 ///
6574 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6575   // Return if warning is ignored.
6576   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6577     return;
6578 
6579   // Don't diagnose declarations at file scope.
6580   if (D->hasGlobalStorage())
6581     return;
6582 
6583   DeclContext *NewDC = D->getDeclContext();
6584 
6585   // Only diagnose if we're shadowing an unambiguous field or variable.
6586   if (R.getResultKind() != LookupResult::Found)
6587     return;
6588 
6589   NamedDecl* ShadowedDecl = R.getFoundDecl();
6590   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6591     return;
6592 
6593   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6594     // Fields are not shadowed by variables in C++ static methods.
6595     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6596       if (MD->isStatic())
6597         return;
6598 
6599     // Fields shadowed by constructor parameters are a special case. Usually
6600     // the constructor initializes the field with the parameter.
6601     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6602       // Remember that this was shadowed so we can either warn about its
6603       // modification or its existence depending on warning settings.
6604       D = D->getCanonicalDecl();
6605       ShadowingDecls.insert({D, FD});
6606       return;
6607     }
6608   }
6609 
6610   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6611     if (shadowedVar->isExternC()) {
6612       // For shadowing external vars, make sure that we point to the global
6613       // declaration, not a locally scoped extern declaration.
6614       for (auto I : shadowedVar->redecls())
6615         if (I->isFileVarDecl()) {
6616           ShadowedDecl = I;
6617           break;
6618         }
6619     }
6620 
6621   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6622 
6623   // Only warn about certain kinds of shadowing for class members.
6624   if (NewDC && NewDC->isRecord()) {
6625     // In particular, don't warn about shadowing non-class members.
6626     if (!OldDC->isRecord())
6627       return;
6628 
6629     // TODO: should we warn about static data members shadowing
6630     // static data members from base classes?
6631 
6632     // TODO: don't diagnose for inaccessible shadowed members.
6633     // This is hard to do perfectly because we might friend the
6634     // shadowing context, but that's just a false negative.
6635   }
6636 
6637 
6638   DeclarationName Name = R.getLookupName();
6639 
6640   // Emit warning and note.
6641   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6642     return;
6643   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6644   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6645   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6646 }
6647 
6648 /// \brief Check -Wshadow without the advantage of a previous lookup.
6649 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6650   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6651     return;
6652 
6653   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6654                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6655   LookupName(R, S);
6656   CheckShadow(S, D, R);
6657 }
6658 
6659 /// Check if 'E', which is an expression that is about to be modified, refers
6660 /// to a constructor parameter that shadows a field.
6661 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6662   // Quickly ignore expressions that can't be shadowing ctor parameters.
6663   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6664     return;
6665   E = E->IgnoreParenImpCasts();
6666   auto *DRE = dyn_cast<DeclRefExpr>(E);
6667   if (!DRE)
6668     return;
6669   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6670   auto I = ShadowingDecls.find(D);
6671   if (I == ShadowingDecls.end())
6672     return;
6673   const NamedDecl *ShadowedDecl = I->second;
6674   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6675   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6676   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6677   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6678 
6679   // Avoid issuing multiple warnings about the same decl.
6680   ShadowingDecls.erase(I);
6681 }
6682 
6683 /// Check for conflict between this global or extern "C" declaration and
6684 /// previous global or extern "C" declarations. This is only used in C++.
6685 template<typename T>
6686 static bool checkGlobalOrExternCConflict(
6687     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6688   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6689   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6690 
6691   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6692     // The common case: this global doesn't conflict with any extern "C"
6693     // declaration.
6694     return false;
6695   }
6696 
6697   if (Prev) {
6698     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6699       // Both the old and new declarations have C language linkage. This is a
6700       // redeclaration.
6701       Previous.clear();
6702       Previous.addDecl(Prev);
6703       return true;
6704     }
6705 
6706     // This is a global, non-extern "C" declaration, and there is a previous
6707     // non-global extern "C" declaration. Diagnose if this is a variable
6708     // declaration.
6709     if (!isa<VarDecl>(ND))
6710       return false;
6711   } else {
6712     // The declaration is extern "C". Check for any declaration in the
6713     // translation unit which might conflict.
6714     if (IsGlobal) {
6715       // We have already performed the lookup into the translation unit.
6716       IsGlobal = false;
6717       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6718            I != E; ++I) {
6719         if (isa<VarDecl>(*I)) {
6720           Prev = *I;
6721           break;
6722         }
6723       }
6724     } else {
6725       DeclContext::lookup_result R =
6726           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6727       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6728            I != E; ++I) {
6729         if (isa<VarDecl>(*I)) {
6730           Prev = *I;
6731           break;
6732         }
6733         // FIXME: If we have any other entity with this name in global scope,
6734         // the declaration is ill-formed, but that is a defect: it breaks the
6735         // 'stat' hack, for instance. Only variables can have mangled name
6736         // clashes with extern "C" declarations, so only they deserve a
6737         // diagnostic.
6738       }
6739     }
6740 
6741     if (!Prev)
6742       return false;
6743   }
6744 
6745   // Use the first declaration's location to ensure we point at something which
6746   // is lexically inside an extern "C" linkage-spec.
6747   assert(Prev && "should have found a previous declaration to diagnose");
6748   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6749     Prev = FD->getFirstDecl();
6750   else
6751     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6752 
6753   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6754     << IsGlobal << ND;
6755   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6756     << IsGlobal;
6757   return false;
6758 }
6759 
6760 /// Apply special rules for handling extern "C" declarations. Returns \c true
6761 /// if we have found that this is a redeclaration of some prior entity.
6762 ///
6763 /// Per C++ [dcl.link]p6:
6764 ///   Two declarations [for a function or variable] with C language linkage
6765 ///   with the same name that appear in different scopes refer to the same
6766 ///   [entity]. An entity with C language linkage shall not be declared with
6767 ///   the same name as an entity in global scope.
6768 template<typename T>
6769 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6770                                                   LookupResult &Previous) {
6771   if (!S.getLangOpts().CPlusPlus) {
6772     // In C, when declaring a global variable, look for a corresponding 'extern'
6773     // variable declared in function scope. We don't need this in C++, because
6774     // we find local extern decls in the surrounding file-scope DeclContext.
6775     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6776       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6777         Previous.clear();
6778         Previous.addDecl(Prev);
6779         return true;
6780       }
6781     }
6782     return false;
6783   }
6784 
6785   // A declaration in the translation unit can conflict with an extern "C"
6786   // declaration.
6787   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6788     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6789 
6790   // An extern "C" declaration can conflict with a declaration in the
6791   // translation unit or can be a redeclaration of an extern "C" declaration
6792   // in another scope.
6793   if (isIncompleteDeclExternC(S,ND))
6794     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6795 
6796   // Neither global nor extern "C": nothing to do.
6797   return false;
6798 }
6799 
6800 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6801   // If the decl is already known invalid, don't check it.
6802   if (NewVD->isInvalidDecl())
6803     return;
6804 
6805   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6806   QualType T = TInfo->getType();
6807 
6808   // Defer checking an 'auto' type until its initializer is attached.
6809   if (T->isUndeducedType())
6810     return;
6811 
6812   if (NewVD->hasAttrs())
6813     CheckAlignasUnderalignment(NewVD);
6814 
6815   if (T->isObjCObjectType()) {
6816     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6817       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6818     T = Context.getObjCObjectPointerType(T);
6819     NewVD->setType(T);
6820   }
6821 
6822   // Emit an error if an address space was applied to decl with local storage.
6823   // This includes arrays of objects with address space qualifiers, but not
6824   // automatic variables that point to other address spaces.
6825   // ISO/IEC TR 18037 S5.1.2
6826   if (!getLangOpts().OpenCL
6827       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6828     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6829     NewVD->setInvalidDecl();
6830     return;
6831   }
6832 
6833   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6834   // scope.
6835   if (getLangOpts().OpenCLVersion == 120 &&
6836       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6837       NewVD->isStaticLocal()) {
6838     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6839     NewVD->setInvalidDecl();
6840     return;
6841   }
6842 
6843   if (getLangOpts().OpenCL) {
6844     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6845     if (NewVD->hasAttr<BlocksAttr>()) {
6846       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6847       return;
6848     }
6849 
6850     if (T->isBlockPointerType()) {
6851       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6852       // can't use 'extern' storage class.
6853       if (!T.isConstQualified()) {
6854         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6855             << 0 /*const*/;
6856         NewVD->setInvalidDecl();
6857         return;
6858       }
6859       if (NewVD->hasExternalStorage()) {
6860         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6861         NewVD->setInvalidDecl();
6862         return;
6863       }
6864       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6865       // TODO: this check is not enough as it doesn't diagnose the typedef
6866       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6867       const FunctionProtoType *FTy =
6868           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6869       if (FTy && FTy->isVariadic()) {
6870         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6871             << T << NewVD->getSourceRange();
6872         NewVD->setInvalidDecl();
6873         return;
6874       }
6875     }
6876     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6877     // __constant address space.
6878     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6879     // variables inside a function can also be declared in the global
6880     // address space.
6881     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6882         NewVD->hasExternalStorage()) {
6883       if (!T->isSamplerT() &&
6884           !(T.getAddressSpace() == LangAS::opencl_constant ||
6885             (T.getAddressSpace() == LangAS::opencl_global &&
6886              getLangOpts().OpenCLVersion == 200))) {
6887         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6888         if (getLangOpts().OpenCLVersion == 200)
6889           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6890               << Scope << "global or constant";
6891         else
6892           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6893               << Scope << "constant";
6894         NewVD->setInvalidDecl();
6895         return;
6896       }
6897     } else {
6898       if (T.getAddressSpace() == LangAS::opencl_global) {
6899         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6900             << 1 /*is any function*/ << "global";
6901         NewVD->setInvalidDecl();
6902         return;
6903       }
6904       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6905       // in functions.
6906       if (T.getAddressSpace() == LangAS::opencl_constant ||
6907           T.getAddressSpace() == LangAS::opencl_local) {
6908         FunctionDecl *FD = getCurFunctionDecl();
6909         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6910           if (T.getAddressSpace() == LangAS::opencl_constant)
6911             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6912                 << 0 /*non-kernel only*/ << "constant";
6913           else
6914             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6915                 << 0 /*non-kernel only*/ << "local";
6916           NewVD->setInvalidDecl();
6917           return;
6918         }
6919       }
6920     }
6921   }
6922 
6923   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6924       && !NewVD->hasAttr<BlocksAttr>()) {
6925     if (getLangOpts().getGC() != LangOptions::NonGC)
6926       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6927     else {
6928       assert(!getLangOpts().ObjCAutoRefCount);
6929       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6930     }
6931   }
6932 
6933   bool isVM = T->isVariablyModifiedType();
6934   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6935       NewVD->hasAttr<BlocksAttr>())
6936     getCurFunction()->setHasBranchProtectedScope();
6937 
6938   if ((isVM && NewVD->hasLinkage()) ||
6939       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6940     bool SizeIsNegative;
6941     llvm::APSInt Oversized;
6942     TypeSourceInfo *FixedTInfo =
6943       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6944                                                     SizeIsNegative, Oversized);
6945     if (!FixedTInfo && T->isVariableArrayType()) {
6946       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6947       // FIXME: This won't give the correct result for
6948       // int a[10][n];
6949       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6950 
6951       if (NewVD->isFileVarDecl())
6952         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6953         << SizeRange;
6954       else if (NewVD->isStaticLocal())
6955         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6956         << SizeRange;
6957       else
6958         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6959         << SizeRange;
6960       NewVD->setInvalidDecl();
6961       return;
6962     }
6963 
6964     if (!FixedTInfo) {
6965       if (NewVD->isFileVarDecl())
6966         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6967       else
6968         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6969       NewVD->setInvalidDecl();
6970       return;
6971     }
6972 
6973     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6974     NewVD->setType(FixedTInfo->getType());
6975     NewVD->setTypeSourceInfo(FixedTInfo);
6976   }
6977 
6978   if (T->isVoidType()) {
6979     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6980     //                    of objects and functions.
6981     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6982       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6983         << T;
6984       NewVD->setInvalidDecl();
6985       return;
6986     }
6987   }
6988 
6989   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6990     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6991     NewVD->setInvalidDecl();
6992     return;
6993   }
6994 
6995   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6996     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6997     NewVD->setInvalidDecl();
6998     return;
6999   }
7000 
7001   if (NewVD->isConstexpr() && !T->isDependentType() &&
7002       RequireLiteralType(NewVD->getLocation(), T,
7003                          diag::err_constexpr_var_non_literal)) {
7004     NewVD->setInvalidDecl();
7005     return;
7006   }
7007 }
7008 
7009 /// \brief Perform semantic checking on a newly-created variable
7010 /// declaration.
7011 ///
7012 /// This routine performs all of the type-checking required for a
7013 /// variable declaration once it has been built. It is used both to
7014 /// check variables after they have been parsed and their declarators
7015 /// have been translated into a declaration, and to check variables
7016 /// that have been instantiated from a template.
7017 ///
7018 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7019 ///
7020 /// Returns true if the variable declaration is a redeclaration.
7021 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7022   CheckVariableDeclarationType(NewVD);
7023 
7024   // If the decl is already known invalid, don't check it.
7025   if (NewVD->isInvalidDecl())
7026     return false;
7027 
7028   // If we did not find anything by this name, look for a non-visible
7029   // extern "C" declaration with the same name.
7030   if (Previous.empty() &&
7031       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7032     Previous.setShadowed();
7033 
7034   if (!Previous.empty()) {
7035     MergeVarDecl(NewVD, Previous);
7036     return true;
7037   }
7038   return false;
7039 }
7040 
7041 namespace {
7042 struct FindOverriddenMethod {
7043   Sema *S;
7044   CXXMethodDecl *Method;
7045 
7046   /// Member lookup function that determines whether a given C++
7047   /// method overrides a method in a base class, to be used with
7048   /// CXXRecordDecl::lookupInBases().
7049   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7050     RecordDecl *BaseRecord =
7051         Specifier->getType()->getAs<RecordType>()->getDecl();
7052 
7053     DeclarationName Name = Method->getDeclName();
7054 
7055     // FIXME: Do we care about other names here too?
7056     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7057       // We really want to find the base class destructor here.
7058       QualType T = S->Context.getTypeDeclType(BaseRecord);
7059       CanQualType CT = S->Context.getCanonicalType(T);
7060 
7061       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7062     }
7063 
7064     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7065          Path.Decls = Path.Decls.slice(1)) {
7066       NamedDecl *D = Path.Decls.front();
7067       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7068         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7069           return true;
7070       }
7071     }
7072 
7073     return false;
7074   }
7075 };
7076 
7077 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7078 } // end anonymous namespace
7079 
7080 /// \brief Report an error regarding overriding, along with any relevant
7081 /// overriden methods.
7082 ///
7083 /// \param DiagID the primary error to report.
7084 /// \param MD the overriding method.
7085 /// \param OEK which overrides to include as notes.
7086 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7087                             OverrideErrorKind OEK = OEK_All) {
7088   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7089   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7090                                       E = MD->end_overridden_methods();
7091        I != E; ++I) {
7092     // This check (& the OEK parameter) could be replaced by a predicate, but
7093     // without lambdas that would be overkill. This is still nicer than writing
7094     // out the diag loop 3 times.
7095     if ((OEK == OEK_All) ||
7096         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7097         (OEK == OEK_Deleted && (*I)->isDeleted()))
7098       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7099   }
7100 }
7101 
7102 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7103 /// and if so, check that it's a valid override and remember it.
7104 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7105   // Look for methods in base classes that this method might override.
7106   CXXBasePaths Paths;
7107   FindOverriddenMethod FOM;
7108   FOM.Method = MD;
7109   FOM.S = this;
7110   bool hasDeletedOverridenMethods = false;
7111   bool hasNonDeletedOverridenMethods = false;
7112   bool AddedAny = false;
7113   if (DC->lookupInBases(FOM, Paths)) {
7114     for (auto *I : Paths.found_decls()) {
7115       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7116         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7117         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7118             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7119             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7120             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7121           hasDeletedOverridenMethods |= OldMD->isDeleted();
7122           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7123           AddedAny = true;
7124         }
7125       }
7126     }
7127   }
7128 
7129   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7130     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7131   }
7132   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7133     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7134   }
7135 
7136   return AddedAny;
7137 }
7138 
7139 namespace {
7140   // Struct for holding all of the extra arguments needed by
7141   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7142   struct ActOnFDArgs {
7143     Scope *S;
7144     Declarator &D;
7145     MultiTemplateParamsArg TemplateParamLists;
7146     bool AddToScope;
7147   };
7148 } // end anonymous namespace
7149 
7150 namespace {
7151 
7152 // Callback to only accept typo corrections that have a non-zero edit distance.
7153 // Also only accept corrections that have the same parent decl.
7154 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7155  public:
7156   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7157                             CXXRecordDecl *Parent)
7158       : Context(Context), OriginalFD(TypoFD),
7159         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7160 
7161   bool ValidateCandidate(const TypoCorrection &candidate) override {
7162     if (candidate.getEditDistance() == 0)
7163       return false;
7164 
7165     SmallVector<unsigned, 1> MismatchedParams;
7166     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7167                                           CDeclEnd = candidate.end();
7168          CDecl != CDeclEnd; ++CDecl) {
7169       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7170 
7171       if (FD && !FD->hasBody() &&
7172           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7173         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7174           CXXRecordDecl *Parent = MD->getParent();
7175           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7176             return true;
7177         } else if (!ExpectedParent) {
7178           return true;
7179         }
7180       }
7181     }
7182 
7183     return false;
7184   }
7185 
7186  private:
7187   ASTContext &Context;
7188   FunctionDecl *OriginalFD;
7189   CXXRecordDecl *ExpectedParent;
7190 };
7191 
7192 } // end anonymous namespace
7193 
7194 /// \brief Generate diagnostics for an invalid function redeclaration.
7195 ///
7196 /// This routine handles generating the diagnostic messages for an invalid
7197 /// function redeclaration, including finding possible similar declarations
7198 /// or performing typo correction if there are no previous declarations with
7199 /// the same name.
7200 ///
7201 /// Returns a NamedDecl iff typo correction was performed and substituting in
7202 /// the new declaration name does not cause new errors.
7203 static NamedDecl *DiagnoseInvalidRedeclaration(
7204     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7205     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7206   DeclarationName Name = NewFD->getDeclName();
7207   DeclContext *NewDC = NewFD->getDeclContext();
7208   SmallVector<unsigned, 1> MismatchedParams;
7209   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7210   TypoCorrection Correction;
7211   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7212   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7213                                    : diag::err_member_decl_does_not_match;
7214   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7215                     IsLocalFriend ? Sema::LookupLocalFriendName
7216                                   : Sema::LookupOrdinaryName,
7217                     Sema::ForRedeclaration);
7218 
7219   NewFD->setInvalidDecl();
7220   if (IsLocalFriend)
7221     SemaRef.LookupName(Prev, S);
7222   else
7223     SemaRef.LookupQualifiedName(Prev, NewDC);
7224   assert(!Prev.isAmbiguous() &&
7225          "Cannot have an ambiguity in previous-declaration lookup");
7226   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7227   if (!Prev.empty()) {
7228     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7229          Func != FuncEnd; ++Func) {
7230       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7231       if (FD &&
7232           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7233         // Add 1 to the index so that 0 can mean the mismatch didn't
7234         // involve a parameter
7235         unsigned ParamNum =
7236             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7237         NearMatches.push_back(std::make_pair(FD, ParamNum));
7238       }
7239     }
7240   // If the qualified name lookup yielded nothing, try typo correction
7241   } else if ((Correction = SemaRef.CorrectTypo(
7242                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7243                   &ExtraArgs.D.getCXXScopeSpec(),
7244                   llvm::make_unique<DifferentNameValidatorCCC>(
7245                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7246                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7247     // Set up everything for the call to ActOnFunctionDeclarator
7248     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7249                               ExtraArgs.D.getIdentifierLoc());
7250     Previous.clear();
7251     Previous.setLookupName(Correction.getCorrection());
7252     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7253                                     CDeclEnd = Correction.end();
7254          CDecl != CDeclEnd; ++CDecl) {
7255       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7256       if (FD && !FD->hasBody() &&
7257           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7258         Previous.addDecl(FD);
7259       }
7260     }
7261     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7262 
7263     NamedDecl *Result;
7264     // Retry building the function declaration with the new previous
7265     // declarations, and with errors suppressed.
7266     {
7267       // Trap errors.
7268       Sema::SFINAETrap Trap(SemaRef);
7269 
7270       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7271       // pieces need to verify the typo-corrected C++ declaration and hopefully
7272       // eliminate the need for the parameter pack ExtraArgs.
7273       Result = SemaRef.ActOnFunctionDeclarator(
7274           ExtraArgs.S, ExtraArgs.D,
7275           Correction.getCorrectionDecl()->getDeclContext(),
7276           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7277           ExtraArgs.AddToScope);
7278 
7279       if (Trap.hasErrorOccurred())
7280         Result = nullptr;
7281     }
7282 
7283     if (Result) {
7284       // Determine which correction we picked.
7285       Decl *Canonical = Result->getCanonicalDecl();
7286       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7287            I != E; ++I)
7288         if ((*I)->getCanonicalDecl() == Canonical)
7289           Correction.setCorrectionDecl(*I);
7290 
7291       SemaRef.diagnoseTypo(
7292           Correction,
7293           SemaRef.PDiag(IsLocalFriend
7294                           ? diag::err_no_matching_local_friend_suggest
7295                           : diag::err_member_decl_does_not_match_suggest)
7296             << Name << NewDC << IsDefinition);
7297       return Result;
7298     }
7299 
7300     // Pretend the typo correction never occurred
7301     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7302                               ExtraArgs.D.getIdentifierLoc());
7303     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7304     Previous.clear();
7305     Previous.setLookupName(Name);
7306   }
7307 
7308   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7309       << Name << NewDC << IsDefinition << NewFD->getLocation();
7310 
7311   bool NewFDisConst = false;
7312   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7313     NewFDisConst = NewMD->isConst();
7314 
7315   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7316        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7317        NearMatch != NearMatchEnd; ++NearMatch) {
7318     FunctionDecl *FD = NearMatch->first;
7319     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7320     bool FDisConst = MD && MD->isConst();
7321     bool IsMember = MD || !IsLocalFriend;
7322 
7323     // FIXME: These notes are poorly worded for the local friend case.
7324     if (unsigned Idx = NearMatch->second) {
7325       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7326       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7327       if (Loc.isInvalid()) Loc = FD->getLocation();
7328       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7329                                  : diag::note_local_decl_close_param_match)
7330         << Idx << FDParam->getType()
7331         << NewFD->getParamDecl(Idx - 1)->getType();
7332     } else if (FDisConst != NewFDisConst) {
7333       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7334           << NewFDisConst << FD->getSourceRange().getEnd();
7335     } else
7336       SemaRef.Diag(FD->getLocation(),
7337                    IsMember ? diag::note_member_def_close_match
7338                             : diag::note_local_decl_close_match);
7339   }
7340   return nullptr;
7341 }
7342 
7343 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7344   switch (D.getDeclSpec().getStorageClassSpec()) {
7345   default: llvm_unreachable("Unknown storage class!");
7346   case DeclSpec::SCS_auto:
7347   case DeclSpec::SCS_register:
7348   case DeclSpec::SCS_mutable:
7349     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7350                  diag::err_typecheck_sclass_func);
7351     D.setInvalidType();
7352     break;
7353   case DeclSpec::SCS_unspecified: break;
7354   case DeclSpec::SCS_extern:
7355     if (D.getDeclSpec().isExternInLinkageSpec())
7356       return SC_None;
7357     return SC_Extern;
7358   case DeclSpec::SCS_static: {
7359     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7360       // C99 6.7.1p5:
7361       //   The declaration of an identifier for a function that has
7362       //   block scope shall have no explicit storage-class specifier
7363       //   other than extern
7364       // See also (C++ [dcl.stc]p4).
7365       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7366                    diag::err_static_block_func);
7367       break;
7368     } else
7369       return SC_Static;
7370   }
7371   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7372   }
7373 
7374   // No explicit storage class has already been returned
7375   return SC_None;
7376 }
7377 
7378 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7379                                            DeclContext *DC, QualType &R,
7380                                            TypeSourceInfo *TInfo,
7381                                            StorageClass SC,
7382                                            bool &IsVirtualOkay) {
7383   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7384   DeclarationName Name = NameInfo.getName();
7385 
7386   FunctionDecl *NewFD = nullptr;
7387   bool isInline = D.getDeclSpec().isInlineSpecified();
7388 
7389   if (!SemaRef.getLangOpts().CPlusPlus) {
7390     // Determine whether the function was written with a
7391     // prototype. This true when:
7392     //   - there is a prototype in the declarator, or
7393     //   - the type R of the function is some kind of typedef or other reference
7394     //     to a type name (which eventually refers to a function type).
7395     bool HasPrototype =
7396       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7397       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7398 
7399     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7400                                  D.getLocStart(), NameInfo, R,
7401                                  TInfo, SC, isInline,
7402                                  HasPrototype, false);
7403     if (D.isInvalidType())
7404       NewFD->setInvalidDecl();
7405 
7406     return NewFD;
7407   }
7408 
7409   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7410   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7411 
7412   // Check that the return type is not an abstract class type.
7413   // For record types, this is done by the AbstractClassUsageDiagnoser once
7414   // the class has been completely parsed.
7415   if (!DC->isRecord() &&
7416       SemaRef.RequireNonAbstractType(
7417           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7418           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7419     D.setInvalidType();
7420 
7421   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7422     // This is a C++ constructor declaration.
7423     assert(DC->isRecord() &&
7424            "Constructors can only be declared in a member context");
7425 
7426     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7427     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7428                                       D.getLocStart(), NameInfo,
7429                                       R, TInfo, isExplicit, isInline,
7430                                       /*isImplicitlyDeclared=*/false,
7431                                       isConstexpr);
7432 
7433   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7434     // This is a C++ destructor declaration.
7435     if (DC->isRecord()) {
7436       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7437       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7438       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7439                                         SemaRef.Context, Record,
7440                                         D.getLocStart(),
7441                                         NameInfo, R, TInfo, isInline,
7442                                         /*isImplicitlyDeclared=*/false);
7443 
7444       // If the class is complete, then we now create the implicit exception
7445       // specification. If the class is incomplete or dependent, we can't do
7446       // it yet.
7447       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7448           Record->getDefinition() && !Record->isBeingDefined() &&
7449           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7450         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7451       }
7452 
7453       IsVirtualOkay = true;
7454       return NewDD;
7455 
7456     } else {
7457       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7458       D.setInvalidType();
7459 
7460       // Create a FunctionDecl to satisfy the function definition parsing
7461       // code path.
7462       return FunctionDecl::Create(SemaRef.Context, DC,
7463                                   D.getLocStart(),
7464                                   D.getIdentifierLoc(), Name, R, TInfo,
7465                                   SC, isInline,
7466                                   /*hasPrototype=*/true, isConstexpr);
7467     }
7468 
7469   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7470     if (!DC->isRecord()) {
7471       SemaRef.Diag(D.getIdentifierLoc(),
7472            diag::err_conv_function_not_member);
7473       return nullptr;
7474     }
7475 
7476     SemaRef.CheckConversionDeclarator(D, R, SC);
7477     IsVirtualOkay = true;
7478     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7479                                      D.getLocStart(), NameInfo,
7480                                      R, TInfo, isInline, isExplicit,
7481                                      isConstexpr, SourceLocation());
7482 
7483   } else if (DC->isRecord()) {
7484     // If the name of the function is the same as the name of the record,
7485     // then this must be an invalid constructor that has a return type.
7486     // (The parser checks for a return type and makes the declarator a
7487     // constructor if it has no return type).
7488     if (Name.getAsIdentifierInfo() &&
7489         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7490       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7491         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7492         << SourceRange(D.getIdentifierLoc());
7493       return nullptr;
7494     }
7495 
7496     // This is a C++ method declaration.
7497     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7498                                                cast<CXXRecordDecl>(DC),
7499                                                D.getLocStart(), NameInfo, R,
7500                                                TInfo, SC, isInline,
7501                                                isConstexpr, SourceLocation());
7502     IsVirtualOkay = !Ret->isStatic();
7503     return Ret;
7504   } else {
7505     bool isFriend =
7506         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7507     if (!isFriend && SemaRef.CurContext->isRecord())
7508       return nullptr;
7509 
7510     // Determine whether the function was written with a
7511     // prototype. This true when:
7512     //   - we're in C++ (where every function has a prototype),
7513     return FunctionDecl::Create(SemaRef.Context, DC,
7514                                 D.getLocStart(),
7515                                 NameInfo, R, TInfo, SC, isInline,
7516                                 true/*HasPrototype*/, isConstexpr);
7517   }
7518 }
7519 
7520 enum OpenCLParamType {
7521   ValidKernelParam,
7522   PtrPtrKernelParam,
7523   PtrKernelParam,
7524   PrivatePtrKernelParam,
7525   InvalidKernelParam,
7526   RecordKernelParam
7527 };
7528 
7529 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7530   if (PT->isPointerType()) {
7531     QualType PointeeType = PT->getPointeeType();
7532     if (PointeeType->isPointerType())
7533       return PtrPtrKernelParam;
7534     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7535                                               : PtrKernelParam;
7536   }
7537 
7538   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7539   // be used as builtin types.
7540 
7541   if (PT->isImageType())
7542     return PtrKernelParam;
7543 
7544   if (PT->isBooleanType())
7545     return InvalidKernelParam;
7546 
7547   if (PT->isEventT())
7548     return InvalidKernelParam;
7549 
7550   // OpenCL extension spec v1.2 s9.5:
7551   // This extension adds support for half scalar and vector types as built-in
7552   // types that can be used for arithmetic operations, conversions etc.
7553   if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType())
7554     return InvalidKernelParam;
7555 
7556   if (PT->isRecordType())
7557     return RecordKernelParam;
7558 
7559   return ValidKernelParam;
7560 }
7561 
7562 static void checkIsValidOpenCLKernelParameter(
7563   Sema &S,
7564   Declarator &D,
7565   ParmVarDecl *Param,
7566   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7567   QualType PT = Param->getType();
7568 
7569   // Cache the valid types we encounter to avoid rechecking structs that are
7570   // used again
7571   if (ValidTypes.count(PT.getTypePtr()))
7572     return;
7573 
7574   switch (getOpenCLKernelParameterType(S, PT)) {
7575   case PtrPtrKernelParam:
7576     // OpenCL v1.2 s6.9.a:
7577     // A kernel function argument cannot be declared as a
7578     // pointer to a pointer type.
7579     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7580     D.setInvalidType();
7581     return;
7582 
7583   case PrivatePtrKernelParam:
7584     // OpenCL v1.2 s6.9.a:
7585     // A kernel function argument cannot be declared as a
7586     // pointer to the private address space.
7587     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7588     D.setInvalidType();
7589     return;
7590 
7591     // OpenCL v1.2 s6.9.k:
7592     // Arguments to kernel functions in a program cannot be declared with the
7593     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7594     // uintptr_t or a struct and/or union that contain fields declared to be
7595     // one of these built-in scalar types.
7596 
7597   case InvalidKernelParam:
7598     // OpenCL v1.2 s6.8 n:
7599     // A kernel function argument cannot be declared
7600     // of event_t type.
7601     // Do not diagnose half type since it is diagnosed as invalid argument
7602     // type for any function elsewhere.
7603     if (!PT->isHalfType())
7604       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7605     D.setInvalidType();
7606     return;
7607 
7608   case PtrKernelParam:
7609   case ValidKernelParam:
7610     ValidTypes.insert(PT.getTypePtr());
7611     return;
7612 
7613   case RecordKernelParam:
7614     break;
7615   }
7616 
7617   // Track nested structs we will inspect
7618   SmallVector<const Decl *, 4> VisitStack;
7619 
7620   // Track where we are in the nested structs. Items will migrate from
7621   // VisitStack to HistoryStack as we do the DFS for bad field.
7622   SmallVector<const FieldDecl *, 4> HistoryStack;
7623   HistoryStack.push_back(nullptr);
7624 
7625   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7626   VisitStack.push_back(PD);
7627 
7628   assert(VisitStack.back() && "First decl null?");
7629 
7630   do {
7631     const Decl *Next = VisitStack.pop_back_val();
7632     if (!Next) {
7633       assert(!HistoryStack.empty());
7634       // Found a marker, we have gone up a level
7635       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7636         ValidTypes.insert(Hist->getType().getTypePtr());
7637 
7638       continue;
7639     }
7640 
7641     // Adds everything except the original parameter declaration (which is not a
7642     // field itself) to the history stack.
7643     const RecordDecl *RD;
7644     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7645       HistoryStack.push_back(Field);
7646       RD = Field->getType()->castAs<RecordType>()->getDecl();
7647     } else {
7648       RD = cast<RecordDecl>(Next);
7649     }
7650 
7651     // Add a null marker so we know when we've gone back up a level
7652     VisitStack.push_back(nullptr);
7653 
7654     for (const auto *FD : RD->fields()) {
7655       QualType QT = FD->getType();
7656 
7657       if (ValidTypes.count(QT.getTypePtr()))
7658         continue;
7659 
7660       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7661       if (ParamType == ValidKernelParam)
7662         continue;
7663 
7664       if (ParamType == RecordKernelParam) {
7665         VisitStack.push_back(FD);
7666         continue;
7667       }
7668 
7669       // OpenCL v1.2 s6.9.p:
7670       // Arguments to kernel functions that are declared to be a struct or union
7671       // do not allow OpenCL objects to be passed as elements of the struct or
7672       // union.
7673       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7674           ParamType == PrivatePtrKernelParam) {
7675         S.Diag(Param->getLocation(),
7676                diag::err_record_with_pointers_kernel_param)
7677           << PT->isUnionType()
7678           << PT;
7679       } else {
7680         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7681       }
7682 
7683       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7684         << PD->getDeclName();
7685 
7686       // We have an error, now let's go back up through history and show where
7687       // the offending field came from
7688       for (ArrayRef<const FieldDecl *>::const_iterator
7689                I = HistoryStack.begin() + 1,
7690                E = HistoryStack.end();
7691            I != E; ++I) {
7692         const FieldDecl *OuterField = *I;
7693         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7694           << OuterField->getType();
7695       }
7696 
7697       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7698         << QT->isPointerType()
7699         << QT;
7700       D.setInvalidType();
7701       return;
7702     }
7703   } while (!VisitStack.empty());
7704 }
7705 
7706 NamedDecl*
7707 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7708                               TypeSourceInfo *TInfo, LookupResult &Previous,
7709                               MultiTemplateParamsArg TemplateParamLists,
7710                               bool &AddToScope) {
7711   QualType R = TInfo->getType();
7712 
7713   assert(R.getTypePtr()->isFunctionType());
7714 
7715   // TODO: consider using NameInfo for diagnostic.
7716   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7717   DeclarationName Name = NameInfo.getName();
7718   StorageClass SC = getFunctionStorageClass(*this, D);
7719 
7720   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7721     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7722          diag::err_invalid_thread)
7723       << DeclSpec::getSpecifierName(TSCS);
7724 
7725   if (D.isFirstDeclarationOfMember())
7726     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7727                            D.getIdentifierLoc());
7728 
7729   bool isFriend = false;
7730   FunctionTemplateDecl *FunctionTemplate = nullptr;
7731   bool isExplicitSpecialization = false;
7732   bool isFunctionTemplateSpecialization = false;
7733 
7734   bool isDependentClassScopeExplicitSpecialization = false;
7735   bool HasExplicitTemplateArgs = false;
7736   TemplateArgumentListInfo TemplateArgs;
7737 
7738   bool isVirtualOkay = false;
7739 
7740   DeclContext *OriginalDC = DC;
7741   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7742 
7743   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7744                                               isVirtualOkay);
7745   if (!NewFD) return nullptr;
7746 
7747   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7748     NewFD->setTopLevelDeclInObjCContainer();
7749 
7750   // Set the lexical context. If this is a function-scope declaration, or has a
7751   // C++ scope specifier, or is the object of a friend declaration, the lexical
7752   // context will be different from the semantic context.
7753   NewFD->setLexicalDeclContext(CurContext);
7754 
7755   if (IsLocalExternDecl)
7756     NewFD->setLocalExternDecl();
7757 
7758   if (getLangOpts().CPlusPlus) {
7759     bool isInline = D.getDeclSpec().isInlineSpecified();
7760     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7761     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7762     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7763     bool isConcept = D.getDeclSpec().isConceptSpecified();
7764     isFriend = D.getDeclSpec().isFriendSpecified();
7765     if (isFriend && !isInline && D.isFunctionDefinition()) {
7766       // C++ [class.friend]p5
7767       //   A function can be defined in a friend declaration of a
7768       //   class . . . . Such a function is implicitly inline.
7769       NewFD->setImplicitlyInline();
7770     }
7771 
7772     // If this is a method defined in an __interface, and is not a constructor
7773     // or an overloaded operator, then set the pure flag (isVirtual will already
7774     // return true).
7775     if (const CXXRecordDecl *Parent =
7776           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7777       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7778         NewFD->setPure(true);
7779 
7780       // C++ [class.union]p2
7781       //   A union can have member functions, but not virtual functions.
7782       if (isVirtual && Parent->isUnion())
7783         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7784     }
7785 
7786     SetNestedNameSpecifier(NewFD, D);
7787     isExplicitSpecialization = false;
7788     isFunctionTemplateSpecialization = false;
7789     if (D.isInvalidType())
7790       NewFD->setInvalidDecl();
7791 
7792     // Match up the template parameter lists with the scope specifier, then
7793     // determine whether we have a template or a template specialization.
7794     bool Invalid = false;
7795     if (TemplateParameterList *TemplateParams =
7796             MatchTemplateParametersToScopeSpecifier(
7797                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7798                 D.getCXXScopeSpec(),
7799                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7800                     ? D.getName().TemplateId
7801                     : nullptr,
7802                 TemplateParamLists, isFriend, isExplicitSpecialization,
7803                 Invalid)) {
7804       if (TemplateParams->size() > 0) {
7805         // This is a function template
7806 
7807         // Check that we can declare a template here.
7808         if (CheckTemplateDeclScope(S, TemplateParams))
7809           NewFD->setInvalidDecl();
7810 
7811         // A destructor cannot be a template.
7812         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7813           Diag(NewFD->getLocation(), diag::err_destructor_template);
7814           NewFD->setInvalidDecl();
7815         }
7816 
7817         // If we're adding a template to a dependent context, we may need to
7818         // rebuilding some of the types used within the template parameter list,
7819         // now that we know what the current instantiation is.
7820         if (DC->isDependentContext()) {
7821           ContextRAII SavedContext(*this, DC);
7822           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7823             Invalid = true;
7824         }
7825 
7826         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7827                                                         NewFD->getLocation(),
7828                                                         Name, TemplateParams,
7829                                                         NewFD);
7830         FunctionTemplate->setLexicalDeclContext(CurContext);
7831         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7832 
7833         // For source fidelity, store the other template param lists.
7834         if (TemplateParamLists.size() > 1) {
7835           NewFD->setTemplateParameterListsInfo(Context,
7836                                                TemplateParamLists.drop_back(1));
7837         }
7838       } else {
7839         // This is a function template specialization.
7840         isFunctionTemplateSpecialization = true;
7841         // For source fidelity, store all the template param lists.
7842         if (TemplateParamLists.size() > 0)
7843           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7844 
7845         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7846         if (isFriend) {
7847           // We want to remove the "template<>", found here.
7848           SourceRange RemoveRange = TemplateParams->getSourceRange();
7849 
7850           // If we remove the template<> and the name is not a
7851           // template-id, we're actually silently creating a problem:
7852           // the friend declaration will refer to an untemplated decl,
7853           // and clearly the user wants a template specialization.  So
7854           // we need to insert '<>' after the name.
7855           SourceLocation InsertLoc;
7856           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7857             InsertLoc = D.getName().getSourceRange().getEnd();
7858             InsertLoc = getLocForEndOfToken(InsertLoc);
7859           }
7860 
7861           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7862             << Name << RemoveRange
7863             << FixItHint::CreateRemoval(RemoveRange)
7864             << FixItHint::CreateInsertion(InsertLoc, "<>");
7865         }
7866       }
7867     }
7868     else {
7869       // All template param lists were matched against the scope specifier:
7870       // this is NOT (an explicit specialization of) a template.
7871       if (TemplateParamLists.size() > 0)
7872         // For source fidelity, store all the template param lists.
7873         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7874     }
7875 
7876     if (Invalid) {
7877       NewFD->setInvalidDecl();
7878       if (FunctionTemplate)
7879         FunctionTemplate->setInvalidDecl();
7880     }
7881 
7882     // C++ [dcl.fct.spec]p5:
7883     //   The virtual specifier shall only be used in declarations of
7884     //   nonstatic class member functions that appear within a
7885     //   member-specification of a class declaration; see 10.3.
7886     //
7887     if (isVirtual && !NewFD->isInvalidDecl()) {
7888       if (!isVirtualOkay) {
7889         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7890              diag::err_virtual_non_function);
7891       } else if (!CurContext->isRecord()) {
7892         // 'virtual' was specified outside of the class.
7893         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7894              diag::err_virtual_out_of_class)
7895           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7896       } else if (NewFD->getDescribedFunctionTemplate()) {
7897         // C++ [temp.mem]p3:
7898         //  A member function template shall not be virtual.
7899         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7900              diag::err_virtual_member_function_template)
7901           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7902       } else {
7903         // Okay: Add virtual to the method.
7904         NewFD->setVirtualAsWritten(true);
7905       }
7906 
7907       if (getLangOpts().CPlusPlus14 &&
7908           NewFD->getReturnType()->isUndeducedType())
7909         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7910     }
7911 
7912     if (getLangOpts().CPlusPlus14 &&
7913         (NewFD->isDependentContext() ||
7914          (isFriend && CurContext->isDependentContext())) &&
7915         NewFD->getReturnType()->isUndeducedType()) {
7916       // If the function template is referenced directly (for instance, as a
7917       // member of the current instantiation), pretend it has a dependent type.
7918       // This is not really justified by the standard, but is the only sane
7919       // thing to do.
7920       // FIXME: For a friend function, we have not marked the function as being
7921       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7922       const FunctionProtoType *FPT =
7923           NewFD->getType()->castAs<FunctionProtoType>();
7924       QualType Result =
7925           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7926       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7927                                              FPT->getExtProtoInfo()));
7928     }
7929 
7930     // C++ [dcl.fct.spec]p3:
7931     //  The inline specifier shall not appear on a block scope function
7932     //  declaration.
7933     if (isInline && !NewFD->isInvalidDecl()) {
7934       if (CurContext->isFunctionOrMethod()) {
7935         // 'inline' is not allowed on block scope function declaration.
7936         Diag(D.getDeclSpec().getInlineSpecLoc(),
7937              diag::err_inline_declaration_block_scope) << Name
7938           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7939       }
7940     }
7941 
7942     // C++ [dcl.fct.spec]p6:
7943     //  The explicit specifier shall be used only in the declaration of a
7944     //  constructor or conversion function within its class definition;
7945     //  see 12.3.1 and 12.3.2.
7946     if (isExplicit && !NewFD->isInvalidDecl()) {
7947       if (!CurContext->isRecord()) {
7948         // 'explicit' was specified outside of the class.
7949         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7950              diag::err_explicit_out_of_class)
7951           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7952       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7953                  !isa<CXXConversionDecl>(NewFD)) {
7954         // 'explicit' was specified on a function that wasn't a constructor
7955         // or conversion function.
7956         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7957              diag::err_explicit_non_ctor_or_conv_function)
7958           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7959       }
7960     }
7961 
7962     if (isConstexpr) {
7963       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7964       // are implicitly inline.
7965       NewFD->setImplicitlyInline();
7966 
7967       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7968       // be either constructors or to return a literal type. Therefore,
7969       // destructors cannot be declared constexpr.
7970       if (isa<CXXDestructorDecl>(NewFD))
7971         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7972     }
7973 
7974     if (isConcept) {
7975       // This is a function concept.
7976       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7977         FTD->setConcept();
7978 
7979       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7980       // applied only to the definition of a function template [...]
7981       if (!D.isFunctionDefinition()) {
7982         Diag(D.getDeclSpec().getConceptSpecLoc(),
7983              diag::err_function_concept_not_defined);
7984         NewFD->setInvalidDecl();
7985       }
7986 
7987       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7988       // have no exception-specification and is treated as if it were specified
7989       // with noexcept(true) (15.4). [...]
7990       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7991         if (FPT->hasExceptionSpec()) {
7992           SourceRange Range;
7993           if (D.isFunctionDeclarator())
7994             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7995           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7996               << FixItHint::CreateRemoval(Range);
7997           NewFD->setInvalidDecl();
7998         } else {
7999           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8000         }
8001 
8002         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8003         // following restrictions:
8004         // - The declared return type shall have the type bool.
8005         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8006           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8007           NewFD->setInvalidDecl();
8008         }
8009 
8010         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8011         // following restrictions:
8012         // - The declaration's parameter list shall be equivalent to an empty
8013         //   parameter list.
8014         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8015           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8016       }
8017 
8018       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8019       // implicity defined to be a constexpr declaration (implicitly inline)
8020       NewFD->setImplicitlyInline();
8021 
8022       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8023       // be declared with the thread_local, inline, friend, or constexpr
8024       // specifiers, [...]
8025       if (isInline) {
8026         Diag(D.getDeclSpec().getInlineSpecLoc(),
8027              diag::err_concept_decl_invalid_specifiers)
8028             << 1 << 1;
8029         NewFD->setInvalidDecl(true);
8030       }
8031 
8032       if (isFriend) {
8033         Diag(D.getDeclSpec().getFriendSpecLoc(),
8034              diag::err_concept_decl_invalid_specifiers)
8035             << 1 << 2;
8036         NewFD->setInvalidDecl(true);
8037       }
8038 
8039       if (isConstexpr) {
8040         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8041              diag::err_concept_decl_invalid_specifiers)
8042             << 1 << 3;
8043         NewFD->setInvalidDecl(true);
8044       }
8045 
8046       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8047       // applied only to the definition of a function template or variable
8048       // template, declared in namespace scope.
8049       if (isFunctionTemplateSpecialization) {
8050         Diag(D.getDeclSpec().getConceptSpecLoc(),
8051              diag::err_concept_specified_specialization) << 1;
8052         NewFD->setInvalidDecl(true);
8053         return NewFD;
8054       }
8055     }
8056 
8057     // If __module_private__ was specified, mark the function accordingly.
8058     if (D.getDeclSpec().isModulePrivateSpecified()) {
8059       if (isFunctionTemplateSpecialization) {
8060         SourceLocation ModulePrivateLoc
8061           = D.getDeclSpec().getModulePrivateSpecLoc();
8062         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8063           << 0
8064           << FixItHint::CreateRemoval(ModulePrivateLoc);
8065       } else {
8066         NewFD->setModulePrivate();
8067         if (FunctionTemplate)
8068           FunctionTemplate->setModulePrivate();
8069       }
8070     }
8071 
8072     if (isFriend) {
8073       if (FunctionTemplate) {
8074         FunctionTemplate->setObjectOfFriendDecl();
8075         FunctionTemplate->setAccess(AS_public);
8076       }
8077       NewFD->setObjectOfFriendDecl();
8078       NewFD->setAccess(AS_public);
8079     }
8080 
8081     // If a function is defined as defaulted or deleted, mark it as such now.
8082     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8083     // definition kind to FDK_Definition.
8084     switch (D.getFunctionDefinitionKind()) {
8085       case FDK_Declaration:
8086       case FDK_Definition:
8087         break;
8088 
8089       case FDK_Defaulted:
8090         NewFD->setDefaulted();
8091         break;
8092 
8093       case FDK_Deleted:
8094         NewFD->setDeletedAsWritten();
8095         break;
8096     }
8097 
8098     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8099         D.isFunctionDefinition()) {
8100       // C++ [class.mfct]p2:
8101       //   A member function may be defined (8.4) in its class definition, in
8102       //   which case it is an inline member function (7.1.2)
8103       NewFD->setImplicitlyInline();
8104     }
8105 
8106     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8107         !CurContext->isRecord()) {
8108       // C++ [class.static]p1:
8109       //   A data or function member of a class may be declared static
8110       //   in a class definition, in which case it is a static member of
8111       //   the class.
8112 
8113       // Complain about the 'static' specifier if it's on an out-of-line
8114       // member function definition.
8115       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8116            diag::err_static_out_of_line)
8117         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8118     }
8119 
8120     // C++11 [except.spec]p15:
8121     //   A deallocation function with no exception-specification is treated
8122     //   as if it were specified with noexcept(true).
8123     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8124     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8125          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8126         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8127       NewFD->setType(Context.getFunctionType(
8128           FPT->getReturnType(), FPT->getParamTypes(),
8129           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8130   }
8131 
8132   // Filter out previous declarations that don't match the scope.
8133   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8134                        D.getCXXScopeSpec().isNotEmpty() ||
8135                        isExplicitSpecialization ||
8136                        isFunctionTemplateSpecialization);
8137 
8138   // Handle GNU asm-label extension (encoded as an attribute).
8139   if (Expr *E = (Expr*) D.getAsmLabel()) {
8140     // The parser guarantees this is a string.
8141     StringLiteral *SE = cast<StringLiteral>(E);
8142     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8143                                                 SE->getString(), 0));
8144   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8145     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8146       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8147     if (I != ExtnameUndeclaredIdentifiers.end()) {
8148       if (isDeclExternC(NewFD)) {
8149         NewFD->addAttr(I->second);
8150         ExtnameUndeclaredIdentifiers.erase(I);
8151       } else
8152         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8153             << /*Variable*/0 << NewFD;
8154     }
8155   }
8156 
8157   // Copy the parameter declarations from the declarator D to the function
8158   // declaration NewFD, if they are available.  First scavenge them into Params.
8159   SmallVector<ParmVarDecl*, 16> Params;
8160   if (D.isFunctionDeclarator()) {
8161     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8162 
8163     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8164     // function that takes no arguments, not a function that takes a
8165     // single void argument.
8166     // We let through "const void" here because Sema::GetTypeForDeclarator
8167     // already checks for that case.
8168     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8169       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8170         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8171         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8172         Param->setDeclContext(NewFD);
8173         Params.push_back(Param);
8174 
8175         if (Param->isInvalidDecl())
8176           NewFD->setInvalidDecl();
8177       }
8178     }
8179   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8180     // When we're declaring a function with a typedef, typeof, etc as in the
8181     // following example, we'll need to synthesize (unnamed)
8182     // parameters for use in the declaration.
8183     //
8184     // @code
8185     // typedef void fn(int);
8186     // fn f;
8187     // @endcode
8188 
8189     // Synthesize a parameter for each argument type.
8190     for (const auto &AI : FT->param_types()) {
8191       ParmVarDecl *Param =
8192           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8193       Param->setScopeInfo(0, Params.size());
8194       Params.push_back(Param);
8195     }
8196   } else {
8197     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8198            "Should not need args for typedef of non-prototype fn");
8199   }
8200 
8201   // Finally, we know we have the right number of parameters, install them.
8202   NewFD->setParams(Params);
8203 
8204   // Find all anonymous symbols defined during the declaration of this function
8205   // and add to NewFD. This lets us track decls such 'enum Y' in:
8206   //
8207   //   void f(enum Y {AA} x) {}
8208   //
8209   // which would otherwise incorrectly end up in the translation unit scope.
8210   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8211   DeclsInPrototypeScope.clear();
8212 
8213   if (D.getDeclSpec().isNoreturnSpecified())
8214     NewFD->addAttr(
8215         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8216                                        Context, 0));
8217 
8218   // Functions returning a variably modified type violate C99 6.7.5.2p2
8219   // because all functions have linkage.
8220   if (!NewFD->isInvalidDecl() &&
8221       NewFD->getReturnType()->isVariablyModifiedType()) {
8222     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8223     NewFD->setInvalidDecl();
8224   }
8225 
8226   // Apply an implicit SectionAttr if #pragma code_seg is active.
8227   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8228       !NewFD->hasAttr<SectionAttr>()) {
8229     NewFD->addAttr(
8230         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8231                                     CodeSegStack.CurrentValue->getString(),
8232                                     CodeSegStack.CurrentPragmaLocation));
8233     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8234                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8235                          ASTContext::PSF_Read,
8236                      NewFD))
8237       NewFD->dropAttr<SectionAttr>();
8238   }
8239 
8240   // Handle attributes.
8241   ProcessDeclAttributes(S, NewFD, D);
8242 
8243   if (getLangOpts().CUDA)
8244     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8245 
8246   if (getLangOpts().OpenCL) {
8247     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8248     // type declaration will generate a compilation error.
8249     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8250     if (AddressSpace == LangAS::opencl_local ||
8251         AddressSpace == LangAS::opencl_global ||
8252         AddressSpace == LangAS::opencl_constant) {
8253       Diag(NewFD->getLocation(),
8254            diag::err_opencl_return_value_with_address_space);
8255       NewFD->setInvalidDecl();
8256     }
8257   }
8258 
8259   if (!getLangOpts().CPlusPlus) {
8260     // Perform semantic checking on the function declaration.
8261     bool isExplicitSpecialization=false;
8262     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8263       CheckMain(NewFD, D.getDeclSpec());
8264 
8265     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8266       CheckMSVCRTEntryPoint(NewFD);
8267 
8268     if (!NewFD->isInvalidDecl())
8269       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8270                                                   isExplicitSpecialization));
8271     else if (!Previous.empty())
8272       // Recover gracefully from an invalid redeclaration.
8273       D.setRedeclaration(true);
8274     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8275             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8276            "previous declaration set still overloaded");
8277 
8278     // Diagnose no-prototype function declarations with calling conventions that
8279     // don't support variadic calls. Only do this in C and do it after merging
8280     // possibly prototyped redeclarations.
8281     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8282     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8283       CallingConv CC = FT->getExtInfo().getCC();
8284       if (!supportsVariadicCall(CC)) {
8285         // Windows system headers sometimes accidentally use stdcall without
8286         // (void) parameters, so we relax this to a warning.
8287         int DiagID =
8288             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8289         Diag(NewFD->getLocation(), DiagID)
8290             << FunctionType::getNameForCallConv(CC);
8291       }
8292     }
8293   } else {
8294     // C++11 [replacement.functions]p3:
8295     //  The program's definitions shall not be specified as inline.
8296     //
8297     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8298     //
8299     // Suppress the diagnostic if the function is __attribute__((used)), since
8300     // that forces an external definition to be emitted.
8301     if (D.getDeclSpec().isInlineSpecified() &&
8302         NewFD->isReplaceableGlobalAllocationFunction() &&
8303         !NewFD->hasAttr<UsedAttr>())
8304       Diag(D.getDeclSpec().getInlineSpecLoc(),
8305            diag::ext_operator_new_delete_declared_inline)
8306         << NewFD->getDeclName();
8307 
8308     // If the declarator is a template-id, translate the parser's template
8309     // argument list into our AST format.
8310     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8311       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8312       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8313       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8314       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8315                                          TemplateId->NumArgs);
8316       translateTemplateArguments(TemplateArgsPtr,
8317                                  TemplateArgs);
8318 
8319       HasExplicitTemplateArgs = true;
8320 
8321       if (NewFD->isInvalidDecl()) {
8322         HasExplicitTemplateArgs = false;
8323       } else if (FunctionTemplate) {
8324         // Function template with explicit template arguments.
8325         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8326           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8327 
8328         HasExplicitTemplateArgs = false;
8329       } else {
8330         assert((isFunctionTemplateSpecialization ||
8331                 D.getDeclSpec().isFriendSpecified()) &&
8332                "should have a 'template<>' for this decl");
8333         // "friend void foo<>(int);" is an implicit specialization decl.
8334         isFunctionTemplateSpecialization = true;
8335       }
8336     } else if (isFriend && isFunctionTemplateSpecialization) {
8337       // This combination is only possible in a recovery case;  the user
8338       // wrote something like:
8339       //   template <> friend void foo(int);
8340       // which we're recovering from as if the user had written:
8341       //   friend void foo<>(int);
8342       // Go ahead and fake up a template id.
8343       HasExplicitTemplateArgs = true;
8344       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8345       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8346     }
8347 
8348     // If it's a friend (and only if it's a friend), it's possible
8349     // that either the specialized function type or the specialized
8350     // template is dependent, and therefore matching will fail.  In
8351     // this case, don't check the specialization yet.
8352     bool InstantiationDependent = false;
8353     if (isFunctionTemplateSpecialization && isFriend &&
8354         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8355          TemplateSpecializationType::anyDependentTemplateArguments(
8356             TemplateArgs,
8357             InstantiationDependent))) {
8358       assert(HasExplicitTemplateArgs &&
8359              "friend function specialization without template args");
8360       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8361                                                        Previous))
8362         NewFD->setInvalidDecl();
8363     } else if (isFunctionTemplateSpecialization) {
8364       if (CurContext->isDependentContext() && CurContext->isRecord()
8365           && !isFriend) {
8366         isDependentClassScopeExplicitSpecialization = true;
8367         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8368           diag::ext_function_specialization_in_class :
8369           diag::err_function_specialization_in_class)
8370           << NewFD->getDeclName();
8371       } else if (CheckFunctionTemplateSpecialization(NewFD,
8372                                   (HasExplicitTemplateArgs ? &TemplateArgs
8373                                                            : nullptr),
8374                                                      Previous))
8375         NewFD->setInvalidDecl();
8376 
8377       // C++ [dcl.stc]p1:
8378       //   A storage-class-specifier shall not be specified in an explicit
8379       //   specialization (14.7.3)
8380       FunctionTemplateSpecializationInfo *Info =
8381           NewFD->getTemplateSpecializationInfo();
8382       if (Info && SC != SC_None) {
8383         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8384           Diag(NewFD->getLocation(),
8385                diag::err_explicit_specialization_inconsistent_storage_class)
8386             << SC
8387             << FixItHint::CreateRemoval(
8388                                       D.getDeclSpec().getStorageClassSpecLoc());
8389 
8390         else
8391           Diag(NewFD->getLocation(),
8392                diag::ext_explicit_specialization_storage_class)
8393             << FixItHint::CreateRemoval(
8394                                       D.getDeclSpec().getStorageClassSpecLoc());
8395       }
8396     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8397       if (CheckMemberSpecialization(NewFD, Previous))
8398           NewFD->setInvalidDecl();
8399     }
8400 
8401     // Perform semantic checking on the function declaration.
8402     if (!isDependentClassScopeExplicitSpecialization) {
8403       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8404         CheckMain(NewFD, D.getDeclSpec());
8405 
8406       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8407         CheckMSVCRTEntryPoint(NewFD);
8408 
8409       if (!NewFD->isInvalidDecl())
8410         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8411                                                     isExplicitSpecialization));
8412       else if (!Previous.empty())
8413         // Recover gracefully from an invalid redeclaration.
8414         D.setRedeclaration(true);
8415     }
8416 
8417     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8418             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8419            "previous declaration set still overloaded");
8420 
8421     NamedDecl *PrincipalDecl = (FunctionTemplate
8422                                 ? cast<NamedDecl>(FunctionTemplate)
8423                                 : NewFD);
8424 
8425     if (isFriend && D.isRedeclaration()) {
8426       AccessSpecifier Access = AS_public;
8427       if (!NewFD->isInvalidDecl())
8428         Access = NewFD->getPreviousDecl()->getAccess();
8429 
8430       NewFD->setAccess(Access);
8431       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8432     }
8433 
8434     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8435         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8436       PrincipalDecl->setNonMemberOperator();
8437 
8438     // If we have a function template, check the template parameter
8439     // list. This will check and merge default template arguments.
8440     if (FunctionTemplate) {
8441       FunctionTemplateDecl *PrevTemplate =
8442                                      FunctionTemplate->getPreviousDecl();
8443       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8444                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8445                                     : nullptr,
8446                             D.getDeclSpec().isFriendSpecified()
8447                               ? (D.isFunctionDefinition()
8448                                    ? TPC_FriendFunctionTemplateDefinition
8449                                    : TPC_FriendFunctionTemplate)
8450                               : (D.getCXXScopeSpec().isSet() &&
8451                                  DC && DC->isRecord() &&
8452                                  DC->isDependentContext())
8453                                   ? TPC_ClassTemplateMember
8454                                   : TPC_FunctionTemplate);
8455     }
8456 
8457     if (NewFD->isInvalidDecl()) {
8458       // Ignore all the rest of this.
8459     } else if (!D.isRedeclaration()) {
8460       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8461                                        AddToScope };
8462       // Fake up an access specifier if it's supposed to be a class member.
8463       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8464         NewFD->setAccess(AS_public);
8465 
8466       // Qualified decls generally require a previous declaration.
8467       if (D.getCXXScopeSpec().isSet()) {
8468         // ...with the major exception of templated-scope or
8469         // dependent-scope friend declarations.
8470 
8471         // TODO: we currently also suppress this check in dependent
8472         // contexts because (1) the parameter depth will be off when
8473         // matching friend templates and (2) we might actually be
8474         // selecting a friend based on a dependent factor.  But there
8475         // are situations where these conditions don't apply and we
8476         // can actually do this check immediately.
8477         if (isFriend &&
8478             (TemplateParamLists.size() ||
8479              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8480              CurContext->isDependentContext())) {
8481           // ignore these
8482         } else {
8483           // The user tried to provide an out-of-line definition for a
8484           // function that is a member of a class or namespace, but there
8485           // was no such member function declared (C++ [class.mfct]p2,
8486           // C++ [namespace.memdef]p2). For example:
8487           //
8488           // class X {
8489           //   void f() const;
8490           // };
8491           //
8492           // void X::f() { } // ill-formed
8493           //
8494           // Complain about this problem, and attempt to suggest close
8495           // matches (e.g., those that differ only in cv-qualifiers and
8496           // whether the parameter types are references).
8497 
8498           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8499                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8500             AddToScope = ExtraArgs.AddToScope;
8501             return Result;
8502           }
8503         }
8504 
8505         // Unqualified local friend declarations are required to resolve
8506         // to something.
8507       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8508         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8509                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8510           AddToScope = ExtraArgs.AddToScope;
8511           return Result;
8512         }
8513       }
8514     } else if (!D.isFunctionDefinition() &&
8515                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8516                !isFriend && !isFunctionTemplateSpecialization &&
8517                !isExplicitSpecialization) {
8518       // An out-of-line member function declaration must also be a
8519       // definition (C++ [class.mfct]p2).
8520       // Note that this is not the case for explicit specializations of
8521       // function templates or member functions of class templates, per
8522       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8523       // extension for compatibility with old SWIG code which likes to
8524       // generate them.
8525       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8526         << D.getCXXScopeSpec().getRange();
8527     }
8528   }
8529 
8530   ProcessPragmaWeak(S, NewFD);
8531   checkAttributesAfterMerging(*this, *NewFD);
8532 
8533   AddKnownFunctionAttributes(NewFD);
8534 
8535   if (NewFD->hasAttr<OverloadableAttr>() &&
8536       !NewFD->getType()->getAs<FunctionProtoType>()) {
8537     Diag(NewFD->getLocation(),
8538          diag::err_attribute_overloadable_no_prototype)
8539       << NewFD;
8540 
8541     // Turn this into a variadic function with no parameters.
8542     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8543     FunctionProtoType::ExtProtoInfo EPI(
8544         Context.getDefaultCallingConvention(true, false));
8545     EPI.Variadic = true;
8546     EPI.ExtInfo = FT->getExtInfo();
8547 
8548     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8549     NewFD->setType(R);
8550   }
8551 
8552   // If there's a #pragma GCC visibility in scope, and this isn't a class
8553   // member, set the visibility of this function.
8554   if (!DC->isRecord() && NewFD->isExternallyVisible())
8555     AddPushedVisibilityAttribute(NewFD);
8556 
8557   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8558   // marking the function.
8559   AddCFAuditedAttribute(NewFD);
8560 
8561   // If this is a function definition, check if we have to apply optnone due to
8562   // a pragma.
8563   if(D.isFunctionDefinition())
8564     AddRangeBasedOptnone(NewFD);
8565 
8566   // If this is the first declaration of an extern C variable, update
8567   // the map of such variables.
8568   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8569       isIncompleteDeclExternC(*this, NewFD))
8570     RegisterLocallyScopedExternCDecl(NewFD, S);
8571 
8572   // Set this FunctionDecl's range up to the right paren.
8573   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8574 
8575   if (D.isRedeclaration() && !Previous.empty()) {
8576     checkDLLAttributeRedeclaration(
8577         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8578         isExplicitSpecialization || isFunctionTemplateSpecialization,
8579         D.isFunctionDefinition());
8580   }
8581 
8582   if (getLangOpts().CUDA) {
8583     IdentifierInfo *II = NewFD->getIdentifier();
8584     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8585         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8586       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8587         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8588 
8589       Context.setcudaConfigureCallDecl(NewFD);
8590     }
8591 
8592     // Variadic functions, other than a *declaration* of printf, are not allowed
8593     // in device-side CUDA code, unless someone passed
8594     // -fcuda-allow-variadic-functions.
8595     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8596         (NewFD->hasAttr<CUDADeviceAttr>() ||
8597          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8598         !(II && II->isStr("printf") && NewFD->isExternC() &&
8599           !D.isFunctionDefinition())) {
8600       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8601     }
8602   }
8603 
8604   if (getLangOpts().CPlusPlus) {
8605     if (FunctionTemplate) {
8606       if (NewFD->isInvalidDecl())
8607         FunctionTemplate->setInvalidDecl();
8608       return FunctionTemplate;
8609     }
8610   }
8611 
8612   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8613     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8614     if ((getLangOpts().OpenCLVersion >= 120)
8615         && (SC == SC_Static)) {
8616       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8617       D.setInvalidType();
8618     }
8619 
8620     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8621     if (!NewFD->getReturnType()->isVoidType()) {
8622       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8623       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8624           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8625                                 : FixItHint());
8626       D.setInvalidType();
8627     }
8628 
8629     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8630     for (auto Param : NewFD->parameters())
8631       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8632   }
8633   for (const ParmVarDecl *Param : NewFD->parameters()) {
8634     QualType PT = Param->getType();
8635 
8636     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8637     // types.
8638     if (getLangOpts().OpenCLVersion >= 200) {
8639       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8640         QualType ElemTy = PipeTy->getElementType();
8641           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8642             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8643             D.setInvalidType();
8644           }
8645       }
8646     }
8647   }
8648 
8649   MarkUnusedFileScopedDecl(NewFD);
8650 
8651   // Here we have an function template explicit specialization at class scope.
8652   // The actually specialization will be postponed to template instatiation
8653   // time via the ClassScopeFunctionSpecializationDecl node.
8654   if (isDependentClassScopeExplicitSpecialization) {
8655     ClassScopeFunctionSpecializationDecl *NewSpec =
8656                          ClassScopeFunctionSpecializationDecl::Create(
8657                                 Context, CurContext, SourceLocation(),
8658                                 cast<CXXMethodDecl>(NewFD),
8659                                 HasExplicitTemplateArgs, TemplateArgs);
8660     CurContext->addDecl(NewSpec);
8661     AddToScope = false;
8662   }
8663 
8664   return NewFD;
8665 }
8666 
8667 /// \brief Checks if the new declaration declared in dependent context must be
8668 /// put in the same redeclaration chain as the specified declaration.
8669 ///
8670 /// \param D Declaration that is checked.
8671 /// \param PrevDecl Previous declaration found with proper lookup method for the
8672 ///                 same declaration name.
8673 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8674 ///          belongs to.
8675 ///
8676 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8677   // Any declarations should be put into redeclaration chains except for
8678   // friend declaration in a dependent context that names a function in
8679   // namespace scope.
8680   //
8681   // This allows to compile code like:
8682   //
8683   //       void func();
8684   //       template<typename T> class C1 { friend void func() { } };
8685   //       template<typename T> class C2 { friend void func() { } };
8686   //
8687   // This code snippet is a valid code unless both templates are instantiated.
8688   return !(D->getLexicalDeclContext()->isDependentContext() &&
8689            D->getDeclContext()->isFileContext() &&
8690            D->getFriendObjectKind() != Decl::FOK_None);
8691 }
8692 
8693 /// \brief Perform semantic checking of a new function declaration.
8694 ///
8695 /// Performs semantic analysis of the new function declaration
8696 /// NewFD. This routine performs all semantic checking that does not
8697 /// require the actual declarator involved in the declaration, and is
8698 /// used both for the declaration of functions as they are parsed
8699 /// (called via ActOnDeclarator) and for the declaration of functions
8700 /// that have been instantiated via C++ template instantiation (called
8701 /// via InstantiateDecl).
8702 ///
8703 /// \param IsExplicitSpecialization whether this new function declaration is
8704 /// an explicit specialization of the previous declaration.
8705 ///
8706 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8707 ///
8708 /// \returns true if the function declaration is a redeclaration.
8709 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8710                                     LookupResult &Previous,
8711                                     bool IsExplicitSpecialization) {
8712   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8713          "Variably modified return types are not handled here");
8714 
8715   // Determine whether the type of this function should be merged with
8716   // a previous visible declaration. This never happens for functions in C++,
8717   // and always happens in C if the previous declaration was visible.
8718   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8719                                !Previous.isShadowed();
8720 
8721   bool Redeclaration = false;
8722   NamedDecl *OldDecl = nullptr;
8723 
8724   // Merge or overload the declaration with an existing declaration of
8725   // the same name, if appropriate.
8726   if (!Previous.empty()) {
8727     // Determine whether NewFD is an overload of PrevDecl or
8728     // a declaration that requires merging. If it's an overload,
8729     // there's no more work to do here; we'll just add the new
8730     // function to the scope.
8731     if (!AllowOverloadingOfFunction(Previous, Context)) {
8732       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8733       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8734         Redeclaration = true;
8735         OldDecl = Candidate;
8736       }
8737     } else {
8738       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8739                             /*NewIsUsingDecl*/ false)) {
8740       case Ovl_Match:
8741         Redeclaration = true;
8742         break;
8743 
8744       case Ovl_NonFunction:
8745         Redeclaration = true;
8746         break;
8747 
8748       case Ovl_Overload:
8749         Redeclaration = false;
8750         break;
8751       }
8752 
8753       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8754         // If a function name is overloadable in C, then every function
8755         // with that name must be marked "overloadable".
8756         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8757           << Redeclaration << NewFD;
8758         NamedDecl *OverloadedDecl = nullptr;
8759         if (Redeclaration)
8760           OverloadedDecl = OldDecl;
8761         else if (!Previous.empty())
8762           OverloadedDecl = Previous.getRepresentativeDecl();
8763         if (OverloadedDecl)
8764           Diag(OverloadedDecl->getLocation(),
8765                diag::note_attribute_overloadable_prev_overload);
8766         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8767       }
8768     }
8769   }
8770 
8771   // Check for a previous extern "C" declaration with this name.
8772   if (!Redeclaration &&
8773       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8774     if (!Previous.empty()) {
8775       // This is an extern "C" declaration with the same name as a previous
8776       // declaration, and thus redeclares that entity...
8777       Redeclaration = true;
8778       OldDecl = Previous.getFoundDecl();
8779       MergeTypeWithPrevious = false;
8780 
8781       // ... except in the presence of __attribute__((overloadable)).
8782       if (OldDecl->hasAttr<OverloadableAttr>()) {
8783         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8784           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8785             << Redeclaration << NewFD;
8786           Diag(Previous.getFoundDecl()->getLocation(),
8787                diag::note_attribute_overloadable_prev_overload);
8788           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8789         }
8790         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8791           Redeclaration = false;
8792           OldDecl = nullptr;
8793         }
8794       }
8795     }
8796   }
8797 
8798   // C++11 [dcl.constexpr]p8:
8799   //   A constexpr specifier for a non-static member function that is not
8800   //   a constructor declares that member function to be const.
8801   //
8802   // This needs to be delayed until we know whether this is an out-of-line
8803   // definition of a static member function.
8804   //
8805   // This rule is not present in C++1y, so we produce a backwards
8806   // compatibility warning whenever it happens in C++11.
8807   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8808   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8809       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8810       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8811     CXXMethodDecl *OldMD = nullptr;
8812     if (OldDecl)
8813       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8814     if (!OldMD || !OldMD->isStatic()) {
8815       const FunctionProtoType *FPT =
8816         MD->getType()->castAs<FunctionProtoType>();
8817       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8818       EPI.TypeQuals |= Qualifiers::Const;
8819       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8820                                           FPT->getParamTypes(), EPI));
8821 
8822       // Warn that we did this, if we're not performing template instantiation.
8823       // In that case, we'll have warned already when the template was defined.
8824       if (ActiveTemplateInstantiations.empty()) {
8825         SourceLocation AddConstLoc;
8826         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8827                 .IgnoreParens().getAs<FunctionTypeLoc>())
8828           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8829 
8830         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8831           << FixItHint::CreateInsertion(AddConstLoc, " const");
8832       }
8833     }
8834   }
8835 
8836   if (Redeclaration) {
8837     // NewFD and OldDecl represent declarations that need to be
8838     // merged.
8839     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8840       NewFD->setInvalidDecl();
8841       return Redeclaration;
8842     }
8843 
8844     Previous.clear();
8845     Previous.addDecl(OldDecl);
8846 
8847     if (FunctionTemplateDecl *OldTemplateDecl
8848                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8849       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8850       FunctionTemplateDecl *NewTemplateDecl
8851         = NewFD->getDescribedFunctionTemplate();
8852       assert(NewTemplateDecl && "Template/non-template mismatch");
8853       if (CXXMethodDecl *Method
8854             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8855         Method->setAccess(OldTemplateDecl->getAccess());
8856         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8857       }
8858 
8859       // If this is an explicit specialization of a member that is a function
8860       // template, mark it as a member specialization.
8861       if (IsExplicitSpecialization &&
8862           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8863         NewTemplateDecl->setMemberSpecialization();
8864         assert(OldTemplateDecl->isMemberSpecialization());
8865         // Explicit specializations of a member template do not inherit deleted
8866         // status from the parent member template that they are specializing.
8867         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8868           FunctionDecl *const OldTemplatedDecl =
8869               OldTemplateDecl->getTemplatedDecl();
8870           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8871           OldTemplatedDecl->setDeletedAsWritten(false);
8872         }
8873       }
8874 
8875     } else {
8876       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
8877         // This needs to happen first so that 'inline' propagates.
8878         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8879         if (isa<CXXMethodDecl>(NewFD))
8880           NewFD->setAccess(OldDecl->getAccess());
8881       } else {
8882         Redeclaration = false;
8883       }
8884     }
8885   }
8886 
8887   // Semantic checking for this function declaration (in isolation).
8888 
8889   if (getLangOpts().CPlusPlus) {
8890     // C++-specific checks.
8891     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8892       CheckConstructor(Constructor);
8893     } else if (CXXDestructorDecl *Destructor =
8894                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8895       CXXRecordDecl *Record = Destructor->getParent();
8896       QualType ClassType = Context.getTypeDeclType(Record);
8897 
8898       // FIXME: Shouldn't we be able to perform this check even when the class
8899       // type is dependent? Both gcc and edg can handle that.
8900       if (!ClassType->isDependentType()) {
8901         DeclarationName Name
8902           = Context.DeclarationNames.getCXXDestructorName(
8903                                         Context.getCanonicalType(ClassType));
8904         if (NewFD->getDeclName() != Name) {
8905           Diag(NewFD->getLocation(), diag::err_destructor_name);
8906           NewFD->setInvalidDecl();
8907           return Redeclaration;
8908         }
8909       }
8910     } else if (CXXConversionDecl *Conversion
8911                = dyn_cast<CXXConversionDecl>(NewFD)) {
8912       ActOnConversionDeclarator(Conversion);
8913     }
8914 
8915     // Find any virtual functions that this function overrides.
8916     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8917       if (!Method->isFunctionTemplateSpecialization() &&
8918           !Method->getDescribedFunctionTemplate() &&
8919           Method->isCanonicalDecl()) {
8920         if (AddOverriddenMethods(Method->getParent(), Method)) {
8921           // If the function was marked as "static", we have a problem.
8922           if (NewFD->getStorageClass() == SC_Static) {
8923             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8924           }
8925         }
8926       }
8927 
8928       if (Method->isStatic())
8929         checkThisInStaticMemberFunctionType(Method);
8930     }
8931 
8932     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8933     if (NewFD->isOverloadedOperator() &&
8934         CheckOverloadedOperatorDeclaration(NewFD)) {
8935       NewFD->setInvalidDecl();
8936       return Redeclaration;
8937     }
8938 
8939     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8940     if (NewFD->getLiteralIdentifier() &&
8941         CheckLiteralOperatorDeclaration(NewFD)) {
8942       NewFD->setInvalidDecl();
8943       return Redeclaration;
8944     }
8945 
8946     // In C++, check default arguments now that we have merged decls. Unless
8947     // the lexical context is the class, because in this case this is done
8948     // during delayed parsing anyway.
8949     if (!CurContext->isRecord())
8950       CheckCXXDefaultArguments(NewFD);
8951 
8952     // If this function declares a builtin function, check the type of this
8953     // declaration against the expected type for the builtin.
8954     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8955       ASTContext::GetBuiltinTypeError Error;
8956       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8957       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8958       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8959         // The type of this function differs from the type of the builtin,
8960         // so forget about the builtin entirely.
8961         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8962       }
8963     }
8964 
8965     // If this function is declared as being extern "C", then check to see if
8966     // the function returns a UDT (class, struct, or union type) that is not C
8967     // compatible, and if it does, warn the user.
8968     // But, issue any diagnostic on the first declaration only.
8969     if (Previous.empty() && NewFD->isExternC()) {
8970       QualType R = NewFD->getReturnType();
8971       if (R->isIncompleteType() && !R->isVoidType())
8972         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8973             << NewFD << R;
8974       else if (!R.isPODType(Context) && !R->isVoidType() &&
8975                !R->isObjCObjectPointerType())
8976         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8977     }
8978   }
8979   return Redeclaration;
8980 }
8981 
8982 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8983   // C++11 [basic.start.main]p3:
8984   //   A program that [...] declares main to be inline, static or
8985   //   constexpr is ill-formed.
8986   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8987   //   appear in a declaration of main.
8988   // static main is not an error under C99, but we should warn about it.
8989   // We accept _Noreturn main as an extension.
8990   if (FD->getStorageClass() == SC_Static)
8991     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8992          ? diag::err_static_main : diag::warn_static_main)
8993       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8994   if (FD->isInlineSpecified())
8995     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8996       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8997   if (DS.isNoreturnSpecified()) {
8998     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8999     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9000     Diag(NoreturnLoc, diag::ext_noreturn_main);
9001     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9002       << FixItHint::CreateRemoval(NoreturnRange);
9003   }
9004   if (FD->isConstexpr()) {
9005     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9006       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9007     FD->setConstexpr(false);
9008   }
9009 
9010   if (getLangOpts().OpenCL) {
9011     Diag(FD->getLocation(), diag::err_opencl_no_main)
9012         << FD->hasAttr<OpenCLKernelAttr>();
9013     FD->setInvalidDecl();
9014     return;
9015   }
9016 
9017   QualType T = FD->getType();
9018   assert(T->isFunctionType() && "function decl is not of function type");
9019   const FunctionType* FT = T->castAs<FunctionType>();
9020 
9021   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9022     // In C with GNU extensions we allow main() to have non-integer return
9023     // type, but we should warn about the extension, and we disable the
9024     // implicit-return-zero rule.
9025 
9026     // GCC in C mode accepts qualified 'int'.
9027     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9028       FD->setHasImplicitReturnZero(true);
9029     else {
9030       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9031       SourceRange RTRange = FD->getReturnTypeSourceRange();
9032       if (RTRange.isValid())
9033         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9034             << FixItHint::CreateReplacement(RTRange, "int");
9035     }
9036   } else {
9037     // In C and C++, main magically returns 0 if you fall off the end;
9038     // set the flag which tells us that.
9039     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9040 
9041     // All the standards say that main() should return 'int'.
9042     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9043       FD->setHasImplicitReturnZero(true);
9044     else {
9045       // Otherwise, this is just a flat-out error.
9046       SourceRange RTRange = FD->getReturnTypeSourceRange();
9047       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9048           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9049                                 : FixItHint());
9050       FD->setInvalidDecl(true);
9051     }
9052   }
9053 
9054   // Treat protoless main() as nullary.
9055   if (isa<FunctionNoProtoType>(FT)) return;
9056 
9057   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9058   unsigned nparams = FTP->getNumParams();
9059   assert(FD->getNumParams() == nparams);
9060 
9061   bool HasExtraParameters = (nparams > 3);
9062 
9063   if (FTP->isVariadic()) {
9064     Diag(FD->getLocation(), diag::ext_variadic_main);
9065     // FIXME: if we had information about the location of the ellipsis, we
9066     // could add a FixIt hint to remove it as a parameter.
9067   }
9068 
9069   // Darwin passes an undocumented fourth argument of type char**.  If
9070   // other platforms start sprouting these, the logic below will start
9071   // getting shifty.
9072   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9073     HasExtraParameters = false;
9074 
9075   if (HasExtraParameters) {
9076     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9077     FD->setInvalidDecl(true);
9078     nparams = 3;
9079   }
9080 
9081   // FIXME: a lot of the following diagnostics would be improved
9082   // if we had some location information about types.
9083 
9084   QualType CharPP =
9085     Context.getPointerType(Context.getPointerType(Context.CharTy));
9086   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9087 
9088   for (unsigned i = 0; i < nparams; ++i) {
9089     QualType AT = FTP->getParamType(i);
9090 
9091     bool mismatch = true;
9092 
9093     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9094       mismatch = false;
9095     else if (Expected[i] == CharPP) {
9096       // As an extension, the following forms are okay:
9097       //   char const **
9098       //   char const * const *
9099       //   char * const *
9100 
9101       QualifierCollector qs;
9102       const PointerType* PT;
9103       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9104           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9105           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9106                               Context.CharTy)) {
9107         qs.removeConst();
9108         mismatch = !qs.empty();
9109       }
9110     }
9111 
9112     if (mismatch) {
9113       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9114       // TODO: suggest replacing given type with expected type
9115       FD->setInvalidDecl(true);
9116     }
9117   }
9118 
9119   if (nparams == 1 && !FD->isInvalidDecl()) {
9120     Diag(FD->getLocation(), diag::warn_main_one_arg);
9121   }
9122 
9123   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9124     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9125     FD->setInvalidDecl();
9126   }
9127 }
9128 
9129 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9130   QualType T = FD->getType();
9131   assert(T->isFunctionType() && "function decl is not of function type");
9132   const FunctionType *FT = T->castAs<FunctionType>();
9133 
9134   // Set an implicit return of 'zero' if the function can return some integral,
9135   // enumeration, pointer or nullptr type.
9136   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9137       FT->getReturnType()->isAnyPointerType() ||
9138       FT->getReturnType()->isNullPtrType())
9139     // DllMain is exempt because a return value of zero means it failed.
9140     if (FD->getName() != "DllMain")
9141       FD->setHasImplicitReturnZero(true);
9142 
9143   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9144     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9145     FD->setInvalidDecl();
9146   }
9147 }
9148 
9149 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9150   // FIXME: Need strict checking.  In C89, we need to check for
9151   // any assignment, increment, decrement, function-calls, or
9152   // commas outside of a sizeof.  In C99, it's the same list,
9153   // except that the aforementioned are allowed in unevaluated
9154   // expressions.  Everything else falls under the
9155   // "may accept other forms of constant expressions" exception.
9156   // (We never end up here for C++, so the constant expression
9157   // rules there don't matter.)
9158   const Expr *Culprit;
9159   if (Init->isConstantInitializer(Context, false, &Culprit))
9160     return false;
9161   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9162     << Culprit->getSourceRange();
9163   return true;
9164 }
9165 
9166 namespace {
9167   // Visits an initialization expression to see if OrigDecl is evaluated in
9168   // its own initialization and throws a warning if it does.
9169   class SelfReferenceChecker
9170       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9171     Sema &S;
9172     Decl *OrigDecl;
9173     bool isRecordType;
9174     bool isPODType;
9175     bool isReferenceType;
9176 
9177     bool isInitList;
9178     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9179 
9180   public:
9181     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9182 
9183     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9184                                                     S(S), OrigDecl(OrigDecl) {
9185       isPODType = false;
9186       isRecordType = false;
9187       isReferenceType = false;
9188       isInitList = false;
9189       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9190         isPODType = VD->getType().isPODType(S.Context);
9191         isRecordType = VD->getType()->isRecordType();
9192         isReferenceType = VD->getType()->isReferenceType();
9193       }
9194     }
9195 
9196     // For most expressions, just call the visitor.  For initializer lists,
9197     // track the index of the field being initialized since fields are
9198     // initialized in order allowing use of previously initialized fields.
9199     void CheckExpr(Expr *E) {
9200       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9201       if (!InitList) {
9202         Visit(E);
9203         return;
9204       }
9205 
9206       // Track and increment the index here.
9207       isInitList = true;
9208       InitFieldIndex.push_back(0);
9209       for (auto Child : InitList->children()) {
9210         CheckExpr(cast<Expr>(Child));
9211         ++InitFieldIndex.back();
9212       }
9213       InitFieldIndex.pop_back();
9214     }
9215 
9216     // Returns true if MemberExpr is checked and no futher checking is needed.
9217     // Returns false if additional checking is required.
9218     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9219       llvm::SmallVector<FieldDecl*, 4> Fields;
9220       Expr *Base = E;
9221       bool ReferenceField = false;
9222 
9223       // Get the field memebers used.
9224       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9225         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9226         if (!FD)
9227           return false;
9228         Fields.push_back(FD);
9229         if (FD->getType()->isReferenceType())
9230           ReferenceField = true;
9231         Base = ME->getBase()->IgnoreParenImpCasts();
9232       }
9233 
9234       // Keep checking only if the base Decl is the same.
9235       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9236       if (!DRE || DRE->getDecl() != OrigDecl)
9237         return false;
9238 
9239       // A reference field can be bound to an unininitialized field.
9240       if (CheckReference && !ReferenceField)
9241         return true;
9242 
9243       // Convert FieldDecls to their index number.
9244       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9245       for (const FieldDecl *I : llvm::reverse(Fields))
9246         UsedFieldIndex.push_back(I->getFieldIndex());
9247 
9248       // See if a warning is needed by checking the first difference in index
9249       // numbers.  If field being used has index less than the field being
9250       // initialized, then the use is safe.
9251       for (auto UsedIter = UsedFieldIndex.begin(),
9252                 UsedEnd = UsedFieldIndex.end(),
9253                 OrigIter = InitFieldIndex.begin(),
9254                 OrigEnd = InitFieldIndex.end();
9255            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9256         if (*UsedIter < *OrigIter)
9257           return true;
9258         if (*UsedIter > *OrigIter)
9259           break;
9260       }
9261 
9262       // TODO: Add a different warning which will print the field names.
9263       HandleDeclRefExpr(DRE);
9264       return true;
9265     }
9266 
9267     // For most expressions, the cast is directly above the DeclRefExpr.
9268     // For conditional operators, the cast can be outside the conditional
9269     // operator if both expressions are DeclRefExpr's.
9270     void HandleValue(Expr *E) {
9271       E = E->IgnoreParens();
9272       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9273         HandleDeclRefExpr(DRE);
9274         return;
9275       }
9276 
9277       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9278         Visit(CO->getCond());
9279         HandleValue(CO->getTrueExpr());
9280         HandleValue(CO->getFalseExpr());
9281         return;
9282       }
9283 
9284       if (BinaryConditionalOperator *BCO =
9285               dyn_cast<BinaryConditionalOperator>(E)) {
9286         Visit(BCO->getCond());
9287         HandleValue(BCO->getFalseExpr());
9288         return;
9289       }
9290 
9291       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9292         HandleValue(OVE->getSourceExpr());
9293         return;
9294       }
9295 
9296       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9297         if (BO->getOpcode() == BO_Comma) {
9298           Visit(BO->getLHS());
9299           HandleValue(BO->getRHS());
9300           return;
9301         }
9302       }
9303 
9304       if (isa<MemberExpr>(E)) {
9305         if (isInitList) {
9306           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9307                                       false /*CheckReference*/))
9308             return;
9309         }
9310 
9311         Expr *Base = E->IgnoreParenImpCasts();
9312         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9313           // Check for static member variables and don't warn on them.
9314           if (!isa<FieldDecl>(ME->getMemberDecl()))
9315             return;
9316           Base = ME->getBase()->IgnoreParenImpCasts();
9317         }
9318         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9319           HandleDeclRefExpr(DRE);
9320         return;
9321       }
9322 
9323       Visit(E);
9324     }
9325 
9326     // Reference types not handled in HandleValue are handled here since all
9327     // uses of references are bad, not just r-value uses.
9328     void VisitDeclRefExpr(DeclRefExpr *E) {
9329       if (isReferenceType)
9330         HandleDeclRefExpr(E);
9331     }
9332 
9333     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9334       if (E->getCastKind() == CK_LValueToRValue) {
9335         HandleValue(E->getSubExpr());
9336         return;
9337       }
9338 
9339       Inherited::VisitImplicitCastExpr(E);
9340     }
9341 
9342     void VisitMemberExpr(MemberExpr *E) {
9343       if (isInitList) {
9344         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9345           return;
9346       }
9347 
9348       // Don't warn on arrays since they can be treated as pointers.
9349       if (E->getType()->canDecayToPointerType()) return;
9350 
9351       // Warn when a non-static method call is followed by non-static member
9352       // field accesses, which is followed by a DeclRefExpr.
9353       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9354       bool Warn = (MD && !MD->isStatic());
9355       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9356       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9357         if (!isa<FieldDecl>(ME->getMemberDecl()))
9358           Warn = false;
9359         Base = ME->getBase()->IgnoreParenImpCasts();
9360       }
9361 
9362       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9363         if (Warn)
9364           HandleDeclRefExpr(DRE);
9365         return;
9366       }
9367 
9368       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9369       // Visit that expression.
9370       Visit(Base);
9371     }
9372 
9373     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9374       Expr *Callee = E->getCallee();
9375 
9376       if (isa<UnresolvedLookupExpr>(Callee))
9377         return Inherited::VisitCXXOperatorCallExpr(E);
9378 
9379       Visit(Callee);
9380       for (auto Arg: E->arguments())
9381         HandleValue(Arg->IgnoreParenImpCasts());
9382     }
9383 
9384     void VisitUnaryOperator(UnaryOperator *E) {
9385       // For POD record types, addresses of its own members are well-defined.
9386       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9387           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9388         if (!isPODType)
9389           HandleValue(E->getSubExpr());
9390         return;
9391       }
9392 
9393       if (E->isIncrementDecrementOp()) {
9394         HandleValue(E->getSubExpr());
9395         return;
9396       }
9397 
9398       Inherited::VisitUnaryOperator(E);
9399     }
9400 
9401     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9402 
9403     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9404       if (E->getConstructor()->isCopyConstructor()) {
9405         Expr *ArgExpr = E->getArg(0);
9406         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9407           if (ILE->getNumInits() == 1)
9408             ArgExpr = ILE->getInit(0);
9409         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9410           if (ICE->getCastKind() == CK_NoOp)
9411             ArgExpr = ICE->getSubExpr();
9412         HandleValue(ArgExpr);
9413         return;
9414       }
9415       Inherited::VisitCXXConstructExpr(E);
9416     }
9417 
9418     void VisitCallExpr(CallExpr *E) {
9419       // Treat std::move as a use.
9420       if (E->getNumArgs() == 1) {
9421         if (FunctionDecl *FD = E->getDirectCallee()) {
9422           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9423               FD->getIdentifier()->isStr("move")) {
9424             HandleValue(E->getArg(0));
9425             return;
9426           }
9427         }
9428       }
9429 
9430       Inherited::VisitCallExpr(E);
9431     }
9432 
9433     void VisitBinaryOperator(BinaryOperator *E) {
9434       if (E->isCompoundAssignmentOp()) {
9435         HandleValue(E->getLHS());
9436         Visit(E->getRHS());
9437         return;
9438       }
9439 
9440       Inherited::VisitBinaryOperator(E);
9441     }
9442 
9443     // A custom visitor for BinaryConditionalOperator is needed because the
9444     // regular visitor would check the condition and true expression separately
9445     // but both point to the same place giving duplicate diagnostics.
9446     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9447       Visit(E->getCond());
9448       Visit(E->getFalseExpr());
9449     }
9450 
9451     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9452       Decl* ReferenceDecl = DRE->getDecl();
9453       if (OrigDecl != ReferenceDecl) return;
9454       unsigned diag;
9455       if (isReferenceType) {
9456         diag = diag::warn_uninit_self_reference_in_reference_init;
9457       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9458         diag = diag::warn_static_self_reference_in_init;
9459       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9460                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9461                  DRE->getDecl()->getType()->isRecordType()) {
9462         diag = diag::warn_uninit_self_reference_in_init;
9463       } else {
9464         // Local variables will be handled by the CFG analysis.
9465         return;
9466       }
9467 
9468       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9469                             S.PDiag(diag)
9470                               << DRE->getNameInfo().getName()
9471                               << OrigDecl->getLocation()
9472                               << DRE->getSourceRange());
9473     }
9474   };
9475 
9476   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9477   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9478                                  bool DirectInit) {
9479     // Parameters arguments are occassionially constructed with itself,
9480     // for instance, in recursive functions.  Skip them.
9481     if (isa<ParmVarDecl>(OrigDecl))
9482       return;
9483 
9484     E = E->IgnoreParens();
9485 
9486     // Skip checking T a = a where T is not a record or reference type.
9487     // Doing so is a way to silence uninitialized warnings.
9488     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9489       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9490         if (ICE->getCastKind() == CK_LValueToRValue)
9491           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9492             if (DRE->getDecl() == OrigDecl)
9493               return;
9494 
9495     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9496   }
9497 } // end anonymous namespace
9498 
9499 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9500                                             DeclarationName Name, QualType Type,
9501                                             TypeSourceInfo *TSI,
9502                                             SourceRange Range, bool DirectInit,
9503                                             Expr *Init) {
9504   bool IsInitCapture = !VDecl;
9505   assert((!VDecl || !VDecl->isInitCapture()) &&
9506          "init captures are expected to be deduced prior to initialization");
9507 
9508   // FIXME: Deduction for a decomposition declaration does weird things if the
9509   // initializer is an array.
9510 
9511   ArrayRef<Expr *> DeduceInits = Init;
9512   if (DirectInit) {
9513     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9514       DeduceInits = PL->exprs();
9515     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9516       DeduceInits = IL->inits();
9517   }
9518 
9519   // Deduction only works if we have exactly one source expression.
9520   if (DeduceInits.empty()) {
9521     // It isn't possible to write this directly, but it is possible to
9522     // end up in this situation with "auto x(some_pack...);"
9523     Diag(Init->getLocStart(), IsInitCapture
9524                                   ? diag::err_init_capture_no_expression
9525                                   : diag::err_auto_var_init_no_expression)
9526         << Name << Type << Range;
9527     return QualType();
9528   }
9529 
9530   if (DeduceInits.size() > 1) {
9531     Diag(DeduceInits[1]->getLocStart(),
9532          IsInitCapture ? diag::err_init_capture_multiple_expressions
9533                        : diag::err_auto_var_init_multiple_expressions)
9534         << Name << Type << Range;
9535     return QualType();
9536   }
9537 
9538   Expr *DeduceInit = DeduceInits[0];
9539   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9540     Diag(Init->getLocStart(), IsInitCapture
9541                                   ? diag::err_init_capture_paren_braces
9542                                   : diag::err_auto_var_init_paren_braces)
9543         << isa<InitListExpr>(Init) << Name << Type << Range;
9544     return QualType();
9545   }
9546 
9547   // Expressions default to 'id' when we're in a debugger.
9548   bool DefaultedAnyToId = false;
9549   if (getLangOpts().DebuggerCastResultToId &&
9550       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9551     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9552     if (Result.isInvalid()) {
9553       return QualType();
9554     }
9555     Init = Result.get();
9556     DefaultedAnyToId = true;
9557   }
9558 
9559   QualType DeducedType;
9560   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9561     if (!IsInitCapture)
9562       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9563     else if (isa<InitListExpr>(Init))
9564       Diag(Range.getBegin(),
9565            diag::err_init_capture_deduction_failure_from_init_list)
9566           << Name
9567           << (DeduceInit->getType().isNull() ? TSI->getType()
9568                                              : DeduceInit->getType())
9569           << DeduceInit->getSourceRange();
9570     else
9571       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9572           << Name << TSI->getType()
9573           << (DeduceInit->getType().isNull() ? TSI->getType()
9574                                              : DeduceInit->getType())
9575           << DeduceInit->getSourceRange();
9576   }
9577 
9578   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9579   // 'id' instead of a specific object type prevents most of our usual
9580   // checks.
9581   // We only want to warn outside of template instantiations, though:
9582   // inside a template, the 'id' could have come from a parameter.
9583   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9584       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9585     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9586     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9587   }
9588 
9589   return DeducedType;
9590 }
9591 
9592 /// AddInitializerToDecl - Adds the initializer Init to the
9593 /// declaration dcl. If DirectInit is true, this is C++ direct
9594 /// initialization rather than copy initialization.
9595 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9596                                 bool DirectInit, bool TypeMayContainAuto) {
9597   // If there is no declaration, there was an error parsing it.  Just ignore
9598   // the initializer.
9599   if (!RealDecl || RealDecl->isInvalidDecl()) {
9600     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9601     return;
9602   }
9603 
9604   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9605     // Pure-specifiers are handled in ActOnPureSpecifier.
9606     Diag(Method->getLocation(), diag::err_member_function_initialization)
9607       << Method->getDeclName() << Init->getSourceRange();
9608     Method->setInvalidDecl();
9609     return;
9610   }
9611 
9612   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9613   if (!VDecl) {
9614     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9615     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9616     RealDecl->setInvalidDecl();
9617     return;
9618   }
9619 
9620   // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not
9621   // permitted.
9622   if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init))
9623     Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl;
9624 
9625   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9626   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9627     // Attempt typo correction early so that the type of the init expression can
9628     // be deduced based on the chosen correction if the original init contains a
9629     // TypoExpr.
9630     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9631     if (!Res.isUsable()) {
9632       RealDecl->setInvalidDecl();
9633       return;
9634     }
9635     Init = Res.get();
9636 
9637     QualType DeducedType = deduceVarTypeFromInitializer(
9638         VDecl, VDecl->getDeclName(), VDecl->getType(),
9639         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9640     if (DeducedType.isNull()) {
9641       RealDecl->setInvalidDecl();
9642       return;
9643     }
9644 
9645     VDecl->setType(DeducedType);
9646     assert(VDecl->isLinkageValid());
9647 
9648     // In ARC, infer lifetime.
9649     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9650       VDecl->setInvalidDecl();
9651 
9652     // If this is a redeclaration, check that the type we just deduced matches
9653     // the previously declared type.
9654     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9655       // We never need to merge the type, because we cannot form an incomplete
9656       // array of auto, nor deduce such a type.
9657       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9658     }
9659 
9660     // Check the deduced type is valid for a variable declaration.
9661     CheckVariableDeclarationType(VDecl);
9662     if (VDecl->isInvalidDecl())
9663       return;
9664   }
9665 
9666   // dllimport cannot be used on variable definitions.
9667   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9668     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9669     VDecl->setInvalidDecl();
9670     return;
9671   }
9672 
9673   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9674     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9675     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9676     VDecl->setInvalidDecl();
9677     return;
9678   }
9679 
9680   if (!VDecl->getType()->isDependentType()) {
9681     // A definition must end up with a complete type, which means it must be
9682     // complete with the restriction that an array type might be completed by
9683     // the initializer; note that later code assumes this restriction.
9684     QualType BaseDeclType = VDecl->getType();
9685     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9686       BaseDeclType = Array->getElementType();
9687     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9688                             diag::err_typecheck_decl_incomplete_type)) {
9689       RealDecl->setInvalidDecl();
9690       return;
9691     }
9692 
9693     // The variable can not have an abstract class type.
9694     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9695                                diag::err_abstract_type_in_decl,
9696                                AbstractVariableType))
9697       VDecl->setInvalidDecl();
9698   }
9699 
9700   VarDecl *Def;
9701   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9702       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine())) {
9703     NamedDecl *Hidden = nullptr;
9704     if (!hasVisibleDefinition(Def, &Hidden) &&
9705         (VDecl->getFormalLinkage() == InternalLinkage ||
9706          VDecl->getDescribedVarTemplate() ||
9707          VDecl->getNumTemplateParameterLists() ||
9708          VDecl->getDeclContext()->isDependentContext())) {
9709       // The previous definition is hidden, and multiple definitions are
9710       // permitted (in separate TUs). Form another definition of it.
9711     } else {
9712       Diag(VDecl->getLocation(), diag::err_redefinition)
9713         << VDecl->getDeclName();
9714       Diag(Def->getLocation(), diag::note_previous_definition);
9715       VDecl->setInvalidDecl();
9716       return;
9717     }
9718   }
9719 
9720   if (getLangOpts().CPlusPlus) {
9721     // C++ [class.static.data]p4
9722     //   If a static data member is of const integral or const
9723     //   enumeration type, its declaration in the class definition can
9724     //   specify a constant-initializer which shall be an integral
9725     //   constant expression (5.19). In that case, the member can appear
9726     //   in integral constant expressions. The member shall still be
9727     //   defined in a namespace scope if it is used in the program and the
9728     //   namespace scope definition shall not contain an initializer.
9729     //
9730     // We already performed a redefinition check above, but for static
9731     // data members we also need to check whether there was an in-class
9732     // declaration with an initializer.
9733     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9734       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9735           << VDecl->getDeclName();
9736       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9737            diag::note_previous_initializer)
9738           << 0;
9739       return;
9740     }
9741 
9742     if (VDecl->hasLocalStorage())
9743       getCurFunction()->setHasBranchProtectedScope();
9744 
9745     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9746       VDecl->setInvalidDecl();
9747       return;
9748     }
9749   }
9750 
9751   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9752   // a kernel function cannot be initialized."
9753   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9754     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9755     VDecl->setInvalidDecl();
9756     return;
9757   }
9758 
9759   // Get the decls type and save a reference for later, since
9760   // CheckInitializerTypes may change it.
9761   QualType DclT = VDecl->getType(), SavT = DclT;
9762 
9763   // Expressions default to 'id' when we're in a debugger
9764   // and we are assigning it to a variable of Objective-C pointer type.
9765   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9766       Init->getType() == Context.UnknownAnyTy) {
9767     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9768     if (Result.isInvalid()) {
9769       VDecl->setInvalidDecl();
9770       return;
9771     }
9772     Init = Result.get();
9773   }
9774 
9775   // Perform the initialization.
9776   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9777   if (!VDecl->isInvalidDecl()) {
9778     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9779     InitializationKind Kind =
9780         DirectInit
9781             ? CXXDirectInit
9782                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9783                                                      Init->getLocStart(),
9784                                                      Init->getLocEnd())
9785                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9786             : InitializationKind::CreateCopy(VDecl->getLocation(),
9787                                              Init->getLocStart());
9788 
9789     MultiExprArg Args = Init;
9790     if (CXXDirectInit)
9791       Args = MultiExprArg(CXXDirectInit->getExprs(),
9792                           CXXDirectInit->getNumExprs());
9793 
9794     // Try to correct any TypoExprs in the initialization arguments.
9795     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9796       ExprResult Res = CorrectDelayedTyposInExpr(
9797           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9798             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9799             return Init.Failed() ? ExprError() : E;
9800           });
9801       if (Res.isInvalid()) {
9802         VDecl->setInvalidDecl();
9803       } else if (Res.get() != Args[Idx]) {
9804         Args[Idx] = Res.get();
9805       }
9806     }
9807     if (VDecl->isInvalidDecl())
9808       return;
9809 
9810     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9811                                    /*TopLevelOfInitList=*/false,
9812                                    /*TreatUnavailableAsInvalid=*/false);
9813     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9814     if (Result.isInvalid()) {
9815       VDecl->setInvalidDecl();
9816       return;
9817     }
9818 
9819     Init = Result.getAs<Expr>();
9820   }
9821 
9822   // Check for self-references within variable initializers.
9823   // Variables declared within a function/method body (except for references)
9824   // are handled by a dataflow analysis.
9825   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9826       VDecl->getType()->isReferenceType()) {
9827     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9828   }
9829 
9830   // If the type changed, it means we had an incomplete type that was
9831   // completed by the initializer. For example:
9832   //   int ary[] = { 1, 3, 5 };
9833   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9834   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9835     VDecl->setType(DclT);
9836 
9837   if (!VDecl->isInvalidDecl()) {
9838     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9839 
9840     if (VDecl->hasAttr<BlocksAttr>())
9841       checkRetainCycles(VDecl, Init);
9842 
9843     // It is safe to assign a weak reference into a strong variable.
9844     // Although this code can still have problems:
9845     //   id x = self.weakProp;
9846     //   id y = self.weakProp;
9847     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9848     // paths through the function. This should be revisited if
9849     // -Wrepeated-use-of-weak is made flow-sensitive.
9850     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9851         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9852                          Init->getLocStart()))
9853       getCurFunction()->markSafeWeakUse(Init);
9854   }
9855 
9856   // The initialization is usually a full-expression.
9857   //
9858   // FIXME: If this is a braced initialization of an aggregate, it is not
9859   // an expression, and each individual field initializer is a separate
9860   // full-expression. For instance, in:
9861   //
9862   //   struct Temp { ~Temp(); };
9863   //   struct S { S(Temp); };
9864   //   struct T { S a, b; } t = { Temp(), Temp() }
9865   //
9866   // we should destroy the first Temp before constructing the second.
9867   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9868                                           false,
9869                                           VDecl->isConstexpr());
9870   if (Result.isInvalid()) {
9871     VDecl->setInvalidDecl();
9872     return;
9873   }
9874   Init = Result.get();
9875 
9876   // Attach the initializer to the decl.
9877   VDecl->setInit(Init);
9878 
9879   if (VDecl->isLocalVarDecl()) {
9880     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9881     // static storage duration shall be constant expressions or string literals.
9882     // C++ does not have this restriction.
9883     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9884       const Expr *Culprit;
9885       if (VDecl->getStorageClass() == SC_Static)
9886         CheckForConstantInitializer(Init, DclT);
9887       // C89 is stricter than C99 for non-static aggregate types.
9888       // C89 6.5.7p3: All the expressions [...] in an initializer list
9889       // for an object that has aggregate or union type shall be
9890       // constant expressions.
9891       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9892                isa<InitListExpr>(Init) &&
9893                !Init->isConstantInitializer(Context, false, &Culprit))
9894         Diag(Culprit->getExprLoc(),
9895              diag::ext_aggregate_init_not_constant)
9896           << Culprit->getSourceRange();
9897     }
9898   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
9899              VDecl->getLexicalDeclContext()->isRecord()) {
9900     // This is an in-class initialization for a static data member, e.g.,
9901     //
9902     // struct S {
9903     //   static const int value = 17;
9904     // };
9905 
9906     // C++ [class.mem]p4:
9907     //   A member-declarator can contain a constant-initializer only
9908     //   if it declares a static member (9.4) of const integral or
9909     //   const enumeration type, see 9.4.2.
9910     //
9911     // C++11 [class.static.data]p3:
9912     //   If a non-volatile non-inline const static data member is of integral
9913     //   or enumeration type, its declaration in the class definition can
9914     //   specify a brace-or-equal-initializer in which every initalizer-clause
9915     //   that is an assignment-expression is a constant expression. A static
9916     //   data member of literal type can be declared in the class definition
9917     //   with the constexpr specifier; if so, its declaration shall specify a
9918     //   brace-or-equal-initializer in which every initializer-clause that is
9919     //   an assignment-expression is a constant expression.
9920 
9921     // Do nothing on dependent types.
9922     if (DclT->isDependentType()) {
9923 
9924     // Allow any 'static constexpr' members, whether or not they are of literal
9925     // type. We separately check that every constexpr variable is of literal
9926     // type.
9927     } else if (VDecl->isConstexpr()) {
9928 
9929     // Require constness.
9930     } else if (!DclT.isConstQualified()) {
9931       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9932         << Init->getSourceRange();
9933       VDecl->setInvalidDecl();
9934 
9935     // We allow integer constant expressions in all cases.
9936     } else if (DclT->isIntegralOrEnumerationType()) {
9937       // Check whether the expression is a constant expression.
9938       SourceLocation Loc;
9939       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9940         // In C++11, a non-constexpr const static data member with an
9941         // in-class initializer cannot be volatile.
9942         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9943       else if (Init->isValueDependent())
9944         ; // Nothing to check.
9945       else if (Init->isIntegerConstantExpr(Context, &Loc))
9946         ; // Ok, it's an ICE!
9947       else if (Init->isEvaluatable(Context)) {
9948         // If we can constant fold the initializer through heroics, accept it,
9949         // but report this as a use of an extension for -pedantic.
9950         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9951           << Init->getSourceRange();
9952       } else {
9953         // Otherwise, this is some crazy unknown case.  Report the issue at the
9954         // location provided by the isIntegerConstantExpr failed check.
9955         Diag(Loc, diag::err_in_class_initializer_non_constant)
9956           << Init->getSourceRange();
9957         VDecl->setInvalidDecl();
9958       }
9959 
9960     // We allow foldable floating-point constants as an extension.
9961     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9962       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9963       // it anyway and provide a fixit to add the 'constexpr'.
9964       if (getLangOpts().CPlusPlus11) {
9965         Diag(VDecl->getLocation(),
9966              diag::ext_in_class_initializer_float_type_cxx11)
9967             << DclT << Init->getSourceRange();
9968         Diag(VDecl->getLocStart(),
9969              diag::note_in_class_initializer_float_type_cxx11)
9970             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9971       } else {
9972         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9973           << DclT << Init->getSourceRange();
9974 
9975         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9976           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9977             << Init->getSourceRange();
9978           VDecl->setInvalidDecl();
9979         }
9980       }
9981 
9982     // Suggest adding 'constexpr' in C++11 for literal types.
9983     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9984       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9985         << DclT << Init->getSourceRange()
9986         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9987       VDecl->setConstexpr(true);
9988 
9989     } else {
9990       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9991         << DclT << Init->getSourceRange();
9992       VDecl->setInvalidDecl();
9993     }
9994   } else if (VDecl->isFileVarDecl()) {
9995     // In C, extern is typically used to avoid tentative definitions when
9996     // declaring variables in headers, but adding an intializer makes it a
9997     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
9998     // In C++, extern is often used to give implictly static const variables
9999     // external linkage, so don't warn in that case. If selectany is present,
10000     // this might be header code intended for C and C++ inclusion, so apply the
10001     // C++ rules.
10002     if (VDecl->getStorageClass() == SC_Extern &&
10003         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10004          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10005         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10006         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10007       Diag(VDecl->getLocation(), diag::warn_extern_init);
10008 
10009     // C99 6.7.8p4. All file scoped initializers need to be constant.
10010     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10011       CheckForConstantInitializer(Init, DclT);
10012   }
10013 
10014   // We will represent direct-initialization similarly to copy-initialization:
10015   //    int x(1);  -as-> int x = 1;
10016   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10017   //
10018   // Clients that want to distinguish between the two forms, can check for
10019   // direct initializer using VarDecl::getInitStyle().
10020   // A major benefit is that clients that don't particularly care about which
10021   // exactly form was it (like the CodeGen) can handle both cases without
10022   // special case code.
10023 
10024   // C++ 8.5p11:
10025   // The form of initialization (using parentheses or '=') is generally
10026   // insignificant, but does matter when the entity being initialized has a
10027   // class type.
10028   if (CXXDirectInit) {
10029     assert(DirectInit && "Call-style initializer must be direct init.");
10030     VDecl->setInitStyle(VarDecl::CallInit);
10031   } else if (DirectInit) {
10032     // This must be list-initialization. No other way is direct-initialization.
10033     VDecl->setInitStyle(VarDecl::ListInit);
10034   }
10035 
10036   CheckCompleteVariableDeclaration(VDecl);
10037 }
10038 
10039 /// ActOnInitializerError - Given that there was an error parsing an
10040 /// initializer for the given declaration, try to return to some form
10041 /// of sanity.
10042 void Sema::ActOnInitializerError(Decl *D) {
10043   // Our main concern here is re-establishing invariants like "a
10044   // variable's type is either dependent or complete".
10045   if (!D || D->isInvalidDecl()) return;
10046 
10047   VarDecl *VD = dyn_cast<VarDecl>(D);
10048   if (!VD) return;
10049 
10050   // Bindings are not usable if we can't make sense of the initializer.
10051   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10052     for (auto *BD : DD->bindings())
10053       BD->setInvalidDecl();
10054 
10055   // Auto types are meaningless if we can't make sense of the initializer.
10056   if (ParsingInitForAutoVars.count(D)) {
10057     D->setInvalidDecl();
10058     return;
10059   }
10060 
10061   QualType Ty = VD->getType();
10062   if (Ty->isDependentType()) return;
10063 
10064   // Require a complete type.
10065   if (RequireCompleteType(VD->getLocation(),
10066                           Context.getBaseElementType(Ty),
10067                           diag::err_typecheck_decl_incomplete_type)) {
10068     VD->setInvalidDecl();
10069     return;
10070   }
10071 
10072   // Require a non-abstract type.
10073   if (RequireNonAbstractType(VD->getLocation(), Ty,
10074                              diag::err_abstract_type_in_decl,
10075                              AbstractVariableType)) {
10076     VD->setInvalidDecl();
10077     return;
10078   }
10079 
10080   // Don't bother complaining about constructors or destructors,
10081   // though.
10082 }
10083 
10084 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
10085                                   bool TypeMayContainAuto) {
10086   // If there is no declaration, there was an error parsing it. Just ignore it.
10087   if (!RealDecl)
10088     return;
10089 
10090   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10091     QualType Type = Var->getType();
10092 
10093     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10094     if (isa<DecompositionDecl>(RealDecl)) {
10095       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10096       Var->setInvalidDecl();
10097       return;
10098     }
10099 
10100     // C++11 [dcl.spec.auto]p3
10101     if (TypeMayContainAuto && Type->getContainedAutoType()) {
10102       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10103         << Var->getDeclName() << Type;
10104       Var->setInvalidDecl();
10105       return;
10106     }
10107 
10108     // C++11 [class.static.data]p3: A static data member can be declared with
10109     // the constexpr specifier; if so, its declaration shall specify
10110     // a brace-or-equal-initializer.
10111     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10112     // the definition of a variable [...] or the declaration of a static data
10113     // member.
10114     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
10115       if (Var->isStaticDataMember()) {
10116         // C++1z removes the relevant rule; the in-class declaration is always
10117         // a definition there.
10118         if (!getLangOpts().CPlusPlus1z) {
10119           Diag(Var->getLocation(),
10120                diag::err_constexpr_static_mem_var_requires_init)
10121             << Var->getDeclName();
10122           Var->setInvalidDecl();
10123           return;
10124         }
10125       } else {
10126         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10127         Var->setInvalidDecl();
10128         return;
10129       }
10130     }
10131 
10132     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10133     // definition having the concept specifier is called a variable concept. A
10134     // concept definition refers to [...] a variable concept and its initializer.
10135     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10136       if (VTD->isConcept()) {
10137         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10138         Var->setInvalidDecl();
10139         return;
10140       }
10141     }
10142 
10143     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10144     // be initialized.
10145     if (!Var->isInvalidDecl() &&
10146         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10147         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10148       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10149       Var->setInvalidDecl();
10150       return;
10151     }
10152 
10153     switch (Var->isThisDeclarationADefinition()) {
10154     case VarDecl::Definition:
10155       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10156         break;
10157 
10158       // We have an out-of-line definition of a static data member
10159       // that has an in-class initializer, so we type-check this like
10160       // a declaration.
10161       //
10162       // Fall through
10163 
10164     case VarDecl::DeclarationOnly:
10165       // It's only a declaration.
10166 
10167       // Block scope. C99 6.7p7: If an identifier for an object is
10168       // declared with no linkage (C99 6.2.2p6), the type for the
10169       // object shall be complete.
10170       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10171           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10172           RequireCompleteType(Var->getLocation(), Type,
10173                               diag::err_typecheck_decl_incomplete_type))
10174         Var->setInvalidDecl();
10175 
10176       // Make sure that the type is not abstract.
10177       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10178           RequireNonAbstractType(Var->getLocation(), Type,
10179                                  diag::err_abstract_type_in_decl,
10180                                  AbstractVariableType))
10181         Var->setInvalidDecl();
10182       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10183           Var->getStorageClass() == SC_PrivateExtern) {
10184         Diag(Var->getLocation(), diag::warn_private_extern);
10185         Diag(Var->getLocation(), diag::note_private_extern);
10186       }
10187 
10188       return;
10189 
10190     case VarDecl::TentativeDefinition:
10191       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10192       // object that has file scope without an initializer, and without a
10193       // storage-class specifier or with the storage-class specifier "static",
10194       // constitutes a tentative definition. Note: A tentative definition with
10195       // external linkage is valid (C99 6.2.2p5).
10196       if (!Var->isInvalidDecl()) {
10197         if (const IncompleteArrayType *ArrayT
10198                                     = Context.getAsIncompleteArrayType(Type)) {
10199           if (RequireCompleteType(Var->getLocation(),
10200                                   ArrayT->getElementType(),
10201                                   diag::err_illegal_decl_array_incomplete_type))
10202             Var->setInvalidDecl();
10203         } else if (Var->getStorageClass() == SC_Static) {
10204           // C99 6.9.2p3: If the declaration of an identifier for an object is
10205           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10206           // declared type shall not be an incomplete type.
10207           // NOTE: code such as the following
10208           //     static struct s;
10209           //     struct s { int a; };
10210           // is accepted by gcc. Hence here we issue a warning instead of
10211           // an error and we do not invalidate the static declaration.
10212           // NOTE: to avoid multiple warnings, only check the first declaration.
10213           if (Var->isFirstDecl())
10214             RequireCompleteType(Var->getLocation(), Type,
10215                                 diag::ext_typecheck_decl_incomplete_type);
10216         }
10217       }
10218 
10219       // Record the tentative definition; we're done.
10220       if (!Var->isInvalidDecl())
10221         TentativeDefinitions.push_back(Var);
10222       return;
10223     }
10224 
10225     // Provide a specific diagnostic for uninitialized variable
10226     // definitions with incomplete array type.
10227     if (Type->isIncompleteArrayType()) {
10228       Diag(Var->getLocation(),
10229            diag::err_typecheck_incomplete_array_needs_initializer);
10230       Var->setInvalidDecl();
10231       return;
10232     }
10233 
10234     // Provide a specific diagnostic for uninitialized variable
10235     // definitions with reference type.
10236     if (Type->isReferenceType()) {
10237       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10238         << Var->getDeclName()
10239         << SourceRange(Var->getLocation(), Var->getLocation());
10240       Var->setInvalidDecl();
10241       return;
10242     }
10243 
10244     // Do not attempt to type-check the default initializer for a
10245     // variable with dependent type.
10246     if (Type->isDependentType())
10247       return;
10248 
10249     if (Var->isInvalidDecl())
10250       return;
10251 
10252     if (!Var->hasAttr<AliasAttr>()) {
10253       if (RequireCompleteType(Var->getLocation(),
10254                               Context.getBaseElementType(Type),
10255                               diag::err_typecheck_decl_incomplete_type)) {
10256         Var->setInvalidDecl();
10257         return;
10258       }
10259     } else {
10260       return;
10261     }
10262 
10263     // The variable can not have an abstract class type.
10264     if (RequireNonAbstractType(Var->getLocation(), Type,
10265                                diag::err_abstract_type_in_decl,
10266                                AbstractVariableType)) {
10267       Var->setInvalidDecl();
10268       return;
10269     }
10270 
10271     // Check for jumps past the implicit initializer.  C++0x
10272     // clarifies that this applies to a "variable with automatic
10273     // storage duration", not a "local variable".
10274     // C++11 [stmt.dcl]p3
10275     //   A program that jumps from a point where a variable with automatic
10276     //   storage duration is not in scope to a point where it is in scope is
10277     //   ill-formed unless the variable has scalar type, class type with a
10278     //   trivial default constructor and a trivial destructor, a cv-qualified
10279     //   version of one of these types, or an array of one of the preceding
10280     //   types and is declared without an initializer.
10281     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10282       if (const RecordType *Record
10283             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10284         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10285         // Mark the function for further checking even if the looser rules of
10286         // C++11 do not require such checks, so that we can diagnose
10287         // incompatibilities with C++98.
10288         if (!CXXRecord->isPOD())
10289           getCurFunction()->setHasBranchProtectedScope();
10290       }
10291     }
10292 
10293     // C++03 [dcl.init]p9:
10294     //   If no initializer is specified for an object, and the
10295     //   object is of (possibly cv-qualified) non-POD class type (or
10296     //   array thereof), the object shall be default-initialized; if
10297     //   the object is of const-qualified type, the underlying class
10298     //   type shall have a user-declared default
10299     //   constructor. Otherwise, if no initializer is specified for
10300     //   a non- static object, the object and its subobjects, if
10301     //   any, have an indeterminate initial value); if the object
10302     //   or any of its subobjects are of const-qualified type, the
10303     //   program is ill-formed.
10304     // C++0x [dcl.init]p11:
10305     //   If no initializer is specified for an object, the object is
10306     //   default-initialized; [...].
10307     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10308     InitializationKind Kind
10309       = InitializationKind::CreateDefault(Var->getLocation());
10310 
10311     InitializationSequence InitSeq(*this, Entity, Kind, None);
10312     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10313     if (Init.isInvalid())
10314       Var->setInvalidDecl();
10315     else if (Init.get()) {
10316       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10317       // This is important for template substitution.
10318       Var->setInitStyle(VarDecl::CallInit);
10319     }
10320 
10321     CheckCompleteVariableDeclaration(Var);
10322   }
10323 }
10324 
10325 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10326   // If there is no declaration, there was an error parsing it. Ignore it.
10327   if (!D)
10328     return;
10329 
10330   VarDecl *VD = dyn_cast<VarDecl>(D);
10331   if (!VD) {
10332     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10333     D->setInvalidDecl();
10334     return;
10335   }
10336 
10337   VD->setCXXForRangeDecl(true);
10338 
10339   // for-range-declaration cannot be given a storage class specifier.
10340   int Error = -1;
10341   switch (VD->getStorageClass()) {
10342   case SC_None:
10343     break;
10344   case SC_Extern:
10345     Error = 0;
10346     break;
10347   case SC_Static:
10348     Error = 1;
10349     break;
10350   case SC_PrivateExtern:
10351     Error = 2;
10352     break;
10353   case SC_Auto:
10354     Error = 3;
10355     break;
10356   case SC_Register:
10357     Error = 4;
10358     break;
10359   }
10360   if (Error != -1) {
10361     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10362       << VD->getDeclName() << Error;
10363     D->setInvalidDecl();
10364   }
10365 }
10366 
10367 StmtResult
10368 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10369                                  IdentifierInfo *Ident,
10370                                  ParsedAttributes &Attrs,
10371                                  SourceLocation AttrEnd) {
10372   // C++1y [stmt.iter]p1:
10373   //   A range-based for statement of the form
10374   //      for ( for-range-identifier : for-range-initializer ) statement
10375   //   is equivalent to
10376   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10377   DeclSpec DS(Attrs.getPool().getFactory());
10378 
10379   const char *PrevSpec;
10380   unsigned DiagID;
10381   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10382                      getPrintingPolicy());
10383 
10384   Declarator D(DS, Declarator::ForContext);
10385   D.SetIdentifier(Ident, IdentLoc);
10386   D.takeAttributes(Attrs, AttrEnd);
10387 
10388   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10389   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10390                 EmptyAttrs, IdentLoc);
10391   Decl *Var = ActOnDeclarator(S, D);
10392   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10393   FinalizeDeclaration(Var);
10394   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10395                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10396 }
10397 
10398 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10399   if (var->isInvalidDecl()) return;
10400 
10401   if (getLangOpts().OpenCL) {
10402     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10403     // initialiser
10404     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10405         !var->hasInit()) {
10406       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10407           << 1 /*Init*/;
10408       var->setInvalidDecl();
10409       return;
10410     }
10411   }
10412 
10413   // In Objective-C, don't allow jumps past the implicit initialization of a
10414   // local retaining variable.
10415   if (getLangOpts().ObjC1 &&
10416       var->hasLocalStorage()) {
10417     switch (var->getType().getObjCLifetime()) {
10418     case Qualifiers::OCL_None:
10419     case Qualifiers::OCL_ExplicitNone:
10420     case Qualifiers::OCL_Autoreleasing:
10421       break;
10422 
10423     case Qualifiers::OCL_Weak:
10424     case Qualifiers::OCL_Strong:
10425       getCurFunction()->setHasBranchProtectedScope();
10426       break;
10427     }
10428   }
10429 
10430   // Warn about externally-visible variables being defined without a
10431   // prior declaration.  We only want to do this for global
10432   // declarations, but we also specifically need to avoid doing it for
10433   // class members because the linkage of an anonymous class can
10434   // change if it's later given a typedef name.
10435   if (var->isThisDeclarationADefinition() &&
10436       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10437       var->isExternallyVisible() && var->hasLinkage() &&
10438       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10439                                   var->getLocation())) {
10440     // Find a previous declaration that's not a definition.
10441     VarDecl *prev = var->getPreviousDecl();
10442     while (prev && prev->isThisDeclarationADefinition())
10443       prev = prev->getPreviousDecl();
10444 
10445     if (!prev)
10446       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10447   }
10448 
10449   // Cache the result of checking for constant initialization.
10450   Optional<bool> CacheHasConstInit;
10451   const Expr *CacheCulprit;
10452   auto checkConstInit = [&]() mutable {
10453     if (!CacheHasConstInit)
10454       CacheHasConstInit = var->getInit()->isConstantInitializer(
10455             Context, var->getType()->isReferenceType(), &CacheCulprit);
10456     return *CacheHasConstInit;
10457   };
10458 
10459   if (var->getTLSKind() == VarDecl::TLS_Static) {
10460     if (var->getType().isDestructedType()) {
10461       // GNU C++98 edits for __thread, [basic.start.term]p3:
10462       //   The type of an object with thread storage duration shall not
10463       //   have a non-trivial destructor.
10464       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10465       if (getLangOpts().CPlusPlus11)
10466         Diag(var->getLocation(), diag::note_use_thread_local);
10467     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10468       if (!checkConstInit()) {
10469         // GNU C++98 edits for __thread, [basic.start.init]p4:
10470         //   An object of thread storage duration shall not require dynamic
10471         //   initialization.
10472         // FIXME: Need strict checking here.
10473         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10474           << CacheCulprit->getSourceRange();
10475         if (getLangOpts().CPlusPlus11)
10476           Diag(var->getLocation(), diag::note_use_thread_local);
10477       }
10478     }
10479   }
10480 
10481   // Apply section attributes and pragmas to global variables.
10482   bool GlobalStorage = var->hasGlobalStorage();
10483   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10484       ActiveTemplateInstantiations.empty()) {
10485     PragmaStack<StringLiteral *> *Stack = nullptr;
10486     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10487     if (var->getType().isConstQualified())
10488       Stack = &ConstSegStack;
10489     else if (!var->getInit()) {
10490       Stack = &BSSSegStack;
10491       SectionFlags |= ASTContext::PSF_Write;
10492     } else {
10493       Stack = &DataSegStack;
10494       SectionFlags |= ASTContext::PSF_Write;
10495     }
10496     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10497       var->addAttr(SectionAttr::CreateImplicit(
10498           Context, SectionAttr::Declspec_allocate,
10499           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10500     }
10501     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10502       if (UnifySection(SA->getName(), SectionFlags, var))
10503         var->dropAttr<SectionAttr>();
10504 
10505     // Apply the init_seg attribute if this has an initializer.  If the
10506     // initializer turns out to not be dynamic, we'll end up ignoring this
10507     // attribute.
10508     if (CurInitSeg && var->getInit())
10509       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10510                                                CurInitSegLoc));
10511   }
10512 
10513   // All the following checks are C++ only.
10514   if (!getLangOpts().CPlusPlus) return;
10515 
10516   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10517     CheckCompleteDecompositionDeclaration(DD);
10518 
10519   QualType type = var->getType();
10520   if (type->isDependentType()) return;
10521 
10522   // __block variables might require us to capture a copy-initializer.
10523   if (var->hasAttr<BlocksAttr>()) {
10524     // It's currently invalid to ever have a __block variable with an
10525     // array type; should we diagnose that here?
10526 
10527     // Regardless, we don't want to ignore array nesting when
10528     // constructing this copy.
10529     if (type->isStructureOrClassType()) {
10530       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10531       SourceLocation poi = var->getLocation();
10532       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10533       ExprResult result
10534         = PerformMoveOrCopyInitialization(
10535             InitializedEntity::InitializeBlock(poi, type, false),
10536             var, var->getType(), varRef, /*AllowNRVO=*/true);
10537       if (!result.isInvalid()) {
10538         result = MaybeCreateExprWithCleanups(result);
10539         Expr *init = result.getAs<Expr>();
10540         Context.setBlockVarCopyInits(var, init);
10541       }
10542     }
10543   }
10544 
10545   Expr *Init = var->getInit();
10546   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10547   QualType baseType = Context.getBaseElementType(type);
10548 
10549   if (!var->getDeclContext()->isDependentContext() &&
10550       Init && !Init->isValueDependent()) {
10551 
10552     if (var->isConstexpr()) {
10553       SmallVector<PartialDiagnosticAt, 8> Notes;
10554       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10555         SourceLocation DiagLoc = var->getLocation();
10556         // If the note doesn't add any useful information other than a source
10557         // location, fold it into the primary diagnostic.
10558         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10559               diag::note_invalid_subexpr_in_const_expr) {
10560           DiagLoc = Notes[0].first;
10561           Notes.clear();
10562         }
10563         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10564           << var << Init->getSourceRange();
10565         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10566           Diag(Notes[I].first, Notes[I].second);
10567       }
10568     } else if (var->isUsableInConstantExpressions(Context)) {
10569       // Check whether the initializer of a const variable of integral or
10570       // enumeration type is an ICE now, since we can't tell whether it was
10571       // initialized by a constant expression if we check later.
10572       var->checkInitIsICE();
10573     }
10574 
10575     // Don't emit further diagnostics about constexpr globals since they
10576     // were just diagnosed.
10577     if (!var->isConstexpr() && GlobalStorage &&
10578             var->hasAttr<RequireConstantInitAttr>()) {
10579       // FIXME: Need strict checking in C++03 here.
10580       bool DiagErr = getLangOpts().CPlusPlus11
10581           ? !var->checkInitIsICE() : !checkConstInit();
10582       if (DiagErr) {
10583         auto attr = var->getAttr<RequireConstantInitAttr>();
10584         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10585           << Init->getSourceRange();
10586         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10587           << attr->getRange();
10588       }
10589     }
10590     else if (!var->isConstexpr() && IsGlobal &&
10591              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10592                                     var->getLocation())) {
10593       // Warn about globals which don't have a constant initializer.  Don't
10594       // warn about globals with a non-trivial destructor because we already
10595       // warned about them.
10596       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10597       if (!(RD && !RD->hasTrivialDestructor())) {
10598         if (!checkConstInit())
10599           Diag(var->getLocation(), diag::warn_global_constructor)
10600             << Init->getSourceRange();
10601       }
10602     }
10603   }
10604 
10605   // Require the destructor.
10606   if (const RecordType *recordType = baseType->getAs<RecordType>())
10607     FinalizeVarWithDestructor(var, recordType);
10608 
10609   // If this variable must be emitted, add it as an initializer for the current
10610   // module.
10611   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10612     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10613 }
10614 
10615 /// \brief Determines if a variable's alignment is dependent.
10616 static bool hasDependentAlignment(VarDecl *VD) {
10617   if (VD->getType()->isDependentType())
10618     return true;
10619   for (auto *I : VD->specific_attrs<AlignedAttr>())
10620     if (I->isAlignmentDependent())
10621       return true;
10622   return false;
10623 }
10624 
10625 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10626 /// any semantic actions necessary after any initializer has been attached.
10627 void
10628 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10629   // Note that we are no longer parsing the initializer for this declaration.
10630   ParsingInitForAutoVars.erase(ThisDecl);
10631 
10632   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10633   if (!VD)
10634     return;
10635 
10636   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10637     for (auto *BD : DD->bindings()) {
10638       if (ThisDecl->isInvalidDecl())
10639         BD->setInvalidDecl();
10640       FinalizeDeclaration(BD);
10641     }
10642   }
10643 
10644   checkAttributesAfterMerging(*this, *VD);
10645 
10646   // Perform TLS alignment check here after attributes attached to the variable
10647   // which may affect the alignment have been processed. Only perform the check
10648   // if the target has a maximum TLS alignment (zero means no constraints).
10649   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10650     // Protect the check so that it's not performed on dependent types and
10651     // dependent alignments (we can't determine the alignment in that case).
10652     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10653       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10654       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10655         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10656           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10657           << (unsigned)MaxAlignChars.getQuantity();
10658       }
10659     }
10660   }
10661 
10662   if (VD->isStaticLocal()) {
10663     if (FunctionDecl *FD =
10664             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10665       // Static locals inherit dll attributes from their function.
10666       if (Attr *A = getDLLAttr(FD)) {
10667         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10668         NewAttr->setInherited(true);
10669         VD->addAttr(NewAttr);
10670       }
10671       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10672       // function, only __shared__ variables may be declared with
10673       // static storage class.
10674       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10675           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10676           !VD->hasAttr<CUDASharedAttr>()) {
10677         Diag(VD->getLocation(), diag::err_device_static_local_var);
10678         VD->setInvalidDecl();
10679       }
10680     }
10681   }
10682 
10683   // Perform check for initializers of device-side global variables.
10684   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10685   // 7.5). We must also apply the same checks to all __shared__
10686   // variables whether they are local or not. CUDA also allows
10687   // constant initializers for __constant__ and __device__ variables.
10688   if (getLangOpts().CUDA) {
10689     const Expr *Init = VD->getInit();
10690     if (Init && VD->hasGlobalStorage()) {
10691       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10692           VD->hasAttr<CUDASharedAttr>()) {
10693         assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10694         bool AllowedInit = false;
10695         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10696           AllowedInit =
10697               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10698         // We'll allow constant initializers even if it's a non-empty
10699         // constructor according to CUDA rules. This deviates from NVCC,
10700         // but allows us to handle things like constexpr constructors.
10701         if (!AllowedInit &&
10702             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10703           AllowedInit = VD->getInit()->isConstantInitializer(
10704               Context, VD->getType()->isReferenceType());
10705 
10706         // Also make sure that destructor, if there is one, is empty.
10707         if (AllowedInit)
10708           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10709             AllowedInit =
10710                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10711 
10712         if (!AllowedInit) {
10713           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10714                                       ? diag::err_shared_var_init
10715                                       : diag::err_dynamic_var_init)
10716               << Init->getSourceRange();
10717           VD->setInvalidDecl();
10718         }
10719       } else {
10720         // This is a host-side global variable.  Check that the initializer is
10721         // callable from the host side.
10722         const FunctionDecl *InitFn = nullptr;
10723         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10724           InitFn = CE->getConstructor();
10725         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10726           InitFn = CE->getDirectCallee();
10727         }
10728         if (InitFn) {
10729           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10730           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10731             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10732                 << InitFnTarget << InitFn;
10733             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10734             VD->setInvalidDecl();
10735           }
10736         }
10737       }
10738     }
10739   }
10740 
10741   // Grab the dllimport or dllexport attribute off of the VarDecl.
10742   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10743 
10744   // Imported static data members cannot be defined out-of-line.
10745   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10746     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10747         VD->isThisDeclarationADefinition()) {
10748       // We allow definitions of dllimport class template static data members
10749       // with a warning.
10750       CXXRecordDecl *Context =
10751         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10752       bool IsClassTemplateMember =
10753           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10754           Context->getDescribedClassTemplate();
10755 
10756       Diag(VD->getLocation(),
10757            IsClassTemplateMember
10758                ? diag::warn_attribute_dllimport_static_field_definition
10759                : diag::err_attribute_dllimport_static_field_definition);
10760       Diag(IA->getLocation(), diag::note_attribute);
10761       if (!IsClassTemplateMember)
10762         VD->setInvalidDecl();
10763     }
10764   }
10765 
10766   // dllimport/dllexport variables cannot be thread local, their TLS index
10767   // isn't exported with the variable.
10768   if (DLLAttr && VD->getTLSKind()) {
10769     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10770     if (F && getDLLAttr(F)) {
10771       assert(VD->isStaticLocal());
10772       // But if this is a static local in a dlimport/dllexport function, the
10773       // function will never be inlined, which means the var would never be
10774       // imported, so having it marked import/export is safe.
10775     } else {
10776       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10777                                                                     << DLLAttr;
10778       VD->setInvalidDecl();
10779     }
10780   }
10781 
10782   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10783     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10784       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10785       VD->dropAttr<UsedAttr>();
10786     }
10787   }
10788 
10789   const DeclContext *DC = VD->getDeclContext();
10790   // If there's a #pragma GCC visibility in scope, and this isn't a class
10791   // member, set the visibility of this variable.
10792   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10793     AddPushedVisibilityAttribute(VD);
10794 
10795   // FIXME: Warn on unused templates.
10796   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10797       !isa<VarTemplatePartialSpecializationDecl>(VD))
10798     MarkUnusedFileScopedDecl(VD);
10799 
10800   // Now we have parsed the initializer and can update the table of magic
10801   // tag values.
10802   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10803       !VD->getType()->isIntegralOrEnumerationType())
10804     return;
10805 
10806   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10807     const Expr *MagicValueExpr = VD->getInit();
10808     if (!MagicValueExpr) {
10809       continue;
10810     }
10811     llvm::APSInt MagicValueInt;
10812     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10813       Diag(I->getRange().getBegin(),
10814            diag::err_type_tag_for_datatype_not_ice)
10815         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10816       continue;
10817     }
10818     if (MagicValueInt.getActiveBits() > 64) {
10819       Diag(I->getRange().getBegin(),
10820            diag::err_type_tag_for_datatype_too_large)
10821         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10822       continue;
10823     }
10824     uint64_t MagicValue = MagicValueInt.getZExtValue();
10825     RegisterTypeTagForDatatype(I->getArgumentKind(),
10826                                MagicValue,
10827                                I->getMatchingCType(),
10828                                I->getLayoutCompatible(),
10829                                I->getMustBeNull());
10830   }
10831 }
10832 
10833 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10834                                                    ArrayRef<Decl *> Group) {
10835   SmallVector<Decl*, 8> Decls;
10836 
10837   if (DS.isTypeSpecOwned())
10838     Decls.push_back(DS.getRepAsDecl());
10839 
10840   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10841   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
10842   bool DiagnosedMultipleDecomps = false;
10843 
10844   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10845     if (Decl *D = Group[i]) {
10846       auto *DD = dyn_cast<DeclaratorDecl>(D);
10847       if (DD && !FirstDeclaratorInGroup)
10848         FirstDeclaratorInGroup = DD;
10849 
10850       auto *Decomp = dyn_cast<DecompositionDecl>(D);
10851       if (Decomp && !FirstDecompDeclaratorInGroup)
10852         FirstDecompDeclaratorInGroup = Decomp;
10853 
10854       // A decomposition declaration cannot be combined with any other
10855       // declaration in the same group.
10856       auto *OtherDD = FirstDeclaratorInGroup;
10857       if (OtherDD == FirstDecompDeclaratorInGroup)
10858         OtherDD = DD;
10859       if (OtherDD && FirstDecompDeclaratorInGroup &&
10860           OtherDD != FirstDecompDeclaratorInGroup &&
10861           !DiagnosedMultipleDecomps) {
10862         Diag(FirstDecompDeclaratorInGroup->getLocation(),
10863              diag::err_decomp_decl_not_alone)
10864           << OtherDD->getSourceRange();
10865         DiagnosedMultipleDecomps = true;
10866       }
10867 
10868       Decls.push_back(D);
10869     }
10870   }
10871 
10872   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10873     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10874       handleTagNumbering(Tag, S);
10875       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10876           getLangOpts().CPlusPlus)
10877         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10878     }
10879   }
10880 
10881   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10882 }
10883 
10884 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10885 /// group, performing any necessary semantic checking.
10886 Sema::DeclGroupPtrTy
10887 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10888                            bool TypeMayContainAuto) {
10889   // C++0x [dcl.spec.auto]p7:
10890   //   If the type deduced for the template parameter U is not the same in each
10891   //   deduction, the program is ill-formed.
10892   // FIXME: When initializer-list support is added, a distinction is needed
10893   // between the deduced type U and the deduced type which 'auto' stands for.
10894   //   auto a = 0, b = { 1, 2, 3 };
10895   // is legal because the deduced type U is 'int' in both cases.
10896   if (TypeMayContainAuto && Group.size() > 1) {
10897     QualType Deduced;
10898     CanQualType DeducedCanon;
10899     VarDecl *DeducedDecl = nullptr;
10900     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10901       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10902         AutoType *AT = D->getType()->getContainedAutoType();
10903         // Don't reissue diagnostics when instantiating a template.
10904         if (AT && D->isInvalidDecl())
10905           break;
10906         QualType U = AT ? AT->getDeducedType() : QualType();
10907         if (!U.isNull()) {
10908           CanQualType UCanon = Context.getCanonicalType(U);
10909           if (Deduced.isNull()) {
10910             Deduced = U;
10911             DeducedCanon = UCanon;
10912             DeducedDecl = D;
10913           } else if (DeducedCanon != UCanon) {
10914             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10915                  diag::err_auto_different_deductions)
10916               << (unsigned)AT->getKeyword()
10917               << Deduced << DeducedDecl->getDeclName()
10918               << U << D->getDeclName()
10919               << DeducedDecl->getInit()->getSourceRange()
10920               << D->getInit()->getSourceRange();
10921             D->setInvalidDecl();
10922             break;
10923           }
10924         }
10925       }
10926     }
10927   }
10928 
10929   ActOnDocumentableDecls(Group);
10930 
10931   return DeclGroupPtrTy::make(
10932       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10933 }
10934 
10935 void Sema::ActOnDocumentableDecl(Decl *D) {
10936   ActOnDocumentableDecls(D);
10937 }
10938 
10939 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10940   // Don't parse the comment if Doxygen diagnostics are ignored.
10941   if (Group.empty() || !Group[0])
10942     return;
10943 
10944   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10945                       Group[0]->getLocation()) &&
10946       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10947                       Group[0]->getLocation()))
10948     return;
10949 
10950   if (Group.size() >= 2) {
10951     // This is a decl group.  Normally it will contain only declarations
10952     // produced from declarator list.  But in case we have any definitions or
10953     // additional declaration references:
10954     //   'typedef struct S {} S;'
10955     //   'typedef struct S *S;'
10956     //   'struct S *pS;'
10957     // FinalizeDeclaratorGroup adds these as separate declarations.
10958     Decl *MaybeTagDecl = Group[0];
10959     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10960       Group = Group.slice(1);
10961     }
10962   }
10963 
10964   // See if there are any new comments that are not attached to a decl.
10965   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10966   if (!Comments.empty() &&
10967       !Comments.back()->isAttached()) {
10968     // There is at least one comment that not attached to a decl.
10969     // Maybe it should be attached to one of these decls?
10970     //
10971     // Note that this way we pick up not only comments that precede the
10972     // declaration, but also comments that *follow* the declaration -- thanks to
10973     // the lookahead in the lexer: we've consumed the semicolon and looked
10974     // ahead through comments.
10975     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10976       Context.getCommentForDecl(Group[i], &PP);
10977   }
10978 }
10979 
10980 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10981 /// to introduce parameters into function prototype scope.
10982 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10983   const DeclSpec &DS = D.getDeclSpec();
10984 
10985   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10986 
10987   // C++03 [dcl.stc]p2 also permits 'auto'.
10988   StorageClass SC = SC_None;
10989   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10990     SC = SC_Register;
10991   } else if (getLangOpts().CPlusPlus &&
10992              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10993     SC = SC_Auto;
10994   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10995     Diag(DS.getStorageClassSpecLoc(),
10996          diag::err_invalid_storage_class_in_func_decl);
10997     D.getMutableDeclSpec().ClearStorageClassSpecs();
10998   }
10999 
11000   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11001     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11002       << DeclSpec::getSpecifierName(TSCS);
11003   if (DS.isInlineSpecified())
11004     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11005         << getLangOpts().CPlusPlus1z;
11006   if (DS.isConstexprSpecified())
11007     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11008       << 0;
11009   if (DS.isConceptSpecified())
11010     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11011 
11012   DiagnoseFunctionSpecifiers(DS);
11013 
11014   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11015   QualType parmDeclType = TInfo->getType();
11016 
11017   if (getLangOpts().CPlusPlus) {
11018     // Check that there are no default arguments inside the type of this
11019     // parameter.
11020     CheckExtraCXXDefaultArguments(D);
11021 
11022     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11023     if (D.getCXXScopeSpec().isSet()) {
11024       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11025         << D.getCXXScopeSpec().getRange();
11026       D.getCXXScopeSpec().clear();
11027     }
11028   }
11029 
11030   // Ensure we have a valid name
11031   IdentifierInfo *II = nullptr;
11032   if (D.hasName()) {
11033     II = D.getIdentifier();
11034     if (!II) {
11035       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11036         << GetNameForDeclarator(D).getName();
11037       D.setInvalidType(true);
11038     }
11039   }
11040 
11041   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11042   if (II) {
11043     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11044                    ForRedeclaration);
11045     LookupName(R, S);
11046     if (R.isSingleResult()) {
11047       NamedDecl *PrevDecl = R.getFoundDecl();
11048       if (PrevDecl->isTemplateParameter()) {
11049         // Maybe we will complain about the shadowed template parameter.
11050         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11051         // Just pretend that we didn't see the previous declaration.
11052         PrevDecl = nullptr;
11053       } else if (S->isDeclScope(PrevDecl)) {
11054         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11055         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11056 
11057         // Recover by removing the name
11058         II = nullptr;
11059         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11060         D.setInvalidType(true);
11061       }
11062     }
11063   }
11064 
11065   // Temporarily put parameter variables in the translation unit, not
11066   // the enclosing context.  This prevents them from accidentally
11067   // looking like class members in C++.
11068   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11069                                     D.getLocStart(),
11070                                     D.getIdentifierLoc(), II,
11071                                     parmDeclType, TInfo,
11072                                     SC);
11073 
11074   if (D.isInvalidType())
11075     New->setInvalidDecl();
11076 
11077   assert(S->isFunctionPrototypeScope());
11078   assert(S->getFunctionPrototypeDepth() >= 1);
11079   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11080                     S->getNextFunctionPrototypeIndex());
11081 
11082   // Add the parameter declaration into this scope.
11083   S->AddDecl(New);
11084   if (II)
11085     IdResolver.AddDecl(New);
11086 
11087   ProcessDeclAttributes(S, New, D);
11088 
11089   if (D.getDeclSpec().isModulePrivateSpecified())
11090     Diag(New->getLocation(), diag::err_module_private_local)
11091       << 1 << New->getDeclName()
11092       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11093       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11094 
11095   if (New->hasAttr<BlocksAttr>()) {
11096     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11097   }
11098   return New;
11099 }
11100 
11101 /// \brief Synthesizes a variable for a parameter arising from a
11102 /// typedef.
11103 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11104                                               SourceLocation Loc,
11105                                               QualType T) {
11106   /* FIXME: setting StartLoc == Loc.
11107      Would it be worth to modify callers so as to provide proper source
11108      location for the unnamed parameters, embedding the parameter's type? */
11109   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11110                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11111                                            SC_None, nullptr);
11112   Param->setImplicit();
11113   return Param;
11114 }
11115 
11116 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11117   // Don't diagnose unused-parameter errors in template instantiations; we
11118   // will already have done so in the template itself.
11119   if (!ActiveTemplateInstantiations.empty())
11120     return;
11121 
11122   for (const ParmVarDecl *Parameter : Parameters) {
11123     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11124         !Parameter->hasAttr<UnusedAttr>()) {
11125       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11126         << Parameter->getDeclName();
11127     }
11128   }
11129 }
11130 
11131 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11132     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11133   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11134     return;
11135 
11136   // Warn if the return value is pass-by-value and larger than the specified
11137   // threshold.
11138   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11139     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11140     if (Size > LangOpts.NumLargeByValueCopy)
11141       Diag(D->getLocation(), diag::warn_return_value_size)
11142           << D->getDeclName() << Size;
11143   }
11144 
11145   // Warn if any parameter is pass-by-value and larger than the specified
11146   // threshold.
11147   for (const ParmVarDecl *Parameter : Parameters) {
11148     QualType T = Parameter->getType();
11149     if (T->isDependentType() || !T.isPODType(Context))
11150       continue;
11151     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11152     if (Size > LangOpts.NumLargeByValueCopy)
11153       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11154           << Parameter->getDeclName() << Size;
11155   }
11156 }
11157 
11158 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11159                                   SourceLocation NameLoc, IdentifierInfo *Name,
11160                                   QualType T, TypeSourceInfo *TSInfo,
11161                                   StorageClass SC) {
11162   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11163   if (getLangOpts().ObjCAutoRefCount &&
11164       T.getObjCLifetime() == Qualifiers::OCL_None &&
11165       T->isObjCLifetimeType()) {
11166 
11167     Qualifiers::ObjCLifetime lifetime;
11168 
11169     // Special cases for arrays:
11170     //   - if it's const, use __unsafe_unretained
11171     //   - otherwise, it's an error
11172     if (T->isArrayType()) {
11173       if (!T.isConstQualified()) {
11174         DelayedDiagnostics.add(
11175             sema::DelayedDiagnostic::makeForbiddenType(
11176             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11177       }
11178       lifetime = Qualifiers::OCL_ExplicitNone;
11179     } else {
11180       lifetime = T->getObjCARCImplicitLifetime();
11181     }
11182     T = Context.getLifetimeQualifiedType(T, lifetime);
11183   }
11184 
11185   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11186                                          Context.getAdjustedParameterType(T),
11187                                          TSInfo, SC, nullptr);
11188 
11189   // Parameters can not be abstract class types.
11190   // For record types, this is done by the AbstractClassUsageDiagnoser once
11191   // the class has been completely parsed.
11192   if (!CurContext->isRecord() &&
11193       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11194                              AbstractParamType))
11195     New->setInvalidDecl();
11196 
11197   // Parameter declarators cannot be interface types. All ObjC objects are
11198   // passed by reference.
11199   if (T->isObjCObjectType()) {
11200     SourceLocation TypeEndLoc =
11201         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11202     Diag(NameLoc,
11203          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11204       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11205     T = Context.getObjCObjectPointerType(T);
11206     New->setType(T);
11207   }
11208 
11209   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11210   // duration shall not be qualified by an address-space qualifier."
11211   // Since all parameters have automatic store duration, they can not have
11212   // an address space.
11213   if (T.getAddressSpace() != 0) {
11214     // OpenCL allows function arguments declared to be an array of a type
11215     // to be qualified with an address space.
11216     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11217       Diag(NameLoc, diag::err_arg_with_address_space);
11218       New->setInvalidDecl();
11219     }
11220   }
11221 
11222   return New;
11223 }
11224 
11225 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11226                                            SourceLocation LocAfterDecls) {
11227   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11228 
11229   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11230   // for a K&R function.
11231   if (!FTI.hasPrototype) {
11232     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11233       --i;
11234       if (FTI.Params[i].Param == nullptr) {
11235         SmallString<256> Code;
11236         llvm::raw_svector_ostream(Code)
11237             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11238         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11239             << FTI.Params[i].Ident
11240             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11241 
11242         // Implicitly declare the argument as type 'int' for lack of a better
11243         // type.
11244         AttributeFactory attrs;
11245         DeclSpec DS(attrs);
11246         const char* PrevSpec; // unused
11247         unsigned DiagID; // unused
11248         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11249                            DiagID, Context.getPrintingPolicy());
11250         // Use the identifier location for the type source range.
11251         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11252         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11253         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11254         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11255         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11256       }
11257     }
11258   }
11259 }
11260 
11261 Decl *
11262 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11263                               MultiTemplateParamsArg TemplateParameterLists,
11264                               SkipBodyInfo *SkipBody) {
11265   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11266   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11267   Scope *ParentScope = FnBodyScope->getParent();
11268 
11269   D.setFunctionDefinitionKind(FDK_Definition);
11270   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11271   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11272 }
11273 
11274 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11275   Consumer.HandleInlineFunctionDefinition(D);
11276 }
11277 
11278 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11279                              const FunctionDecl*& PossibleZeroParamPrototype) {
11280   // Don't warn about invalid declarations.
11281   if (FD->isInvalidDecl())
11282     return false;
11283 
11284   // Or declarations that aren't global.
11285   if (!FD->isGlobal())
11286     return false;
11287 
11288   // Don't warn about C++ member functions.
11289   if (isa<CXXMethodDecl>(FD))
11290     return false;
11291 
11292   // Don't warn about 'main'.
11293   if (FD->isMain())
11294     return false;
11295 
11296   // Don't warn about inline functions.
11297   if (FD->isInlined())
11298     return false;
11299 
11300   // Don't warn about function templates.
11301   if (FD->getDescribedFunctionTemplate())
11302     return false;
11303 
11304   // Don't warn about function template specializations.
11305   if (FD->isFunctionTemplateSpecialization())
11306     return false;
11307 
11308   // Don't warn for OpenCL kernels.
11309   if (FD->hasAttr<OpenCLKernelAttr>())
11310     return false;
11311 
11312   // Don't warn on explicitly deleted functions.
11313   if (FD->isDeleted())
11314     return false;
11315 
11316   bool MissingPrototype = true;
11317   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11318        Prev; Prev = Prev->getPreviousDecl()) {
11319     // Ignore any declarations that occur in function or method
11320     // scope, because they aren't visible from the header.
11321     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11322       continue;
11323 
11324     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11325     if (FD->getNumParams() == 0)
11326       PossibleZeroParamPrototype = Prev;
11327     break;
11328   }
11329 
11330   return MissingPrototype;
11331 }
11332 
11333 void
11334 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11335                                    const FunctionDecl *EffectiveDefinition,
11336                                    SkipBodyInfo *SkipBody) {
11337   // Don't complain if we're in GNU89 mode and the previous definition
11338   // was an extern inline function.
11339   const FunctionDecl *Definition = EffectiveDefinition;
11340   if (!Definition)
11341     if (!FD->isDefined(Definition))
11342       return;
11343 
11344   if (canRedefineFunction(Definition, getLangOpts()))
11345     return;
11346 
11347   // If we don't have a visible definition of the function, and it's inline or
11348   // a template, skip the new definition.
11349   if (SkipBody && !hasVisibleDefinition(Definition) &&
11350       (Definition->getFormalLinkage() == InternalLinkage ||
11351        Definition->isInlined() ||
11352        Definition->getDescribedFunctionTemplate() ||
11353        Definition->getNumTemplateParameterLists())) {
11354     SkipBody->ShouldSkip = true;
11355     if (auto *TD = Definition->getDescribedFunctionTemplate())
11356       makeMergedDefinitionVisible(TD, FD->getLocation());
11357     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11358                                 FD->getLocation());
11359     return;
11360   }
11361 
11362   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11363       Definition->getStorageClass() == SC_Extern)
11364     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11365         << FD->getDeclName() << getLangOpts().CPlusPlus;
11366   else
11367     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11368 
11369   Diag(Definition->getLocation(), diag::note_previous_definition);
11370   FD->setInvalidDecl();
11371 }
11372 
11373 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11374                                    Sema &S) {
11375   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11376 
11377   LambdaScopeInfo *LSI = S.PushLambdaScope();
11378   LSI->CallOperator = CallOperator;
11379   LSI->Lambda = LambdaClass;
11380   LSI->ReturnType = CallOperator->getReturnType();
11381   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11382 
11383   if (LCD == LCD_None)
11384     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11385   else if (LCD == LCD_ByCopy)
11386     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11387   else if (LCD == LCD_ByRef)
11388     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11389   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11390 
11391   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11392   LSI->Mutable = !CallOperator->isConst();
11393 
11394   // Add the captures to the LSI so they can be noted as already
11395   // captured within tryCaptureVar.
11396   auto I = LambdaClass->field_begin();
11397   for (const auto &C : LambdaClass->captures()) {
11398     if (C.capturesVariable()) {
11399       VarDecl *VD = C.getCapturedVar();
11400       if (VD->isInitCapture())
11401         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11402       QualType CaptureType = VD->getType();
11403       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11404       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11405           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11406           /*EllipsisLoc*/C.isPackExpansion()
11407                          ? C.getEllipsisLoc() : SourceLocation(),
11408           CaptureType, /*Expr*/ nullptr);
11409 
11410     } else if (C.capturesThis()) {
11411       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11412                               /*Expr*/ nullptr,
11413                               C.getCaptureKind() == LCK_StarThis);
11414     } else {
11415       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11416     }
11417     ++I;
11418   }
11419 }
11420 
11421 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11422                                     SkipBodyInfo *SkipBody) {
11423   // Clear the last template instantiation error context.
11424   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11425 
11426   if (!D)
11427     return D;
11428   FunctionDecl *FD = nullptr;
11429 
11430   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11431     FD = FunTmpl->getTemplatedDecl();
11432   else
11433     FD = cast<FunctionDecl>(D);
11434 
11435   // See if this is a redefinition.
11436   if (!FD->isLateTemplateParsed()) {
11437     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11438 
11439     // If we're skipping the body, we're done. Don't enter the scope.
11440     if (SkipBody && SkipBody->ShouldSkip)
11441       return D;
11442   }
11443 
11444   // If we are instantiating a generic lambda call operator, push
11445   // a LambdaScopeInfo onto the function stack.  But use the information
11446   // that's already been calculated (ActOnLambdaExpr) to prime the current
11447   // LambdaScopeInfo.
11448   // When the template operator is being specialized, the LambdaScopeInfo,
11449   // has to be properly restored so that tryCaptureVariable doesn't try
11450   // and capture any new variables. In addition when calculating potential
11451   // captures during transformation of nested lambdas, it is necessary to
11452   // have the LSI properly restored.
11453   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11454     assert(ActiveTemplateInstantiations.size() &&
11455       "There should be an active template instantiation on the stack "
11456       "when instantiating a generic lambda!");
11457     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11458   }
11459   else
11460     // Enter a new function scope
11461     PushFunctionScope();
11462 
11463   // Builtin functions cannot be defined.
11464   if (unsigned BuiltinID = FD->getBuiltinID()) {
11465     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11466         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11467       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11468       FD->setInvalidDecl();
11469     }
11470   }
11471 
11472   // The return type of a function definition must be complete
11473   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11474   QualType ResultType = FD->getReturnType();
11475   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11476       !FD->isInvalidDecl() &&
11477       RequireCompleteType(FD->getLocation(), ResultType,
11478                           diag::err_func_def_incomplete_result))
11479     FD->setInvalidDecl();
11480 
11481   if (FnBodyScope)
11482     PushDeclContext(FnBodyScope, FD);
11483 
11484   // Check the validity of our function parameters
11485   CheckParmsForFunctionDef(FD->parameters(),
11486                            /*CheckParameterNames=*/true);
11487 
11488   // Introduce our parameters into the function scope
11489   for (auto Param : FD->parameters()) {
11490     Param->setOwningFunction(FD);
11491 
11492     // If this has an identifier, add it to the scope stack.
11493     if (Param->getIdentifier() && FnBodyScope) {
11494       CheckShadow(FnBodyScope, Param);
11495 
11496       PushOnScopeChains(Param, FnBodyScope);
11497     }
11498   }
11499 
11500   // If we had any tags defined in the function prototype,
11501   // introduce them into the function scope.
11502   if (FnBodyScope) {
11503     for (ArrayRef<NamedDecl *>::iterator
11504              I = FD->getDeclsInPrototypeScope().begin(),
11505              E = FD->getDeclsInPrototypeScope().end();
11506          I != E; ++I) {
11507       NamedDecl *D = *I;
11508 
11509       // Some of these decls (like enums) may have been pinned to the
11510       // translation unit for lack of a real context earlier. If so, remove
11511       // from the translation unit and reattach to the current context.
11512       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11513         // Is the decl actually in the context?
11514         if (Context.getTranslationUnitDecl()->containsDecl(D))
11515           Context.getTranslationUnitDecl()->removeDecl(D);
11516         // Either way, reassign the lexical decl context to our FunctionDecl.
11517         D->setLexicalDeclContext(CurContext);
11518       }
11519 
11520       // If the decl has a non-null name, make accessible in the current scope.
11521       if (!D->getName().empty())
11522         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11523 
11524       // Similarly, dive into enums and fish their constants out, making them
11525       // accessible in this scope.
11526       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11527         for (auto *EI : ED->enumerators())
11528           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11529       }
11530     }
11531   }
11532 
11533   // Ensure that the function's exception specification is instantiated.
11534   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11535     ResolveExceptionSpec(D->getLocation(), FPT);
11536 
11537   // dllimport cannot be applied to non-inline function definitions.
11538   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11539       !FD->isTemplateInstantiation()) {
11540     assert(!FD->hasAttr<DLLExportAttr>());
11541     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11542     FD->setInvalidDecl();
11543     return D;
11544   }
11545   // We want to attach documentation to original Decl (which might be
11546   // a function template).
11547   ActOnDocumentableDecl(D);
11548   if (getCurLexicalContext()->isObjCContainer() &&
11549       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11550       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11551     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11552 
11553   return D;
11554 }
11555 
11556 /// \brief Given the set of return statements within a function body,
11557 /// compute the variables that are subject to the named return value
11558 /// optimization.
11559 ///
11560 /// Each of the variables that is subject to the named return value
11561 /// optimization will be marked as NRVO variables in the AST, and any
11562 /// return statement that has a marked NRVO variable as its NRVO candidate can
11563 /// use the named return value optimization.
11564 ///
11565 /// This function applies a very simplistic algorithm for NRVO: if every return
11566 /// statement in the scope of a variable has the same NRVO candidate, that
11567 /// candidate is an NRVO variable.
11568 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11569   ReturnStmt **Returns = Scope->Returns.data();
11570 
11571   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11572     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11573       if (!NRVOCandidate->isNRVOVariable())
11574         Returns[I]->setNRVOCandidate(nullptr);
11575     }
11576   }
11577 }
11578 
11579 bool Sema::canDelayFunctionBody(const Declarator &D) {
11580   // We can't delay parsing the body of a constexpr function template (yet).
11581   if (D.getDeclSpec().isConstexprSpecified())
11582     return false;
11583 
11584   // We can't delay parsing the body of a function template with a deduced
11585   // return type (yet).
11586   if (D.getDeclSpec().containsPlaceholderType()) {
11587     // If the placeholder introduces a non-deduced trailing return type,
11588     // we can still delay parsing it.
11589     if (D.getNumTypeObjects()) {
11590       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11591       if (Outer.Kind == DeclaratorChunk::Function &&
11592           Outer.Fun.hasTrailingReturnType()) {
11593         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11594         return Ty.isNull() || !Ty->isUndeducedType();
11595       }
11596     }
11597     return false;
11598   }
11599 
11600   return true;
11601 }
11602 
11603 bool Sema::canSkipFunctionBody(Decl *D) {
11604   // We cannot skip the body of a function (or function template) which is
11605   // constexpr, since we may need to evaluate its body in order to parse the
11606   // rest of the file.
11607   // We cannot skip the body of a function with an undeduced return type,
11608   // because any callers of that function need to know the type.
11609   if (const FunctionDecl *FD = D->getAsFunction())
11610     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11611       return false;
11612   return Consumer.shouldSkipFunctionBody(D);
11613 }
11614 
11615 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11616   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11617     FD->setHasSkippedBody();
11618   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11619     MD->setHasSkippedBody();
11620   return Decl;
11621 }
11622 
11623 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11624   return ActOnFinishFunctionBody(D, BodyArg, false);
11625 }
11626 
11627 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11628                                     bool IsInstantiation) {
11629   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11630 
11631   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11632   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11633 
11634   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11635     CheckCompletedCoroutineBody(FD, Body);
11636 
11637   if (FD) {
11638     FD->setBody(Body);
11639 
11640     if (getLangOpts().CPlusPlus14) {
11641       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11642           FD->getReturnType()->isUndeducedType()) {
11643         // If the function has a deduced result type but contains no 'return'
11644         // statements, the result type as written must be exactly 'auto', and
11645         // the deduced result type is 'void'.
11646         if (!FD->getReturnType()->getAs<AutoType>()) {
11647           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11648               << FD->getReturnType();
11649           FD->setInvalidDecl();
11650         } else {
11651           // Substitute 'void' for the 'auto' in the type.
11652           TypeLoc ResultType = getReturnTypeLoc(FD);
11653           Context.adjustDeducedFunctionResultType(
11654               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11655         }
11656       }
11657     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11658       // In C++11, we don't use 'auto' deduction rules for lambda call
11659       // operators because we don't support return type deduction.
11660       auto *LSI = getCurLambda();
11661       if (LSI->HasImplicitReturnType) {
11662         deduceClosureReturnType(*LSI);
11663 
11664         // C++11 [expr.prim.lambda]p4:
11665         //   [...] if there are no return statements in the compound-statement
11666         //   [the deduced type is] the type void
11667         QualType RetType =
11668             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11669 
11670         // Update the return type to the deduced type.
11671         const FunctionProtoType *Proto =
11672             FD->getType()->getAs<FunctionProtoType>();
11673         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11674                                             Proto->getExtProtoInfo()));
11675       }
11676     }
11677 
11678     // The only way to be included in UndefinedButUsed is if there is an
11679     // ODR use before the definition. Avoid the expensive map lookup if this
11680     // is the first declaration.
11681     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11682       if (!FD->isExternallyVisible())
11683         UndefinedButUsed.erase(FD);
11684       else if (FD->isInlined() &&
11685                !LangOpts.GNUInline &&
11686                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11687         UndefinedButUsed.erase(FD);
11688     }
11689 
11690     // If the function implicitly returns zero (like 'main') or is naked,
11691     // don't complain about missing return statements.
11692     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11693       WP.disableCheckFallThrough();
11694 
11695     // MSVC permits the use of pure specifier (=0) on function definition,
11696     // defined at class scope, warn about this non-standard construct.
11697     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11698       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11699 
11700     if (!FD->isInvalidDecl()) {
11701       // Don't diagnose unused parameters of defaulted or deleted functions.
11702       if (!FD->isDeleted() && !FD->isDefaulted())
11703         DiagnoseUnusedParameters(FD->parameters());
11704       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11705                                              FD->getReturnType(), FD);
11706 
11707       // If this is a structor, we need a vtable.
11708       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11709         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11710       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11711         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11712 
11713       // Try to apply the named return value optimization. We have to check
11714       // if we can do this here because lambdas keep return statements around
11715       // to deduce an implicit return type.
11716       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11717           !FD->isDependentContext())
11718         computeNRVO(Body, getCurFunction());
11719     }
11720 
11721     // GNU warning -Wmissing-prototypes:
11722     //   Warn if a global function is defined without a previous
11723     //   prototype declaration. This warning is issued even if the
11724     //   definition itself provides a prototype. The aim is to detect
11725     //   global functions that fail to be declared in header files.
11726     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11727     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11728       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11729 
11730       if (PossibleZeroParamPrototype) {
11731         // We found a declaration that is not a prototype,
11732         // but that could be a zero-parameter prototype
11733         if (TypeSourceInfo *TI =
11734                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11735           TypeLoc TL = TI->getTypeLoc();
11736           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11737             Diag(PossibleZeroParamPrototype->getLocation(),
11738                  diag::note_declaration_not_a_prototype)
11739                 << PossibleZeroParamPrototype
11740                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11741         }
11742       }
11743     }
11744 
11745     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11746       const CXXMethodDecl *KeyFunction;
11747       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11748           MD->isVirtual() &&
11749           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11750           MD == KeyFunction->getCanonicalDecl()) {
11751         // Update the key-function state if necessary for this ABI.
11752         if (FD->isInlined() &&
11753             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11754           Context.setNonKeyFunction(MD);
11755 
11756           // If the newly-chosen key function is already defined, then we
11757           // need to mark the vtable as used retroactively.
11758           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11759           const FunctionDecl *Definition;
11760           if (KeyFunction && KeyFunction->isDefined(Definition))
11761             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11762         } else {
11763           // We just defined they key function; mark the vtable as used.
11764           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11765         }
11766       }
11767     }
11768 
11769     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11770            "Function parsing confused");
11771   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11772     assert(MD == getCurMethodDecl() && "Method parsing confused");
11773     MD->setBody(Body);
11774     if (!MD->isInvalidDecl()) {
11775       DiagnoseUnusedParameters(MD->parameters());
11776       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11777                                              MD->getReturnType(), MD);
11778 
11779       if (Body)
11780         computeNRVO(Body, getCurFunction());
11781     }
11782     if (getCurFunction()->ObjCShouldCallSuper) {
11783       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11784         << MD->getSelector().getAsString();
11785       getCurFunction()->ObjCShouldCallSuper = false;
11786     }
11787     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11788       const ObjCMethodDecl *InitMethod = nullptr;
11789       bool isDesignated =
11790           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11791       assert(isDesignated && InitMethod);
11792       (void)isDesignated;
11793 
11794       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11795         auto IFace = MD->getClassInterface();
11796         if (!IFace)
11797           return false;
11798         auto SuperD = IFace->getSuperClass();
11799         if (!SuperD)
11800           return false;
11801         return SuperD->getIdentifier() ==
11802             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11803       };
11804       // Don't issue this warning for unavailable inits or direct subclasses
11805       // of NSObject.
11806       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11807         Diag(MD->getLocation(),
11808              diag::warn_objc_designated_init_missing_super_call);
11809         Diag(InitMethod->getLocation(),
11810              diag::note_objc_designated_init_marked_here);
11811       }
11812       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11813     }
11814     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11815       // Don't issue this warning for unavaialable inits.
11816       if (!MD->isUnavailable())
11817         Diag(MD->getLocation(),
11818              diag::warn_objc_secondary_init_missing_init_call);
11819       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11820     }
11821   } else {
11822     return nullptr;
11823   }
11824 
11825   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
11826     DiagnoseUnguardedAvailabilityViolations(dcl);
11827 
11828   assert(!getCurFunction()->ObjCShouldCallSuper &&
11829          "This should only be set for ObjC methods, which should have been "
11830          "handled in the block above.");
11831 
11832   // Verify and clean out per-function state.
11833   if (Body && (!FD || !FD->isDefaulted())) {
11834     // C++ constructors that have function-try-blocks can't have return
11835     // statements in the handlers of that block. (C++ [except.handle]p14)
11836     // Verify this.
11837     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11838       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11839 
11840     // Verify that gotos and switch cases don't jump into scopes illegally.
11841     if (getCurFunction()->NeedsScopeChecking() &&
11842         !PP.isCodeCompletionEnabled())
11843       DiagnoseInvalidJumps(Body);
11844 
11845     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11846       if (!Destructor->getParent()->isDependentType())
11847         CheckDestructor(Destructor);
11848 
11849       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11850                                              Destructor->getParent());
11851     }
11852 
11853     // If any errors have occurred, clear out any temporaries that may have
11854     // been leftover. This ensures that these temporaries won't be picked up for
11855     // deletion in some later function.
11856     if (getDiagnostics().hasErrorOccurred() ||
11857         getDiagnostics().getSuppressAllDiagnostics()) {
11858       DiscardCleanupsInEvaluationContext();
11859     }
11860     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11861         !isa<FunctionTemplateDecl>(dcl)) {
11862       // Since the body is valid, issue any analysis-based warnings that are
11863       // enabled.
11864       ActivePolicy = &WP;
11865     }
11866 
11867     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11868         (!CheckConstexprFunctionDecl(FD) ||
11869          !CheckConstexprFunctionBody(FD, Body)))
11870       FD->setInvalidDecl();
11871 
11872     if (FD && FD->hasAttr<NakedAttr>()) {
11873       for (const Stmt *S : Body->children()) {
11874         // Allow local register variables without initializer as they don't
11875         // require prologue.
11876         bool RegisterVariables = false;
11877         if (auto *DS = dyn_cast<DeclStmt>(S)) {
11878           for (const auto *Decl : DS->decls()) {
11879             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
11880               RegisterVariables =
11881                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
11882               if (!RegisterVariables)
11883                 break;
11884             }
11885           }
11886         }
11887         if (RegisterVariables)
11888           continue;
11889         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11890           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11891           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11892           FD->setInvalidDecl();
11893           break;
11894         }
11895       }
11896     }
11897 
11898     assert(ExprCleanupObjects.size() ==
11899                ExprEvalContexts.back().NumCleanupObjects &&
11900            "Leftover temporaries in function");
11901     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
11902     assert(MaybeODRUseExprs.empty() &&
11903            "Leftover expressions for odr-use checking");
11904   }
11905 
11906   if (!IsInstantiation)
11907     PopDeclContext();
11908 
11909   PopFunctionScopeInfo(ActivePolicy, dcl);
11910   // If any errors have occurred, clear out any temporaries that may have
11911   // been leftover. This ensures that these temporaries won't be picked up for
11912   // deletion in some later function.
11913   if (getDiagnostics().hasErrorOccurred()) {
11914     DiscardCleanupsInEvaluationContext();
11915   }
11916 
11917   return dcl;
11918 }
11919 
11920 /// When we finish delayed parsing of an attribute, we must attach it to the
11921 /// relevant Decl.
11922 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11923                                        ParsedAttributes &Attrs) {
11924   // Always attach attributes to the underlying decl.
11925   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11926     D = TD->getTemplatedDecl();
11927   ProcessDeclAttributeList(S, D, Attrs.getList());
11928 
11929   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11930     if (Method->isStatic())
11931       checkThisInStaticMemberFunctionAttributes(Method);
11932 }
11933 
11934 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11935 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11936 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11937                                           IdentifierInfo &II, Scope *S) {
11938   // Before we produce a declaration for an implicitly defined
11939   // function, see whether there was a locally-scoped declaration of
11940   // this name as a function or variable. If so, use that
11941   // (non-visible) declaration, and complain about it.
11942   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11943     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11944     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11945     return ExternCPrev;
11946   }
11947 
11948   // Extension in C99.  Legal in C90, but warn about it.
11949   unsigned diag_id;
11950   if (II.getName().startswith("__builtin_"))
11951     diag_id = diag::warn_builtin_unknown;
11952   else if (getLangOpts().C99)
11953     diag_id = diag::ext_implicit_function_decl;
11954   else
11955     diag_id = diag::warn_implicit_function_decl;
11956   Diag(Loc, diag_id) << &II;
11957 
11958   // Because typo correction is expensive, only do it if the implicit
11959   // function declaration is going to be treated as an error.
11960   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11961     TypoCorrection Corrected;
11962     if (S &&
11963         (Corrected = CorrectTypo(
11964              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11965              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11966       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11967                    /*ErrorRecovery*/false);
11968   }
11969 
11970   // Set a Declarator for the implicit definition: int foo();
11971   const char *Dummy;
11972   AttributeFactory attrFactory;
11973   DeclSpec DS(attrFactory);
11974   unsigned DiagID;
11975   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11976                                   Context.getPrintingPolicy());
11977   (void)Error; // Silence warning.
11978   assert(!Error && "Error setting up implicit decl!");
11979   SourceLocation NoLoc;
11980   Declarator D(DS, Declarator::BlockContext);
11981   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11982                                              /*IsAmbiguous=*/false,
11983                                              /*LParenLoc=*/NoLoc,
11984                                              /*Params=*/nullptr,
11985                                              /*NumParams=*/0,
11986                                              /*EllipsisLoc=*/NoLoc,
11987                                              /*RParenLoc=*/NoLoc,
11988                                              /*TypeQuals=*/0,
11989                                              /*RefQualifierIsLvalueRef=*/true,
11990                                              /*RefQualifierLoc=*/NoLoc,
11991                                              /*ConstQualifierLoc=*/NoLoc,
11992                                              /*VolatileQualifierLoc=*/NoLoc,
11993                                              /*RestrictQualifierLoc=*/NoLoc,
11994                                              /*MutableLoc=*/NoLoc,
11995                                              EST_None,
11996                                              /*ESpecRange=*/SourceRange(),
11997                                              /*Exceptions=*/nullptr,
11998                                              /*ExceptionRanges=*/nullptr,
11999                                              /*NumExceptions=*/0,
12000                                              /*NoexceptExpr=*/nullptr,
12001                                              /*ExceptionSpecTokens=*/nullptr,
12002                                              Loc, Loc, D),
12003                 DS.getAttributes(),
12004                 SourceLocation());
12005   D.SetIdentifier(&II, Loc);
12006 
12007   // Insert this function into translation-unit scope.
12008 
12009   DeclContext *PrevDC = CurContext;
12010   CurContext = Context.getTranslationUnitDecl();
12011 
12012   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12013   FD->setImplicit();
12014 
12015   CurContext = PrevDC;
12016 
12017   AddKnownFunctionAttributes(FD);
12018 
12019   return FD;
12020 }
12021 
12022 /// \brief Adds any function attributes that we know a priori based on
12023 /// the declaration of this function.
12024 ///
12025 /// These attributes can apply both to implicitly-declared builtins
12026 /// (like __builtin___printf_chk) or to library-declared functions
12027 /// like NSLog or printf.
12028 ///
12029 /// We need to check for duplicate attributes both here and where user-written
12030 /// attributes are applied to declarations.
12031 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12032   if (FD->isInvalidDecl())
12033     return;
12034 
12035   // If this is a built-in function, map its builtin attributes to
12036   // actual attributes.
12037   if (unsigned BuiltinID = FD->getBuiltinID()) {
12038     // Handle printf-formatting attributes.
12039     unsigned FormatIdx;
12040     bool HasVAListArg;
12041     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12042       if (!FD->hasAttr<FormatAttr>()) {
12043         const char *fmt = "printf";
12044         unsigned int NumParams = FD->getNumParams();
12045         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12046             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12047           fmt = "NSString";
12048         FD->addAttr(FormatAttr::CreateImplicit(Context,
12049                                                &Context.Idents.get(fmt),
12050                                                FormatIdx+1,
12051                                                HasVAListArg ? 0 : FormatIdx+2,
12052                                                FD->getLocation()));
12053       }
12054     }
12055     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12056                                              HasVAListArg)) {
12057      if (!FD->hasAttr<FormatAttr>())
12058        FD->addAttr(FormatAttr::CreateImplicit(Context,
12059                                               &Context.Idents.get("scanf"),
12060                                               FormatIdx+1,
12061                                               HasVAListArg ? 0 : FormatIdx+2,
12062                                               FD->getLocation()));
12063     }
12064 
12065     // Mark const if we don't care about errno and that is the only
12066     // thing preventing the function from being const. This allows
12067     // IRgen to use LLVM intrinsics for such functions.
12068     if (!getLangOpts().MathErrno &&
12069         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12070       if (!FD->hasAttr<ConstAttr>())
12071         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12072     }
12073 
12074     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12075         !FD->hasAttr<ReturnsTwiceAttr>())
12076       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12077                                          FD->getLocation()));
12078     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12079       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12080     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12081       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12082     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12083       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12084     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12085         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12086       // Add the appropriate attribute, depending on the CUDA compilation mode
12087       // and which target the builtin belongs to. For example, during host
12088       // compilation, aux builtins are __device__, while the rest are __host__.
12089       if (getLangOpts().CUDAIsDevice !=
12090           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12091         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12092       else
12093         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12094     }
12095   }
12096 
12097   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12098   // throw, add an implicit nothrow attribute to any extern "C" function we come
12099   // across.
12100   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12101       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12102     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12103     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12104       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12105   }
12106 
12107   IdentifierInfo *Name = FD->getIdentifier();
12108   if (!Name)
12109     return;
12110   if ((!getLangOpts().CPlusPlus &&
12111        FD->getDeclContext()->isTranslationUnit()) ||
12112       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12113        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12114        LinkageSpecDecl::lang_c)) {
12115     // Okay: this could be a libc/libm/Objective-C function we know
12116     // about.
12117   } else
12118     return;
12119 
12120   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12121     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12122     // target-specific builtins, perhaps?
12123     if (!FD->hasAttr<FormatAttr>())
12124       FD->addAttr(FormatAttr::CreateImplicit(Context,
12125                                              &Context.Idents.get("printf"), 2,
12126                                              Name->isStr("vasprintf") ? 0 : 3,
12127                                              FD->getLocation()));
12128   }
12129 
12130   if (Name->isStr("__CFStringMakeConstantString")) {
12131     // We already have a __builtin___CFStringMakeConstantString,
12132     // but builds that use -fno-constant-cfstrings don't go through that.
12133     if (!FD->hasAttr<FormatArgAttr>())
12134       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12135                                                 FD->getLocation()));
12136   }
12137 }
12138 
12139 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12140                                     TypeSourceInfo *TInfo) {
12141   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12142   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12143 
12144   if (!TInfo) {
12145     assert(D.isInvalidType() && "no declarator info for valid type");
12146     TInfo = Context.getTrivialTypeSourceInfo(T);
12147   }
12148 
12149   // Scope manipulation handled by caller.
12150   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12151                                            D.getLocStart(),
12152                                            D.getIdentifierLoc(),
12153                                            D.getIdentifier(),
12154                                            TInfo);
12155 
12156   // Bail out immediately if we have an invalid declaration.
12157   if (D.isInvalidType()) {
12158     NewTD->setInvalidDecl();
12159     return NewTD;
12160   }
12161 
12162   if (D.getDeclSpec().isModulePrivateSpecified()) {
12163     if (CurContext->isFunctionOrMethod())
12164       Diag(NewTD->getLocation(), diag::err_module_private_local)
12165         << 2 << NewTD->getDeclName()
12166         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12167         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12168     else
12169       NewTD->setModulePrivate();
12170   }
12171 
12172   // C++ [dcl.typedef]p8:
12173   //   If the typedef declaration defines an unnamed class (or
12174   //   enum), the first typedef-name declared by the declaration
12175   //   to be that class type (or enum type) is used to denote the
12176   //   class type (or enum type) for linkage purposes only.
12177   // We need to check whether the type was declared in the declaration.
12178   switch (D.getDeclSpec().getTypeSpecType()) {
12179   case TST_enum:
12180   case TST_struct:
12181   case TST_interface:
12182   case TST_union:
12183   case TST_class: {
12184     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12185     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12186     break;
12187   }
12188 
12189   default:
12190     break;
12191   }
12192 
12193   return NewTD;
12194 }
12195 
12196 /// \brief Check that this is a valid underlying type for an enum declaration.
12197 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12198   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12199   QualType T = TI->getType();
12200 
12201   if (T->isDependentType())
12202     return false;
12203 
12204   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12205     if (BT->isInteger())
12206       return false;
12207 
12208   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12209   return true;
12210 }
12211 
12212 /// Check whether this is a valid redeclaration of a previous enumeration.
12213 /// \return true if the redeclaration was invalid.
12214 bool Sema::CheckEnumRedeclaration(
12215     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12216     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12217   bool IsFixed = !EnumUnderlyingTy.isNull();
12218 
12219   if (IsScoped != Prev->isScoped()) {
12220     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12221       << Prev->isScoped();
12222     Diag(Prev->getLocation(), diag::note_previous_declaration);
12223     return true;
12224   }
12225 
12226   if (IsFixed && Prev->isFixed()) {
12227     if (!EnumUnderlyingTy->isDependentType() &&
12228         !Prev->getIntegerType()->isDependentType() &&
12229         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12230                                         Prev->getIntegerType())) {
12231       // TODO: Highlight the underlying type of the redeclaration.
12232       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12233         << EnumUnderlyingTy << Prev->getIntegerType();
12234       Diag(Prev->getLocation(), diag::note_previous_declaration)
12235           << Prev->getIntegerTypeRange();
12236       return true;
12237     }
12238   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12239     ;
12240   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12241     ;
12242   } else if (IsFixed != Prev->isFixed()) {
12243     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12244       << Prev->isFixed();
12245     Diag(Prev->getLocation(), diag::note_previous_declaration);
12246     return true;
12247   }
12248 
12249   return false;
12250 }
12251 
12252 /// \brief Get diagnostic %select index for tag kind for
12253 /// redeclaration diagnostic message.
12254 /// WARNING: Indexes apply to particular diagnostics only!
12255 ///
12256 /// \returns diagnostic %select index.
12257 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12258   switch (Tag) {
12259   case TTK_Struct: return 0;
12260   case TTK_Interface: return 1;
12261   case TTK_Class:  return 2;
12262   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12263   }
12264 }
12265 
12266 /// \brief Determine if tag kind is a class-key compatible with
12267 /// class for redeclaration (class, struct, or __interface).
12268 ///
12269 /// \returns true iff the tag kind is compatible.
12270 static bool isClassCompatTagKind(TagTypeKind Tag)
12271 {
12272   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12273 }
12274 
12275 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl) {
12276   if (isa<TypedefDecl>(PrevDecl))
12277     return NTK_Typedef;
12278   else if (isa<TypeAliasDecl>(PrevDecl))
12279     return NTK_TypeAlias;
12280   else if (isa<ClassTemplateDecl>(PrevDecl))
12281     return NTK_Template;
12282   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12283     return NTK_TypeAliasTemplate;
12284   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12285     return NTK_TemplateTemplateArgument;
12286   return NTK_Unknown;
12287 }
12288 
12289 /// \brief Determine whether a tag with a given kind is acceptable
12290 /// as a redeclaration of the given tag declaration.
12291 ///
12292 /// \returns true if the new tag kind is acceptable, false otherwise.
12293 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12294                                         TagTypeKind NewTag, bool isDefinition,
12295                                         SourceLocation NewTagLoc,
12296                                         const IdentifierInfo *Name) {
12297   // C++ [dcl.type.elab]p3:
12298   //   The class-key or enum keyword present in the
12299   //   elaborated-type-specifier shall agree in kind with the
12300   //   declaration to which the name in the elaborated-type-specifier
12301   //   refers. This rule also applies to the form of
12302   //   elaborated-type-specifier that declares a class-name or
12303   //   friend class since it can be construed as referring to the
12304   //   definition of the class. Thus, in any
12305   //   elaborated-type-specifier, the enum keyword shall be used to
12306   //   refer to an enumeration (7.2), the union class-key shall be
12307   //   used to refer to a union (clause 9), and either the class or
12308   //   struct class-key shall be used to refer to a class (clause 9)
12309   //   declared using the class or struct class-key.
12310   TagTypeKind OldTag = Previous->getTagKind();
12311   if (!isDefinition || !isClassCompatTagKind(NewTag))
12312     if (OldTag == NewTag)
12313       return true;
12314 
12315   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12316     // Warn about the struct/class tag mismatch.
12317     bool isTemplate = false;
12318     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12319       isTemplate = Record->getDescribedClassTemplate();
12320 
12321     if (!ActiveTemplateInstantiations.empty()) {
12322       // In a template instantiation, do not offer fix-its for tag mismatches
12323       // since they usually mess up the template instead of fixing the problem.
12324       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12325         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12326         << getRedeclDiagFromTagKind(OldTag);
12327       return true;
12328     }
12329 
12330     if (isDefinition) {
12331       // On definitions, check previous tags and issue a fix-it for each
12332       // one that doesn't match the current tag.
12333       if (Previous->getDefinition()) {
12334         // Don't suggest fix-its for redefinitions.
12335         return true;
12336       }
12337 
12338       bool previousMismatch = false;
12339       for (auto I : Previous->redecls()) {
12340         if (I->getTagKind() != NewTag) {
12341           if (!previousMismatch) {
12342             previousMismatch = true;
12343             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12344               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12345               << getRedeclDiagFromTagKind(I->getTagKind());
12346           }
12347           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12348             << getRedeclDiagFromTagKind(NewTag)
12349             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12350                  TypeWithKeyword::getTagTypeKindName(NewTag));
12351         }
12352       }
12353       return true;
12354     }
12355 
12356     // Check for a previous definition.  If current tag and definition
12357     // are same type, do nothing.  If no definition, but disagree with
12358     // with previous tag type, give a warning, but no fix-it.
12359     const TagDecl *Redecl = Previous->getDefinition() ?
12360                             Previous->getDefinition() : Previous;
12361     if (Redecl->getTagKind() == NewTag) {
12362       return true;
12363     }
12364 
12365     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12366       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12367       << getRedeclDiagFromTagKind(OldTag);
12368     Diag(Redecl->getLocation(), diag::note_previous_use);
12369 
12370     // If there is a previous definition, suggest a fix-it.
12371     if (Previous->getDefinition()) {
12372         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12373           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12374           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12375                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12376     }
12377 
12378     return true;
12379   }
12380   return false;
12381 }
12382 
12383 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12384 /// from an outer enclosing namespace or file scope inside a friend declaration.
12385 /// This should provide the commented out code in the following snippet:
12386 ///   namespace N {
12387 ///     struct X;
12388 ///     namespace M {
12389 ///       struct Y { friend struct /*N::*/ X; };
12390 ///     }
12391 ///   }
12392 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12393                                          SourceLocation NameLoc) {
12394   // While the decl is in a namespace, do repeated lookup of that name and see
12395   // if we get the same namespace back.  If we do not, continue until
12396   // translation unit scope, at which point we have a fully qualified NNS.
12397   SmallVector<IdentifierInfo *, 4> Namespaces;
12398   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12399   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12400     // This tag should be declared in a namespace, which can only be enclosed by
12401     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12402     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12403     if (!Namespace || Namespace->isAnonymousNamespace())
12404       return FixItHint();
12405     IdentifierInfo *II = Namespace->getIdentifier();
12406     Namespaces.push_back(II);
12407     NamedDecl *Lookup = SemaRef.LookupSingleName(
12408         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12409     if (Lookup == Namespace)
12410       break;
12411   }
12412 
12413   // Once we have all the namespaces, reverse them to go outermost first, and
12414   // build an NNS.
12415   SmallString<64> Insertion;
12416   llvm::raw_svector_ostream OS(Insertion);
12417   if (DC->isTranslationUnit())
12418     OS << "::";
12419   std::reverse(Namespaces.begin(), Namespaces.end());
12420   for (auto *II : Namespaces)
12421     OS << II->getName() << "::";
12422   return FixItHint::CreateInsertion(NameLoc, Insertion);
12423 }
12424 
12425 /// \brief Determine whether a tag originally declared in context \p OldDC can
12426 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12427 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12428 /// using-declaration).
12429 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12430                                          DeclContext *NewDC) {
12431   OldDC = OldDC->getRedeclContext();
12432   NewDC = NewDC->getRedeclContext();
12433 
12434   if (OldDC->Equals(NewDC))
12435     return true;
12436 
12437   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12438   // encloses the other).
12439   if (S.getLangOpts().MSVCCompat &&
12440       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12441     return true;
12442 
12443   return false;
12444 }
12445 
12446 /// Find the DeclContext in which a tag is implicitly declared if we see an
12447 /// elaborated type specifier in the specified context, and lookup finds
12448 /// nothing.
12449 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12450   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12451     DC = DC->getParent();
12452   return DC;
12453 }
12454 
12455 /// Find the Scope in which a tag is implicitly declared if we see an
12456 /// elaborated type specifier in the specified context, and lookup finds
12457 /// nothing.
12458 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12459   while (S->isClassScope() ||
12460          (LangOpts.CPlusPlus &&
12461           S->isFunctionPrototypeScope()) ||
12462          ((S->getFlags() & Scope::DeclScope) == 0) ||
12463          (S->getEntity() && S->getEntity()->isTransparentContext()))
12464     S = S->getParent();
12465   return S;
12466 }
12467 
12468 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12469 /// former case, Name will be non-null.  In the later case, Name will be null.
12470 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12471 /// reference/declaration/definition of a tag.
12472 ///
12473 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12474 /// trailing-type-specifier) other than one in an alias-declaration.
12475 ///
12476 /// \param SkipBody If non-null, will be set to indicate if the caller should
12477 /// skip the definition of this tag and treat it as if it were a declaration.
12478 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12479                      SourceLocation KWLoc, CXXScopeSpec &SS,
12480                      IdentifierInfo *Name, SourceLocation NameLoc,
12481                      AttributeList *Attr, AccessSpecifier AS,
12482                      SourceLocation ModulePrivateLoc,
12483                      MultiTemplateParamsArg TemplateParameterLists,
12484                      bool &OwnedDecl, bool &IsDependent,
12485                      SourceLocation ScopedEnumKWLoc,
12486                      bool ScopedEnumUsesClassTag,
12487                      TypeResult UnderlyingType,
12488                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12489   // If this is not a definition, it must have a name.
12490   IdentifierInfo *OrigName = Name;
12491   assert((Name != nullptr || TUK == TUK_Definition) &&
12492          "Nameless record must be a definition!");
12493   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12494 
12495   OwnedDecl = false;
12496   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12497   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12498 
12499   // FIXME: Check explicit specializations more carefully.
12500   bool isExplicitSpecialization = false;
12501   bool Invalid = false;
12502 
12503   // We only need to do this matching if we have template parameters
12504   // or a scope specifier, which also conveniently avoids this work
12505   // for non-C++ cases.
12506   if (TemplateParameterLists.size() > 0 ||
12507       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12508     if (TemplateParameterList *TemplateParams =
12509             MatchTemplateParametersToScopeSpecifier(
12510                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12511                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12512       if (Kind == TTK_Enum) {
12513         Diag(KWLoc, diag::err_enum_template);
12514         return nullptr;
12515       }
12516 
12517       if (TemplateParams->size() > 0) {
12518         // This is a declaration or definition of a class template (which may
12519         // be a member of another template).
12520 
12521         if (Invalid)
12522           return nullptr;
12523 
12524         OwnedDecl = false;
12525         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12526                                                SS, Name, NameLoc, Attr,
12527                                                TemplateParams, AS,
12528                                                ModulePrivateLoc,
12529                                                /*FriendLoc*/SourceLocation(),
12530                                                TemplateParameterLists.size()-1,
12531                                                TemplateParameterLists.data(),
12532                                                SkipBody);
12533         return Result.get();
12534       } else {
12535         // The "template<>" header is extraneous.
12536         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12537           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12538         isExplicitSpecialization = true;
12539       }
12540     }
12541   }
12542 
12543   // Figure out the underlying type if this a enum declaration. We need to do
12544   // this early, because it's needed to detect if this is an incompatible
12545   // redeclaration.
12546   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12547   bool EnumUnderlyingIsImplicit = false;
12548 
12549   if (Kind == TTK_Enum) {
12550     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12551       // No underlying type explicitly specified, or we failed to parse the
12552       // type, default to int.
12553       EnumUnderlying = Context.IntTy.getTypePtr();
12554     else if (UnderlyingType.get()) {
12555       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12556       // integral type; any cv-qualification is ignored.
12557       TypeSourceInfo *TI = nullptr;
12558       GetTypeFromParser(UnderlyingType.get(), &TI);
12559       EnumUnderlying = TI;
12560 
12561       if (CheckEnumUnderlyingType(TI))
12562         // Recover by falling back to int.
12563         EnumUnderlying = Context.IntTy.getTypePtr();
12564 
12565       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12566                                           UPPC_FixedUnderlyingType))
12567         EnumUnderlying = Context.IntTy.getTypePtr();
12568 
12569     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12570       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12571         // Microsoft enums are always of int type.
12572         EnumUnderlying = Context.IntTy.getTypePtr();
12573         EnumUnderlyingIsImplicit = true;
12574       }
12575     }
12576   }
12577 
12578   DeclContext *SearchDC = CurContext;
12579   DeclContext *DC = CurContext;
12580   bool isStdBadAlloc = false;
12581   bool isStdAlignValT = false;
12582 
12583   RedeclarationKind Redecl = ForRedeclaration;
12584   if (TUK == TUK_Friend || TUK == TUK_Reference)
12585     Redecl = NotForRedeclaration;
12586 
12587   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12588   if (Name && SS.isNotEmpty()) {
12589     // We have a nested-name tag ('struct foo::bar').
12590 
12591     // Check for invalid 'foo::'.
12592     if (SS.isInvalid()) {
12593       Name = nullptr;
12594       goto CreateNewDecl;
12595     }
12596 
12597     // If this is a friend or a reference to a class in a dependent
12598     // context, don't try to make a decl for it.
12599     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12600       DC = computeDeclContext(SS, false);
12601       if (!DC) {
12602         IsDependent = true;
12603         return nullptr;
12604       }
12605     } else {
12606       DC = computeDeclContext(SS, true);
12607       if (!DC) {
12608         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12609           << SS.getRange();
12610         return nullptr;
12611       }
12612     }
12613 
12614     if (RequireCompleteDeclContext(SS, DC))
12615       return nullptr;
12616 
12617     SearchDC = DC;
12618     // Look-up name inside 'foo::'.
12619     LookupQualifiedName(Previous, DC);
12620 
12621     if (Previous.isAmbiguous())
12622       return nullptr;
12623 
12624     if (Previous.empty()) {
12625       // Name lookup did not find anything. However, if the
12626       // nested-name-specifier refers to the current instantiation,
12627       // and that current instantiation has any dependent base
12628       // classes, we might find something at instantiation time: treat
12629       // this as a dependent elaborated-type-specifier.
12630       // But this only makes any sense for reference-like lookups.
12631       if (Previous.wasNotFoundInCurrentInstantiation() &&
12632           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12633         IsDependent = true;
12634         return nullptr;
12635       }
12636 
12637       // A tag 'foo::bar' must already exist.
12638       Diag(NameLoc, diag::err_not_tag_in_scope)
12639         << Kind << Name << DC << SS.getRange();
12640       Name = nullptr;
12641       Invalid = true;
12642       goto CreateNewDecl;
12643     }
12644   } else if (Name) {
12645     // C++14 [class.mem]p14:
12646     //   If T is the name of a class, then each of the following shall have a
12647     //   name different from T:
12648     //    -- every member of class T that is itself a type
12649     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12650         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12651       return nullptr;
12652 
12653     // If this is a named struct, check to see if there was a previous forward
12654     // declaration or definition.
12655     // FIXME: We're looking into outer scopes here, even when we
12656     // shouldn't be. Doing so can result in ambiguities that we
12657     // shouldn't be diagnosing.
12658     LookupName(Previous, S);
12659 
12660     // When declaring or defining a tag, ignore ambiguities introduced
12661     // by types using'ed into this scope.
12662     if (Previous.isAmbiguous() &&
12663         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12664       LookupResult::Filter F = Previous.makeFilter();
12665       while (F.hasNext()) {
12666         NamedDecl *ND = F.next();
12667         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12668                 SearchDC->getRedeclContext()))
12669           F.erase();
12670       }
12671       F.done();
12672     }
12673 
12674     // C++11 [namespace.memdef]p3:
12675     //   If the name in a friend declaration is neither qualified nor
12676     //   a template-id and the declaration is a function or an
12677     //   elaborated-type-specifier, the lookup to determine whether
12678     //   the entity has been previously declared shall not consider
12679     //   any scopes outside the innermost enclosing namespace.
12680     //
12681     // MSVC doesn't implement the above rule for types, so a friend tag
12682     // declaration may be a redeclaration of a type declared in an enclosing
12683     // scope.  They do implement this rule for friend functions.
12684     //
12685     // Does it matter that this should be by scope instead of by
12686     // semantic context?
12687     if (!Previous.empty() && TUK == TUK_Friend) {
12688       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12689       LookupResult::Filter F = Previous.makeFilter();
12690       bool FriendSawTagOutsideEnclosingNamespace = false;
12691       while (F.hasNext()) {
12692         NamedDecl *ND = F.next();
12693         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12694         if (DC->isFileContext() &&
12695             !EnclosingNS->Encloses(ND->getDeclContext())) {
12696           if (getLangOpts().MSVCCompat)
12697             FriendSawTagOutsideEnclosingNamespace = true;
12698           else
12699             F.erase();
12700         }
12701       }
12702       F.done();
12703 
12704       // Diagnose this MSVC extension in the easy case where lookup would have
12705       // unambiguously found something outside the enclosing namespace.
12706       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12707         NamedDecl *ND = Previous.getFoundDecl();
12708         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12709             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12710       }
12711     }
12712 
12713     // Note:  there used to be some attempt at recovery here.
12714     if (Previous.isAmbiguous())
12715       return nullptr;
12716 
12717     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12718       // FIXME: This makes sure that we ignore the contexts associated
12719       // with C structs, unions, and enums when looking for a matching
12720       // tag declaration or definition. See the similar lookup tweak
12721       // in Sema::LookupName; is there a better way to deal with this?
12722       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12723         SearchDC = SearchDC->getParent();
12724     }
12725   }
12726 
12727   if (Previous.isSingleResult() &&
12728       Previous.getFoundDecl()->isTemplateParameter()) {
12729     // Maybe we will complain about the shadowed template parameter.
12730     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12731     // Just pretend that we didn't see the previous declaration.
12732     Previous.clear();
12733   }
12734 
12735   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12736       DC->Equals(getStdNamespace())) {
12737     if (Name->isStr("bad_alloc")) {
12738       // This is a declaration of or a reference to "std::bad_alloc".
12739       isStdBadAlloc = true;
12740 
12741       // If std::bad_alloc has been implicitly declared (but made invisible to
12742       // name lookup), fill in this implicit declaration as the previous
12743       // declaration, so that the declarations get chained appropriately.
12744       if (Previous.empty() && StdBadAlloc)
12745         Previous.addDecl(getStdBadAlloc());
12746     } else if (Name->isStr("align_val_t")) {
12747       isStdAlignValT = true;
12748       if (Previous.empty() && StdAlignValT)
12749         Previous.addDecl(getStdAlignValT());
12750     }
12751   }
12752 
12753   // If we didn't find a previous declaration, and this is a reference
12754   // (or friend reference), move to the correct scope.  In C++, we
12755   // also need to do a redeclaration lookup there, just in case
12756   // there's a shadow friend decl.
12757   if (Name && Previous.empty() &&
12758       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12759     if (Invalid) goto CreateNewDecl;
12760     assert(SS.isEmpty());
12761 
12762     if (TUK == TUK_Reference) {
12763       // C++ [basic.scope.pdecl]p5:
12764       //   -- for an elaborated-type-specifier of the form
12765       //
12766       //          class-key identifier
12767       //
12768       //      if the elaborated-type-specifier is used in the
12769       //      decl-specifier-seq or parameter-declaration-clause of a
12770       //      function defined in namespace scope, the identifier is
12771       //      declared as a class-name in the namespace that contains
12772       //      the declaration; otherwise, except as a friend
12773       //      declaration, the identifier is declared in the smallest
12774       //      non-class, non-function-prototype scope that contains the
12775       //      declaration.
12776       //
12777       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12778       // C structs and unions.
12779       //
12780       // It is an error in C++ to declare (rather than define) an enum
12781       // type, including via an elaborated type specifier.  We'll
12782       // diagnose that later; for now, declare the enum in the same
12783       // scope as we would have picked for any other tag type.
12784       //
12785       // GNU C also supports this behavior as part of its incomplete
12786       // enum types extension, while GNU C++ does not.
12787       //
12788       // Find the context where we'll be declaring the tag.
12789       // FIXME: We would like to maintain the current DeclContext as the
12790       // lexical context,
12791       SearchDC = getTagInjectionContext(SearchDC);
12792 
12793       // Find the scope where we'll be declaring the tag.
12794       S = getTagInjectionScope(S, getLangOpts());
12795     } else {
12796       assert(TUK == TUK_Friend);
12797       // C++ [namespace.memdef]p3:
12798       //   If a friend declaration in a non-local class first declares a
12799       //   class or function, the friend class or function is a member of
12800       //   the innermost enclosing namespace.
12801       SearchDC = SearchDC->getEnclosingNamespaceContext();
12802     }
12803 
12804     // In C++, we need to do a redeclaration lookup to properly
12805     // diagnose some problems.
12806     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12807     // hidden declaration so that we don't get ambiguity errors when using a
12808     // type declared by an elaborated-type-specifier.  In C that is not correct
12809     // and we should instead merge compatible types found by lookup.
12810     if (getLangOpts().CPlusPlus) {
12811       Previous.setRedeclarationKind(ForRedeclaration);
12812       LookupQualifiedName(Previous, SearchDC);
12813     } else {
12814       Previous.setRedeclarationKind(ForRedeclaration);
12815       LookupName(Previous, S);
12816     }
12817   }
12818 
12819   // If we have a known previous declaration to use, then use it.
12820   if (Previous.empty() && SkipBody && SkipBody->Previous)
12821     Previous.addDecl(SkipBody->Previous);
12822 
12823   if (!Previous.empty()) {
12824     NamedDecl *PrevDecl = Previous.getFoundDecl();
12825     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12826 
12827     // It's okay to have a tag decl in the same scope as a typedef
12828     // which hides a tag decl in the same scope.  Finding this
12829     // insanity with a redeclaration lookup can only actually happen
12830     // in C++.
12831     //
12832     // This is also okay for elaborated-type-specifiers, which is
12833     // technically forbidden by the current standard but which is
12834     // okay according to the likely resolution of an open issue;
12835     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12836     if (getLangOpts().CPlusPlus) {
12837       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12838         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12839           TagDecl *Tag = TT->getDecl();
12840           if (Tag->getDeclName() == Name &&
12841               Tag->getDeclContext()->getRedeclContext()
12842                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12843             PrevDecl = Tag;
12844             Previous.clear();
12845             Previous.addDecl(Tag);
12846             Previous.resolveKind();
12847           }
12848         }
12849       }
12850     }
12851 
12852     // If this is a redeclaration of a using shadow declaration, it must
12853     // declare a tag in the same context. In MSVC mode, we allow a
12854     // redefinition if either context is within the other.
12855     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12856       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12857       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12858           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12859           !(OldTag && isAcceptableTagRedeclContext(
12860                           *this, OldTag->getDeclContext(), SearchDC))) {
12861         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12862         Diag(Shadow->getTargetDecl()->getLocation(),
12863              diag::note_using_decl_target);
12864         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12865             << 0;
12866         // Recover by ignoring the old declaration.
12867         Previous.clear();
12868         goto CreateNewDecl;
12869       }
12870     }
12871 
12872     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12873       // If this is a use of a previous tag, or if the tag is already declared
12874       // in the same scope (so that the definition/declaration completes or
12875       // rementions the tag), reuse the decl.
12876       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12877           isDeclInScope(DirectPrevDecl, SearchDC, S,
12878                         SS.isNotEmpty() || isExplicitSpecialization)) {
12879         // Make sure that this wasn't declared as an enum and now used as a
12880         // struct or something similar.
12881         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12882                                           TUK == TUK_Definition, KWLoc,
12883                                           Name)) {
12884           bool SafeToContinue
12885             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12886                Kind != TTK_Enum);
12887           if (SafeToContinue)
12888             Diag(KWLoc, diag::err_use_with_wrong_tag)
12889               << Name
12890               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12891                                               PrevTagDecl->getKindName());
12892           else
12893             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12894           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12895 
12896           if (SafeToContinue)
12897             Kind = PrevTagDecl->getTagKind();
12898           else {
12899             // Recover by making this an anonymous redefinition.
12900             Name = nullptr;
12901             Previous.clear();
12902             Invalid = true;
12903           }
12904         }
12905 
12906         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12907           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12908 
12909           // If this is an elaborated-type-specifier for a scoped enumeration,
12910           // the 'class' keyword is not necessary and not permitted.
12911           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12912             if (ScopedEnum)
12913               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12914                 << PrevEnum->isScoped()
12915                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12916             return PrevTagDecl;
12917           }
12918 
12919           QualType EnumUnderlyingTy;
12920           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12921             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12922           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12923             EnumUnderlyingTy = QualType(T, 0);
12924 
12925           // All conflicts with previous declarations are recovered by
12926           // returning the previous declaration, unless this is a definition,
12927           // in which case we want the caller to bail out.
12928           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12929                                      ScopedEnum, EnumUnderlyingTy,
12930                                      EnumUnderlyingIsImplicit, PrevEnum))
12931             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12932         }
12933 
12934         // C++11 [class.mem]p1:
12935         //   A member shall not be declared twice in the member-specification,
12936         //   except that a nested class or member class template can be declared
12937         //   and then later defined.
12938         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12939             S->isDeclScope(PrevDecl)) {
12940           Diag(NameLoc, diag::ext_member_redeclared);
12941           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12942         }
12943 
12944         if (!Invalid) {
12945           // If this is a use, just return the declaration we found, unless
12946           // we have attributes.
12947           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12948             if (Attr) {
12949               // FIXME: Diagnose these attributes. For now, we create a new
12950               // declaration to hold them.
12951             } else if (TUK == TUK_Reference &&
12952                        (PrevTagDecl->getFriendObjectKind() ==
12953                             Decl::FOK_Undeclared ||
12954                         PP.getModuleContainingLocation(
12955                             PrevDecl->getLocation()) !=
12956                             PP.getModuleContainingLocation(KWLoc)) &&
12957                        SS.isEmpty()) {
12958               // This declaration is a reference to an existing entity, but
12959               // has different visibility from that entity: it either makes
12960               // a friend visible or it makes a type visible in a new module.
12961               // In either case, create a new declaration. We only do this if
12962               // the declaration would have meant the same thing if no prior
12963               // declaration were found, that is, if it was found in the same
12964               // scope where we would have injected a declaration.
12965               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12966                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12967                 return PrevTagDecl;
12968               // This is in the injected scope, create a new declaration in
12969               // that scope.
12970               S = getTagInjectionScope(S, getLangOpts());
12971             } else {
12972               return PrevTagDecl;
12973             }
12974           }
12975 
12976           // Diagnose attempts to redefine a tag.
12977           if (TUK == TUK_Definition) {
12978             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12979               // If we're defining a specialization and the previous definition
12980               // is from an implicit instantiation, don't emit an error
12981               // here; we'll catch this in the general case below.
12982               bool IsExplicitSpecializationAfterInstantiation = false;
12983               if (isExplicitSpecialization) {
12984                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12985                   IsExplicitSpecializationAfterInstantiation =
12986                     RD->getTemplateSpecializationKind() !=
12987                     TSK_ExplicitSpecialization;
12988                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12989                   IsExplicitSpecializationAfterInstantiation =
12990                     ED->getTemplateSpecializationKind() !=
12991                     TSK_ExplicitSpecialization;
12992               }
12993 
12994               NamedDecl *Hidden = nullptr;
12995               if (SkipBody && getLangOpts().CPlusPlus &&
12996                   !hasVisibleDefinition(Def, &Hidden)) {
12997                 // There is a definition of this tag, but it is not visible. We
12998                 // explicitly make use of C++'s one definition rule here, and
12999                 // assume that this definition is identical to the hidden one
13000                 // we already have. Make the existing definition visible and
13001                 // use it in place of this one.
13002                 SkipBody->ShouldSkip = true;
13003                 makeMergedDefinitionVisible(Hidden, KWLoc);
13004                 return Def;
13005               } else if (!IsExplicitSpecializationAfterInstantiation) {
13006                 // A redeclaration in function prototype scope in C isn't
13007                 // visible elsewhere, so merely issue a warning.
13008                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13009                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13010                 else
13011                   Diag(NameLoc, diag::err_redefinition) << Name;
13012                 Diag(Def->getLocation(), diag::note_previous_definition);
13013                 // If this is a redefinition, recover by making this
13014                 // struct be anonymous, which will make any later
13015                 // references get the previous definition.
13016                 Name = nullptr;
13017                 Previous.clear();
13018                 Invalid = true;
13019               }
13020             } else {
13021               // If the type is currently being defined, complain
13022               // about a nested redefinition.
13023               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13024               if (TD->isBeingDefined()) {
13025                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13026                 Diag(PrevTagDecl->getLocation(),
13027                      diag::note_previous_definition);
13028                 Name = nullptr;
13029                 Previous.clear();
13030                 Invalid = true;
13031               }
13032             }
13033 
13034             // Okay, this is definition of a previously declared or referenced
13035             // tag. We're going to create a new Decl for it.
13036           }
13037 
13038           // Okay, we're going to make a redeclaration.  If this is some kind
13039           // of reference, make sure we build the redeclaration in the same DC
13040           // as the original, and ignore the current access specifier.
13041           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13042             SearchDC = PrevTagDecl->getDeclContext();
13043             AS = AS_none;
13044           }
13045         }
13046         // If we get here we have (another) forward declaration or we
13047         // have a definition.  Just create a new decl.
13048 
13049       } else {
13050         // If we get here, this is a definition of a new tag type in a nested
13051         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13052         // new decl/type.  We set PrevDecl to NULL so that the entities
13053         // have distinct types.
13054         Previous.clear();
13055       }
13056       // If we get here, we're going to create a new Decl. If PrevDecl
13057       // is non-NULL, it's a definition of the tag declared by
13058       // PrevDecl. If it's NULL, we have a new definition.
13059 
13060     // Otherwise, PrevDecl is not a tag, but was found with tag
13061     // lookup.  This is only actually possible in C++, where a few
13062     // things like templates still live in the tag namespace.
13063     } else {
13064       // Use a better diagnostic if an elaborated-type-specifier
13065       // found the wrong kind of type on the first
13066       // (non-redeclaration) lookup.
13067       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13068           !Previous.isForRedeclaration()) {
13069         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl);
13070         Diag(NameLoc, diag::err_tag_reference_non_tag) << NTK;
13071         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13072         Invalid = true;
13073 
13074       // Otherwise, only diagnose if the declaration is in scope.
13075       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13076                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13077         // do nothing
13078 
13079       // Diagnose implicit declarations introduced by elaborated types.
13080       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13081         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl);
13082         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13083         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13084         Invalid = true;
13085 
13086       // Otherwise it's a declaration.  Call out a particularly common
13087       // case here.
13088       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13089         unsigned Kind = 0;
13090         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13091         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13092           << Name << Kind << TND->getUnderlyingType();
13093         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13094         Invalid = true;
13095 
13096       // Otherwise, diagnose.
13097       } else {
13098         // The tag name clashes with something else in the target scope,
13099         // issue an error and recover by making this tag be anonymous.
13100         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13101         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13102         Name = nullptr;
13103         Invalid = true;
13104       }
13105 
13106       // The existing declaration isn't relevant to us; we're in a
13107       // new scope, so clear out the previous declaration.
13108       Previous.clear();
13109     }
13110   }
13111 
13112 CreateNewDecl:
13113 
13114   TagDecl *PrevDecl = nullptr;
13115   if (Previous.isSingleResult())
13116     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13117 
13118   // If there is an identifier, use the location of the identifier as the
13119   // location of the decl, otherwise use the location of the struct/union
13120   // keyword.
13121   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13122 
13123   // Otherwise, create a new declaration. If there is a previous
13124   // declaration of the same entity, the two will be linked via
13125   // PrevDecl.
13126   TagDecl *New;
13127 
13128   bool IsForwardReference = false;
13129   if (Kind == TTK_Enum) {
13130     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13131     // enum X { A, B, C } D;    D should chain to X.
13132     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13133                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13134                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13135 
13136     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13137       StdAlignValT = cast<EnumDecl>(New);
13138 
13139     // If this is an undefined enum, warn.
13140     if (TUK != TUK_Definition && !Invalid) {
13141       TagDecl *Def;
13142       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13143           cast<EnumDecl>(New)->isFixed()) {
13144         // C++0x: 7.2p2: opaque-enum-declaration.
13145         // Conflicts are diagnosed above. Do nothing.
13146       }
13147       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13148         Diag(Loc, diag::ext_forward_ref_enum_def)
13149           << New;
13150         Diag(Def->getLocation(), diag::note_previous_definition);
13151       } else {
13152         unsigned DiagID = diag::ext_forward_ref_enum;
13153         if (getLangOpts().MSVCCompat)
13154           DiagID = diag::ext_ms_forward_ref_enum;
13155         else if (getLangOpts().CPlusPlus)
13156           DiagID = diag::err_forward_ref_enum;
13157         Diag(Loc, DiagID);
13158 
13159         // If this is a forward-declared reference to an enumeration, make a
13160         // note of it; we won't actually be introducing the declaration into
13161         // the declaration context.
13162         if (TUK == TUK_Reference)
13163           IsForwardReference = true;
13164       }
13165     }
13166 
13167     if (EnumUnderlying) {
13168       EnumDecl *ED = cast<EnumDecl>(New);
13169       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13170         ED->setIntegerTypeSourceInfo(TI);
13171       else
13172         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13173       ED->setPromotionType(ED->getIntegerType());
13174     }
13175   } else {
13176     // struct/union/class
13177 
13178     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13179     // struct X { int A; } D;    D should chain to X.
13180     if (getLangOpts().CPlusPlus) {
13181       // FIXME: Look for a way to use RecordDecl for simple structs.
13182       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13183                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13184 
13185       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13186         StdBadAlloc = cast<CXXRecordDecl>(New);
13187     } else
13188       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13189                                cast_or_null<RecordDecl>(PrevDecl));
13190   }
13191 
13192   // C++11 [dcl.type]p3:
13193   //   A type-specifier-seq shall not define a class or enumeration [...].
13194   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13195     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13196       << Context.getTagDeclType(New);
13197     Invalid = true;
13198   }
13199 
13200   // Maybe add qualifier info.
13201   if (SS.isNotEmpty()) {
13202     if (SS.isSet()) {
13203       // If this is either a declaration or a definition, check the
13204       // nested-name-specifier against the current context. We don't do this
13205       // for explicit specializations, because they have similar checking
13206       // (with more specific diagnostics) in the call to
13207       // CheckMemberSpecialization, below.
13208       if (!isExplicitSpecialization &&
13209           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13210           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13211         Invalid = true;
13212 
13213       New->setQualifierInfo(SS.getWithLocInContext(Context));
13214       if (TemplateParameterLists.size() > 0) {
13215         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13216       }
13217     }
13218     else
13219       Invalid = true;
13220   }
13221 
13222   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13223     // Add alignment attributes if necessary; these attributes are checked when
13224     // the ASTContext lays out the structure.
13225     //
13226     // It is important for implementing the correct semantics that this
13227     // happen here (in act on tag decl). The #pragma pack stack is
13228     // maintained as a result of parser callbacks which can occur at
13229     // many points during the parsing of a struct declaration (because
13230     // the #pragma tokens are effectively skipped over during the
13231     // parsing of the struct).
13232     if (TUK == TUK_Definition) {
13233       AddAlignmentAttributesForRecord(RD);
13234       AddMsStructLayoutForRecord(RD);
13235     }
13236   }
13237 
13238   if (ModulePrivateLoc.isValid()) {
13239     if (isExplicitSpecialization)
13240       Diag(New->getLocation(), diag::err_module_private_specialization)
13241         << 2
13242         << FixItHint::CreateRemoval(ModulePrivateLoc);
13243     // __module_private__ does not apply to local classes. However, we only
13244     // diagnose this as an error when the declaration specifiers are
13245     // freestanding. Here, we just ignore the __module_private__.
13246     else if (!SearchDC->isFunctionOrMethod())
13247       New->setModulePrivate();
13248   }
13249 
13250   // If this is a specialization of a member class (of a class template),
13251   // check the specialization.
13252   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13253     Invalid = true;
13254 
13255   // If we're declaring or defining a tag in function prototype scope in C,
13256   // note that this type can only be used within the function and add it to
13257   // the list of decls to inject into the function definition scope.
13258   if ((Name || Kind == TTK_Enum) &&
13259       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13260     if (getLangOpts().CPlusPlus) {
13261       // C++ [dcl.fct]p6:
13262       //   Types shall not be defined in return or parameter types.
13263       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13264         Diag(Loc, diag::err_type_defined_in_param_type)
13265             << Name;
13266         Invalid = true;
13267       }
13268     } else if (!PrevDecl) {
13269       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13270     }
13271     DeclsInPrototypeScope.push_back(New);
13272   }
13273 
13274   if (Invalid)
13275     New->setInvalidDecl();
13276 
13277   if (Attr)
13278     ProcessDeclAttributeList(S, New, Attr);
13279 
13280   // Set the lexical context. If the tag has a C++ scope specifier, the
13281   // lexical context will be different from the semantic context.
13282   New->setLexicalDeclContext(CurContext);
13283 
13284   // Mark this as a friend decl if applicable.
13285   // In Microsoft mode, a friend declaration also acts as a forward
13286   // declaration so we always pass true to setObjectOfFriendDecl to make
13287   // the tag name visible.
13288   if (TUK == TUK_Friend)
13289     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13290 
13291   // Set the access specifier.
13292   if (!Invalid && SearchDC->isRecord())
13293     SetMemberAccessSpecifier(New, PrevDecl, AS);
13294 
13295   if (TUK == TUK_Definition)
13296     New->startDefinition();
13297 
13298   // If this has an identifier, add it to the scope stack.
13299   if (TUK == TUK_Friend) {
13300     // We might be replacing an existing declaration in the lookup tables;
13301     // if so, borrow its access specifier.
13302     if (PrevDecl)
13303       New->setAccess(PrevDecl->getAccess());
13304 
13305     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13306     DC->makeDeclVisibleInContext(New);
13307     if (Name) // can be null along some error paths
13308       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13309         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13310   } else if (Name) {
13311     S = getNonFieldDeclScope(S);
13312     PushOnScopeChains(New, S, !IsForwardReference);
13313     if (IsForwardReference)
13314       SearchDC->makeDeclVisibleInContext(New);
13315   } else {
13316     CurContext->addDecl(New);
13317   }
13318 
13319   // If this is the C FILE type, notify the AST context.
13320   if (IdentifierInfo *II = New->getIdentifier())
13321     if (!New->isInvalidDecl() &&
13322         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13323         II->isStr("FILE"))
13324       Context.setFILEDecl(New);
13325 
13326   if (PrevDecl)
13327     mergeDeclAttributes(New, PrevDecl);
13328 
13329   // If there's a #pragma GCC visibility in scope, set the visibility of this
13330   // record.
13331   AddPushedVisibilityAttribute(New);
13332 
13333   OwnedDecl = true;
13334   // In C++, don't return an invalid declaration. We can't recover well from
13335   // the cases where we make the type anonymous.
13336   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13337 }
13338 
13339 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13340   AdjustDeclIfTemplate(TagD);
13341   TagDecl *Tag = cast<TagDecl>(TagD);
13342 
13343   // Enter the tag context.
13344   PushDeclContext(S, Tag);
13345 
13346   ActOnDocumentableDecl(TagD);
13347 
13348   // If there's a #pragma GCC visibility in scope, set the visibility of this
13349   // record.
13350   AddPushedVisibilityAttribute(Tag);
13351 }
13352 
13353 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13354   assert(isa<ObjCContainerDecl>(IDecl) &&
13355          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13356   DeclContext *OCD = cast<DeclContext>(IDecl);
13357   assert(getContainingDC(OCD) == CurContext &&
13358       "The next DeclContext should be lexically contained in the current one.");
13359   CurContext = OCD;
13360   return IDecl;
13361 }
13362 
13363 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13364                                            SourceLocation FinalLoc,
13365                                            bool IsFinalSpelledSealed,
13366                                            SourceLocation LBraceLoc) {
13367   AdjustDeclIfTemplate(TagD);
13368   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13369 
13370   FieldCollector->StartClass();
13371 
13372   if (!Record->getIdentifier())
13373     return;
13374 
13375   if (FinalLoc.isValid())
13376     Record->addAttr(new (Context)
13377                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13378 
13379   // C++ [class]p2:
13380   //   [...] The class-name is also inserted into the scope of the
13381   //   class itself; this is known as the injected-class-name. For
13382   //   purposes of access checking, the injected-class-name is treated
13383   //   as if it were a public member name.
13384   CXXRecordDecl *InjectedClassName
13385     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13386                             Record->getLocStart(), Record->getLocation(),
13387                             Record->getIdentifier(),
13388                             /*PrevDecl=*/nullptr,
13389                             /*DelayTypeCreation=*/true);
13390   Context.getTypeDeclType(InjectedClassName, Record);
13391   InjectedClassName->setImplicit();
13392   InjectedClassName->setAccess(AS_public);
13393   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13394       InjectedClassName->setDescribedClassTemplate(Template);
13395   PushOnScopeChains(InjectedClassName, S);
13396   assert(InjectedClassName->isInjectedClassName() &&
13397          "Broken injected-class-name");
13398 }
13399 
13400 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13401                                     SourceRange BraceRange) {
13402   AdjustDeclIfTemplate(TagD);
13403   TagDecl *Tag = cast<TagDecl>(TagD);
13404   Tag->setBraceRange(BraceRange);
13405 
13406   // Make sure we "complete" the definition even it is invalid.
13407   if (Tag->isBeingDefined()) {
13408     assert(Tag->isInvalidDecl() && "We should already have completed it");
13409     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13410       RD->completeDefinition();
13411   }
13412 
13413   if (isa<CXXRecordDecl>(Tag))
13414     FieldCollector->FinishClass();
13415 
13416   // Exit this scope of this tag's definition.
13417   PopDeclContext();
13418 
13419   if (getCurLexicalContext()->isObjCContainer() &&
13420       Tag->getDeclContext()->isFileContext())
13421     Tag->setTopLevelDeclInObjCContainer();
13422 
13423   // Notify the consumer that we've defined a tag.
13424   if (!Tag->isInvalidDecl())
13425     Consumer.HandleTagDeclDefinition(Tag);
13426 }
13427 
13428 void Sema::ActOnObjCContainerFinishDefinition() {
13429   // Exit this scope of this interface definition.
13430   PopDeclContext();
13431 }
13432 
13433 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13434   assert(DC == CurContext && "Mismatch of container contexts");
13435   OriginalLexicalContext = DC;
13436   ActOnObjCContainerFinishDefinition();
13437 }
13438 
13439 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13440   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13441   OriginalLexicalContext = nullptr;
13442 }
13443 
13444 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13445   AdjustDeclIfTemplate(TagD);
13446   TagDecl *Tag = cast<TagDecl>(TagD);
13447   Tag->setInvalidDecl();
13448 
13449   // Make sure we "complete" the definition even it is invalid.
13450   if (Tag->isBeingDefined()) {
13451     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13452       RD->completeDefinition();
13453   }
13454 
13455   // We're undoing ActOnTagStartDefinition here, not
13456   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13457   // the FieldCollector.
13458 
13459   PopDeclContext();
13460 }
13461 
13462 // Note that FieldName may be null for anonymous bitfields.
13463 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13464                                 IdentifierInfo *FieldName,
13465                                 QualType FieldTy, bool IsMsStruct,
13466                                 Expr *BitWidth, bool *ZeroWidth) {
13467   // Default to true; that shouldn't confuse checks for emptiness
13468   if (ZeroWidth)
13469     *ZeroWidth = true;
13470 
13471   // C99 6.7.2.1p4 - verify the field type.
13472   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13473   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13474     // Handle incomplete types with specific error.
13475     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13476       return ExprError();
13477     if (FieldName)
13478       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13479         << FieldName << FieldTy << BitWidth->getSourceRange();
13480     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13481       << FieldTy << BitWidth->getSourceRange();
13482   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13483                                              UPPC_BitFieldWidth))
13484     return ExprError();
13485 
13486   // If the bit-width is type- or value-dependent, don't try to check
13487   // it now.
13488   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13489     return BitWidth;
13490 
13491   llvm::APSInt Value;
13492   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13493   if (ICE.isInvalid())
13494     return ICE;
13495   BitWidth = ICE.get();
13496 
13497   if (Value != 0 && ZeroWidth)
13498     *ZeroWidth = false;
13499 
13500   // Zero-width bitfield is ok for anonymous field.
13501   if (Value == 0 && FieldName)
13502     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13503 
13504   if (Value.isSigned() && Value.isNegative()) {
13505     if (FieldName)
13506       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13507                << FieldName << Value.toString(10);
13508     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13509       << Value.toString(10);
13510   }
13511 
13512   if (!FieldTy->isDependentType()) {
13513     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13514     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13515     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13516 
13517     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13518     // ABI.
13519     bool CStdConstraintViolation =
13520         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13521     bool MSBitfieldViolation =
13522         Value.ugt(TypeStorageSize) &&
13523         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13524     if (CStdConstraintViolation || MSBitfieldViolation) {
13525       unsigned DiagWidth =
13526           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13527       if (FieldName)
13528         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13529                << FieldName << (unsigned)Value.getZExtValue()
13530                << !CStdConstraintViolation << DiagWidth;
13531 
13532       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13533              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13534              << DiagWidth;
13535     }
13536 
13537     // Warn on types where the user might conceivably expect to get all
13538     // specified bits as value bits: that's all integral types other than
13539     // 'bool'.
13540     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13541       if (FieldName)
13542         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13543             << FieldName << (unsigned)Value.getZExtValue()
13544             << (unsigned)TypeWidth;
13545       else
13546         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13547             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13548     }
13549   }
13550 
13551   return BitWidth;
13552 }
13553 
13554 /// ActOnField - Each field of a C struct/union is passed into this in order
13555 /// to create a FieldDecl object for it.
13556 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13557                        Declarator &D, Expr *BitfieldWidth) {
13558   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13559                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13560                                /*InitStyle=*/ICIS_NoInit, AS_public);
13561   return Res;
13562 }
13563 
13564 /// HandleField - Analyze a field of a C struct or a C++ data member.
13565 ///
13566 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13567                              SourceLocation DeclStart,
13568                              Declarator &D, Expr *BitWidth,
13569                              InClassInitStyle InitStyle,
13570                              AccessSpecifier AS) {
13571   if (D.isDecompositionDeclarator()) {
13572     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13573     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13574       << Decomp.getSourceRange();
13575     return nullptr;
13576   }
13577 
13578   IdentifierInfo *II = D.getIdentifier();
13579   SourceLocation Loc = DeclStart;
13580   if (II) Loc = D.getIdentifierLoc();
13581 
13582   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13583   QualType T = TInfo->getType();
13584   if (getLangOpts().CPlusPlus) {
13585     CheckExtraCXXDefaultArguments(D);
13586 
13587     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13588                                         UPPC_DataMemberType)) {
13589       D.setInvalidType();
13590       T = Context.IntTy;
13591       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13592     }
13593   }
13594 
13595   // TR 18037 does not allow fields to be declared with address spaces.
13596   if (T.getQualifiers().hasAddressSpace()) {
13597     Diag(Loc, diag::err_field_with_address_space);
13598     D.setInvalidType();
13599   }
13600 
13601   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13602   // used as structure or union field: image, sampler, event or block types.
13603   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13604                           T->isSamplerT() || T->isBlockPointerType())) {
13605     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13606     D.setInvalidType();
13607   }
13608 
13609   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13610 
13611   if (D.getDeclSpec().isInlineSpecified())
13612     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13613         << getLangOpts().CPlusPlus1z;
13614   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13615     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13616          diag::err_invalid_thread)
13617       << DeclSpec::getSpecifierName(TSCS);
13618 
13619   // Check to see if this name was declared as a member previously
13620   NamedDecl *PrevDecl = nullptr;
13621   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13622   LookupName(Previous, S);
13623   switch (Previous.getResultKind()) {
13624     case LookupResult::Found:
13625     case LookupResult::FoundUnresolvedValue:
13626       PrevDecl = Previous.getAsSingle<NamedDecl>();
13627       break;
13628 
13629     case LookupResult::FoundOverloaded:
13630       PrevDecl = Previous.getRepresentativeDecl();
13631       break;
13632 
13633     case LookupResult::NotFound:
13634     case LookupResult::NotFoundInCurrentInstantiation:
13635     case LookupResult::Ambiguous:
13636       break;
13637   }
13638   Previous.suppressDiagnostics();
13639 
13640   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13641     // Maybe we will complain about the shadowed template parameter.
13642     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13643     // Just pretend that we didn't see the previous declaration.
13644     PrevDecl = nullptr;
13645   }
13646 
13647   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13648     PrevDecl = nullptr;
13649 
13650   bool Mutable
13651     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13652   SourceLocation TSSL = D.getLocStart();
13653   FieldDecl *NewFD
13654     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13655                      TSSL, AS, PrevDecl, &D);
13656 
13657   if (NewFD->isInvalidDecl())
13658     Record->setInvalidDecl();
13659 
13660   if (D.getDeclSpec().isModulePrivateSpecified())
13661     NewFD->setModulePrivate();
13662 
13663   if (NewFD->isInvalidDecl() && PrevDecl) {
13664     // Don't introduce NewFD into scope; there's already something
13665     // with the same name in the same scope.
13666   } else if (II) {
13667     PushOnScopeChains(NewFD, S);
13668   } else
13669     Record->addDecl(NewFD);
13670 
13671   return NewFD;
13672 }
13673 
13674 /// \brief Build a new FieldDecl and check its well-formedness.
13675 ///
13676 /// This routine builds a new FieldDecl given the fields name, type,
13677 /// record, etc. \p PrevDecl should refer to any previous declaration
13678 /// with the same name and in the same scope as the field to be
13679 /// created.
13680 ///
13681 /// \returns a new FieldDecl.
13682 ///
13683 /// \todo The Declarator argument is a hack. It will be removed once
13684 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13685                                 TypeSourceInfo *TInfo,
13686                                 RecordDecl *Record, SourceLocation Loc,
13687                                 bool Mutable, Expr *BitWidth,
13688                                 InClassInitStyle InitStyle,
13689                                 SourceLocation TSSL,
13690                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13691                                 Declarator *D) {
13692   IdentifierInfo *II = Name.getAsIdentifierInfo();
13693   bool InvalidDecl = false;
13694   if (D) InvalidDecl = D->isInvalidType();
13695 
13696   // If we receive a broken type, recover by assuming 'int' and
13697   // marking this declaration as invalid.
13698   if (T.isNull()) {
13699     InvalidDecl = true;
13700     T = Context.IntTy;
13701   }
13702 
13703   QualType EltTy = Context.getBaseElementType(T);
13704   if (!EltTy->isDependentType()) {
13705     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13706       // Fields of incomplete type force their record to be invalid.
13707       Record->setInvalidDecl();
13708       InvalidDecl = true;
13709     } else {
13710       NamedDecl *Def;
13711       EltTy->isIncompleteType(&Def);
13712       if (Def && Def->isInvalidDecl()) {
13713         Record->setInvalidDecl();
13714         InvalidDecl = true;
13715       }
13716     }
13717   }
13718 
13719   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13720   if (BitWidth && getLangOpts().OpenCL) {
13721     Diag(Loc, diag::err_opencl_bitfields);
13722     InvalidDecl = true;
13723   }
13724 
13725   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13726   // than a variably modified type.
13727   if (!InvalidDecl && T->isVariablyModifiedType()) {
13728     bool SizeIsNegative;
13729     llvm::APSInt Oversized;
13730 
13731     TypeSourceInfo *FixedTInfo =
13732       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13733                                                     SizeIsNegative,
13734                                                     Oversized);
13735     if (FixedTInfo) {
13736       Diag(Loc, diag::warn_illegal_constant_array_size);
13737       TInfo = FixedTInfo;
13738       T = FixedTInfo->getType();
13739     } else {
13740       if (SizeIsNegative)
13741         Diag(Loc, diag::err_typecheck_negative_array_size);
13742       else if (Oversized.getBoolValue())
13743         Diag(Loc, diag::err_array_too_large)
13744           << Oversized.toString(10);
13745       else
13746         Diag(Loc, diag::err_typecheck_field_variable_size);
13747       InvalidDecl = true;
13748     }
13749   }
13750 
13751   // Fields can not have abstract class types
13752   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13753                                              diag::err_abstract_type_in_decl,
13754                                              AbstractFieldType))
13755     InvalidDecl = true;
13756 
13757   bool ZeroWidth = false;
13758   if (InvalidDecl)
13759     BitWidth = nullptr;
13760   // If this is declared as a bit-field, check the bit-field.
13761   if (BitWidth) {
13762     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13763                               &ZeroWidth).get();
13764     if (!BitWidth) {
13765       InvalidDecl = true;
13766       BitWidth = nullptr;
13767       ZeroWidth = false;
13768     }
13769   }
13770 
13771   // Check that 'mutable' is consistent with the type of the declaration.
13772   if (!InvalidDecl && Mutable) {
13773     unsigned DiagID = 0;
13774     if (T->isReferenceType())
13775       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13776                                         : diag::err_mutable_reference;
13777     else if (T.isConstQualified())
13778       DiagID = diag::err_mutable_const;
13779 
13780     if (DiagID) {
13781       SourceLocation ErrLoc = Loc;
13782       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13783         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13784       Diag(ErrLoc, DiagID);
13785       if (DiagID != diag::ext_mutable_reference) {
13786         Mutable = false;
13787         InvalidDecl = true;
13788       }
13789     }
13790   }
13791 
13792   // C++11 [class.union]p8 (DR1460):
13793   //   At most one variant member of a union may have a
13794   //   brace-or-equal-initializer.
13795   if (InitStyle != ICIS_NoInit)
13796     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13797 
13798   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13799                                        BitWidth, Mutable, InitStyle);
13800   if (InvalidDecl)
13801     NewFD->setInvalidDecl();
13802 
13803   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13804     Diag(Loc, diag::err_duplicate_member) << II;
13805     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13806     NewFD->setInvalidDecl();
13807   }
13808 
13809   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13810     if (Record->isUnion()) {
13811       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13812         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13813         if (RDecl->getDefinition()) {
13814           // C++ [class.union]p1: An object of a class with a non-trivial
13815           // constructor, a non-trivial copy constructor, a non-trivial
13816           // destructor, or a non-trivial copy assignment operator
13817           // cannot be a member of a union, nor can an array of such
13818           // objects.
13819           if (CheckNontrivialField(NewFD))
13820             NewFD->setInvalidDecl();
13821         }
13822       }
13823 
13824       // C++ [class.union]p1: If a union contains a member of reference type,
13825       // the program is ill-formed, except when compiling with MSVC extensions
13826       // enabled.
13827       if (EltTy->isReferenceType()) {
13828         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13829                                     diag::ext_union_member_of_reference_type :
13830                                     diag::err_union_member_of_reference_type)
13831           << NewFD->getDeclName() << EltTy;
13832         if (!getLangOpts().MicrosoftExt)
13833           NewFD->setInvalidDecl();
13834       }
13835     }
13836   }
13837 
13838   // FIXME: We need to pass in the attributes given an AST
13839   // representation, not a parser representation.
13840   if (D) {
13841     // FIXME: The current scope is almost... but not entirely... correct here.
13842     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13843 
13844     if (NewFD->hasAttrs())
13845       CheckAlignasUnderalignment(NewFD);
13846   }
13847 
13848   // In auto-retain/release, infer strong retension for fields of
13849   // retainable type.
13850   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13851     NewFD->setInvalidDecl();
13852 
13853   if (T.isObjCGCWeak())
13854     Diag(Loc, diag::warn_attribute_weak_on_field);
13855 
13856   NewFD->setAccess(AS);
13857   return NewFD;
13858 }
13859 
13860 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13861   assert(FD);
13862   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13863 
13864   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13865     return false;
13866 
13867   QualType EltTy = Context.getBaseElementType(FD->getType());
13868   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13869     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13870     if (RDecl->getDefinition()) {
13871       // We check for copy constructors before constructors
13872       // because otherwise we'll never get complaints about
13873       // copy constructors.
13874 
13875       CXXSpecialMember member = CXXInvalid;
13876       // We're required to check for any non-trivial constructors. Since the
13877       // implicit default constructor is suppressed if there are any
13878       // user-declared constructors, we just need to check that there is a
13879       // trivial default constructor and a trivial copy constructor. (We don't
13880       // worry about move constructors here, since this is a C++98 check.)
13881       if (RDecl->hasNonTrivialCopyConstructor())
13882         member = CXXCopyConstructor;
13883       else if (!RDecl->hasTrivialDefaultConstructor())
13884         member = CXXDefaultConstructor;
13885       else if (RDecl->hasNonTrivialCopyAssignment())
13886         member = CXXCopyAssignment;
13887       else if (RDecl->hasNonTrivialDestructor())
13888         member = CXXDestructor;
13889 
13890       if (member != CXXInvalid) {
13891         if (!getLangOpts().CPlusPlus11 &&
13892             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13893           // Objective-C++ ARC: it is an error to have a non-trivial field of
13894           // a union. However, system headers in Objective-C programs
13895           // occasionally have Objective-C lifetime objects within unions,
13896           // and rather than cause the program to fail, we make those
13897           // members unavailable.
13898           SourceLocation Loc = FD->getLocation();
13899           if (getSourceManager().isInSystemHeader(Loc)) {
13900             if (!FD->hasAttr<UnavailableAttr>())
13901               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13902                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13903             return false;
13904           }
13905         }
13906 
13907         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13908                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13909                diag::err_illegal_union_or_anon_struct_member)
13910           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13911         DiagnoseNontrivial(RDecl, member);
13912         return !getLangOpts().CPlusPlus11;
13913       }
13914     }
13915   }
13916 
13917   return false;
13918 }
13919 
13920 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13921 ///  AST enum value.
13922 static ObjCIvarDecl::AccessControl
13923 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13924   switch (ivarVisibility) {
13925   default: llvm_unreachable("Unknown visitibility kind");
13926   case tok::objc_private: return ObjCIvarDecl::Private;
13927   case tok::objc_public: return ObjCIvarDecl::Public;
13928   case tok::objc_protected: return ObjCIvarDecl::Protected;
13929   case tok::objc_package: return ObjCIvarDecl::Package;
13930   }
13931 }
13932 
13933 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13934 /// in order to create an IvarDecl object for it.
13935 Decl *Sema::ActOnIvar(Scope *S,
13936                                 SourceLocation DeclStart,
13937                                 Declarator &D, Expr *BitfieldWidth,
13938                                 tok::ObjCKeywordKind Visibility) {
13939 
13940   IdentifierInfo *II = D.getIdentifier();
13941   Expr *BitWidth = (Expr*)BitfieldWidth;
13942   SourceLocation Loc = DeclStart;
13943   if (II) Loc = D.getIdentifierLoc();
13944 
13945   // FIXME: Unnamed fields can be handled in various different ways, for
13946   // example, unnamed unions inject all members into the struct namespace!
13947 
13948   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13949   QualType T = TInfo->getType();
13950 
13951   if (BitWidth) {
13952     // 6.7.2.1p3, 6.7.2.1p4
13953     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13954     if (!BitWidth)
13955       D.setInvalidType();
13956   } else {
13957     // Not a bitfield.
13958 
13959     // validate II.
13960 
13961   }
13962   if (T->isReferenceType()) {
13963     Diag(Loc, diag::err_ivar_reference_type);
13964     D.setInvalidType();
13965   }
13966   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13967   // than a variably modified type.
13968   else if (T->isVariablyModifiedType()) {
13969     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13970     D.setInvalidType();
13971   }
13972 
13973   // Get the visibility (access control) for this ivar.
13974   ObjCIvarDecl::AccessControl ac =
13975     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13976                                         : ObjCIvarDecl::None;
13977   // Must set ivar's DeclContext to its enclosing interface.
13978   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13979   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13980     return nullptr;
13981   ObjCContainerDecl *EnclosingContext;
13982   if (ObjCImplementationDecl *IMPDecl =
13983       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13984     if (LangOpts.ObjCRuntime.isFragile()) {
13985     // Case of ivar declared in an implementation. Context is that of its class.
13986       EnclosingContext = IMPDecl->getClassInterface();
13987       assert(EnclosingContext && "Implementation has no class interface!");
13988     }
13989     else
13990       EnclosingContext = EnclosingDecl;
13991   } else {
13992     if (ObjCCategoryDecl *CDecl =
13993         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13994       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13995         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13996         return nullptr;
13997       }
13998     }
13999     EnclosingContext = EnclosingDecl;
14000   }
14001 
14002   // Construct the decl.
14003   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14004                                              DeclStart, Loc, II, T,
14005                                              TInfo, ac, (Expr *)BitfieldWidth);
14006 
14007   if (II) {
14008     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14009                                            ForRedeclaration);
14010     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14011         && !isa<TagDecl>(PrevDecl)) {
14012       Diag(Loc, diag::err_duplicate_member) << II;
14013       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14014       NewID->setInvalidDecl();
14015     }
14016   }
14017 
14018   // Process attributes attached to the ivar.
14019   ProcessDeclAttributes(S, NewID, D);
14020 
14021   if (D.isInvalidType())
14022     NewID->setInvalidDecl();
14023 
14024   // In ARC, infer 'retaining' for ivars of retainable type.
14025   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14026     NewID->setInvalidDecl();
14027 
14028   if (D.getDeclSpec().isModulePrivateSpecified())
14029     NewID->setModulePrivate();
14030 
14031   if (II) {
14032     // FIXME: When interfaces are DeclContexts, we'll need to add
14033     // these to the interface.
14034     S->AddDecl(NewID);
14035     IdResolver.AddDecl(NewID);
14036   }
14037 
14038   if (LangOpts.ObjCRuntime.isNonFragile() &&
14039       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14040     Diag(Loc, diag::warn_ivars_in_interface);
14041 
14042   return NewID;
14043 }
14044 
14045 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14046 /// class and class extensions. For every class \@interface and class
14047 /// extension \@interface, if the last ivar is a bitfield of any type,
14048 /// then add an implicit `char :0` ivar to the end of that interface.
14049 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14050                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14051   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14052     return;
14053 
14054   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14055   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14056 
14057   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14058     return;
14059   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14060   if (!ID) {
14061     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14062       if (!CD->IsClassExtension())
14063         return;
14064     }
14065     // No need to add this to end of @implementation.
14066     else
14067       return;
14068   }
14069   // All conditions are met. Add a new bitfield to the tail end of ivars.
14070   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14071   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14072 
14073   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14074                               DeclLoc, DeclLoc, nullptr,
14075                               Context.CharTy,
14076                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14077                                                                DeclLoc),
14078                               ObjCIvarDecl::Private, BW,
14079                               true);
14080   AllIvarDecls.push_back(Ivar);
14081 }
14082 
14083 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14084                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14085                        SourceLocation RBrac, AttributeList *Attr) {
14086   assert(EnclosingDecl && "missing record or interface decl");
14087 
14088   // If this is an Objective-C @implementation or category and we have
14089   // new fields here we should reset the layout of the interface since
14090   // it will now change.
14091   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14092     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14093     switch (DC->getKind()) {
14094     default: break;
14095     case Decl::ObjCCategory:
14096       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14097       break;
14098     case Decl::ObjCImplementation:
14099       Context.
14100         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14101       break;
14102     }
14103   }
14104 
14105   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14106 
14107   // Start counting up the number of named members; make sure to include
14108   // members of anonymous structs and unions in the total.
14109   unsigned NumNamedMembers = 0;
14110   if (Record) {
14111     for (const auto *I : Record->decls()) {
14112       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14113         if (IFD->getDeclName())
14114           ++NumNamedMembers;
14115     }
14116   }
14117 
14118   // Verify that all the fields are okay.
14119   SmallVector<FieldDecl*, 32> RecFields;
14120 
14121   bool ARCErrReported = false;
14122   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14123        i != end; ++i) {
14124     FieldDecl *FD = cast<FieldDecl>(*i);
14125 
14126     // Get the type for the field.
14127     const Type *FDTy = FD->getType().getTypePtr();
14128 
14129     if (!FD->isAnonymousStructOrUnion()) {
14130       // Remember all fields written by the user.
14131       RecFields.push_back(FD);
14132     }
14133 
14134     // If the field is already invalid for some reason, don't emit more
14135     // diagnostics about it.
14136     if (FD->isInvalidDecl()) {
14137       EnclosingDecl->setInvalidDecl();
14138       continue;
14139     }
14140 
14141     // C99 6.7.2.1p2:
14142     //   A structure or union shall not contain a member with
14143     //   incomplete or function type (hence, a structure shall not
14144     //   contain an instance of itself, but may contain a pointer to
14145     //   an instance of itself), except that the last member of a
14146     //   structure with more than one named member may have incomplete
14147     //   array type; such a structure (and any union containing,
14148     //   possibly recursively, a member that is such a structure)
14149     //   shall not be a member of a structure or an element of an
14150     //   array.
14151     if (FDTy->isFunctionType()) {
14152       // Field declared as a function.
14153       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14154         << FD->getDeclName();
14155       FD->setInvalidDecl();
14156       EnclosingDecl->setInvalidDecl();
14157       continue;
14158     } else if (FDTy->isIncompleteArrayType() && Record &&
14159                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14160                 ((getLangOpts().MicrosoftExt ||
14161                   getLangOpts().CPlusPlus) &&
14162                  (i + 1 == Fields.end() || Record->isUnion())))) {
14163       // Flexible array member.
14164       // Microsoft and g++ is more permissive regarding flexible array.
14165       // It will accept flexible array in union and also
14166       // as the sole element of a struct/class.
14167       unsigned DiagID = 0;
14168       if (Record->isUnion())
14169         DiagID = getLangOpts().MicrosoftExt
14170                      ? diag::ext_flexible_array_union_ms
14171                      : getLangOpts().CPlusPlus
14172                            ? diag::ext_flexible_array_union_gnu
14173                            : diag::err_flexible_array_union;
14174       else if (NumNamedMembers < 1)
14175         DiagID = getLangOpts().MicrosoftExt
14176                      ? diag::ext_flexible_array_empty_aggregate_ms
14177                      : getLangOpts().CPlusPlus
14178                            ? diag::ext_flexible_array_empty_aggregate_gnu
14179                            : diag::err_flexible_array_empty_aggregate;
14180 
14181       if (DiagID)
14182         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14183                                         << Record->getTagKind();
14184       // While the layout of types that contain virtual bases is not specified
14185       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14186       // virtual bases after the derived members.  This would make a flexible
14187       // array member declared at the end of an object not adjacent to the end
14188       // of the type.
14189       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14190         if (RD->getNumVBases() != 0)
14191           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14192             << FD->getDeclName() << Record->getTagKind();
14193       if (!getLangOpts().C99)
14194         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14195           << FD->getDeclName() << Record->getTagKind();
14196 
14197       // If the element type has a non-trivial destructor, we would not
14198       // implicitly destroy the elements, so disallow it for now.
14199       //
14200       // FIXME: GCC allows this. We should probably either implicitly delete
14201       // the destructor of the containing class, or just allow this.
14202       QualType BaseElem = Context.getBaseElementType(FD->getType());
14203       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14204         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14205           << FD->getDeclName() << FD->getType();
14206         FD->setInvalidDecl();
14207         EnclosingDecl->setInvalidDecl();
14208         continue;
14209       }
14210       // Okay, we have a legal flexible array member at the end of the struct.
14211       Record->setHasFlexibleArrayMember(true);
14212     } else if (!FDTy->isDependentType() &&
14213                RequireCompleteType(FD->getLocation(), FD->getType(),
14214                                    diag::err_field_incomplete)) {
14215       // Incomplete type
14216       FD->setInvalidDecl();
14217       EnclosingDecl->setInvalidDecl();
14218       continue;
14219     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14220       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14221         // A type which contains a flexible array member is considered to be a
14222         // flexible array member.
14223         Record->setHasFlexibleArrayMember(true);
14224         if (!Record->isUnion()) {
14225           // If this is a struct/class and this is not the last element, reject
14226           // it.  Note that GCC supports variable sized arrays in the middle of
14227           // structures.
14228           if (i + 1 != Fields.end())
14229             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14230               << FD->getDeclName() << FD->getType();
14231           else {
14232             // We support flexible arrays at the end of structs in
14233             // other structs as an extension.
14234             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14235               << FD->getDeclName();
14236           }
14237         }
14238       }
14239       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14240           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14241                                  diag::err_abstract_type_in_decl,
14242                                  AbstractIvarType)) {
14243         // Ivars can not have abstract class types
14244         FD->setInvalidDecl();
14245       }
14246       if (Record && FDTTy->getDecl()->hasObjectMember())
14247         Record->setHasObjectMember(true);
14248       if (Record && FDTTy->getDecl()->hasVolatileMember())
14249         Record->setHasVolatileMember(true);
14250     } else if (FDTy->isObjCObjectType()) {
14251       /// A field cannot be an Objective-c object
14252       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14253         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14254       QualType T = Context.getObjCObjectPointerType(FD->getType());
14255       FD->setType(T);
14256     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14257                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14258       // It's an error in ARC if a field has lifetime.
14259       // We don't want to report this in a system header, though,
14260       // so we just make the field unavailable.
14261       // FIXME: that's really not sufficient; we need to make the type
14262       // itself invalid to, say, initialize or copy.
14263       QualType T = FD->getType();
14264       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14265       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14266         SourceLocation loc = FD->getLocation();
14267         if (getSourceManager().isInSystemHeader(loc)) {
14268           if (!FD->hasAttr<UnavailableAttr>()) {
14269             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14270                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14271           }
14272         } else {
14273           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14274             << T->isBlockPointerType() << Record->getTagKind();
14275         }
14276         ARCErrReported = true;
14277       }
14278     } else if (getLangOpts().ObjC1 &&
14279                getLangOpts().getGC() != LangOptions::NonGC &&
14280                Record && !Record->hasObjectMember()) {
14281       if (FD->getType()->isObjCObjectPointerType() ||
14282           FD->getType().isObjCGCStrong())
14283         Record->setHasObjectMember(true);
14284       else if (Context.getAsArrayType(FD->getType())) {
14285         QualType BaseType = Context.getBaseElementType(FD->getType());
14286         if (BaseType->isRecordType() &&
14287             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14288           Record->setHasObjectMember(true);
14289         else if (BaseType->isObjCObjectPointerType() ||
14290                  BaseType.isObjCGCStrong())
14291                Record->setHasObjectMember(true);
14292       }
14293     }
14294     if (Record && FD->getType().isVolatileQualified())
14295       Record->setHasVolatileMember(true);
14296     // Keep track of the number of named members.
14297     if (FD->getIdentifier())
14298       ++NumNamedMembers;
14299   }
14300 
14301   // Okay, we successfully defined 'Record'.
14302   if (Record) {
14303     bool Completed = false;
14304     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14305       if (!CXXRecord->isInvalidDecl()) {
14306         // Set access bits correctly on the directly-declared conversions.
14307         for (CXXRecordDecl::conversion_iterator
14308                I = CXXRecord->conversion_begin(),
14309                E = CXXRecord->conversion_end(); I != E; ++I)
14310           I.setAccess((*I)->getAccess());
14311       }
14312 
14313       if (!CXXRecord->isDependentType()) {
14314         if (CXXRecord->hasUserDeclaredDestructor()) {
14315           // Adjust user-defined destructor exception spec.
14316           if (getLangOpts().CPlusPlus11)
14317             AdjustDestructorExceptionSpec(CXXRecord,
14318                                           CXXRecord->getDestructor());
14319         }
14320 
14321         if (!CXXRecord->isInvalidDecl()) {
14322           // Add any implicitly-declared members to this class.
14323           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14324 
14325           // If we have virtual base classes, we may end up finding multiple
14326           // final overriders for a given virtual function. Check for this
14327           // problem now.
14328           if (CXXRecord->getNumVBases()) {
14329             CXXFinalOverriderMap FinalOverriders;
14330             CXXRecord->getFinalOverriders(FinalOverriders);
14331 
14332             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14333                                              MEnd = FinalOverriders.end();
14334                  M != MEnd; ++M) {
14335               for (OverridingMethods::iterator SO = M->second.begin(),
14336                                             SOEnd = M->second.end();
14337                    SO != SOEnd; ++SO) {
14338                 assert(SO->second.size() > 0 &&
14339                        "Virtual function without overridding functions?");
14340                 if (SO->second.size() == 1)
14341                   continue;
14342 
14343                 // C++ [class.virtual]p2:
14344                 //   In a derived class, if a virtual member function of a base
14345                 //   class subobject has more than one final overrider the
14346                 //   program is ill-formed.
14347                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14348                   << (const NamedDecl *)M->first << Record;
14349                 Diag(M->first->getLocation(),
14350                      diag::note_overridden_virtual_function);
14351                 for (OverridingMethods::overriding_iterator
14352                           OM = SO->second.begin(),
14353                        OMEnd = SO->second.end();
14354                      OM != OMEnd; ++OM)
14355                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14356                     << (const NamedDecl *)M->first << OM->Method->getParent();
14357 
14358                 Record->setInvalidDecl();
14359               }
14360             }
14361             CXXRecord->completeDefinition(&FinalOverriders);
14362             Completed = true;
14363           }
14364         }
14365       }
14366     }
14367 
14368     if (!Completed)
14369       Record->completeDefinition();
14370 
14371     // We may have deferred checking for a deleted destructor. Check now.
14372     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14373       auto *Dtor = CXXRecord->getDestructor();
14374       if (Dtor && Dtor->isImplicit() &&
14375           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14376         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14377     }
14378 
14379     if (Record->hasAttrs()) {
14380       CheckAlignasUnderalignment(Record);
14381 
14382       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14383         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14384                                            IA->getRange(), IA->getBestCase(),
14385                                            IA->getSemanticSpelling());
14386     }
14387 
14388     // Check if the structure/union declaration is a type that can have zero
14389     // size in C. For C this is a language extension, for C++ it may cause
14390     // compatibility problems.
14391     bool CheckForZeroSize;
14392     if (!getLangOpts().CPlusPlus) {
14393       CheckForZeroSize = true;
14394     } else {
14395       // For C++ filter out types that cannot be referenced in C code.
14396       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14397       CheckForZeroSize =
14398           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14399           !CXXRecord->isDependentType() &&
14400           CXXRecord->isCLike();
14401     }
14402     if (CheckForZeroSize) {
14403       bool ZeroSize = true;
14404       bool IsEmpty = true;
14405       unsigned NonBitFields = 0;
14406       for (RecordDecl::field_iterator I = Record->field_begin(),
14407                                       E = Record->field_end();
14408            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14409         IsEmpty = false;
14410         if (I->isUnnamedBitfield()) {
14411           if (I->getBitWidthValue(Context) > 0)
14412             ZeroSize = false;
14413         } else {
14414           ++NonBitFields;
14415           QualType FieldType = I->getType();
14416           if (FieldType->isIncompleteType() ||
14417               !Context.getTypeSizeInChars(FieldType).isZero())
14418             ZeroSize = false;
14419         }
14420       }
14421 
14422       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14423       // allowed in C++, but warn if its declaration is inside
14424       // extern "C" block.
14425       if (ZeroSize) {
14426         Diag(RecLoc, getLangOpts().CPlusPlus ?
14427                          diag::warn_zero_size_struct_union_in_extern_c :
14428                          diag::warn_zero_size_struct_union_compat)
14429           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14430       }
14431 
14432       // Structs without named members are extension in C (C99 6.7.2.1p7),
14433       // but are accepted by GCC.
14434       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14435         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14436                                diag::ext_no_named_members_in_struct_union)
14437           << Record->isUnion();
14438       }
14439     }
14440   } else {
14441     ObjCIvarDecl **ClsFields =
14442       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14443     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14444       ID->setEndOfDefinitionLoc(RBrac);
14445       // Add ivar's to class's DeclContext.
14446       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14447         ClsFields[i]->setLexicalDeclContext(ID);
14448         ID->addDecl(ClsFields[i]);
14449       }
14450       // Must enforce the rule that ivars in the base classes may not be
14451       // duplicates.
14452       if (ID->getSuperClass())
14453         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14454     } else if (ObjCImplementationDecl *IMPDecl =
14455                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14456       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14457       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14458         // Ivar declared in @implementation never belongs to the implementation.
14459         // Only it is in implementation's lexical context.
14460         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14461       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14462       IMPDecl->setIvarLBraceLoc(LBrac);
14463       IMPDecl->setIvarRBraceLoc(RBrac);
14464     } else if (ObjCCategoryDecl *CDecl =
14465                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14466       // case of ivars in class extension; all other cases have been
14467       // reported as errors elsewhere.
14468       // FIXME. Class extension does not have a LocEnd field.
14469       // CDecl->setLocEnd(RBrac);
14470       // Add ivar's to class extension's DeclContext.
14471       // Diagnose redeclaration of private ivars.
14472       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14473       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14474         if (IDecl) {
14475           if (const ObjCIvarDecl *ClsIvar =
14476               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14477             Diag(ClsFields[i]->getLocation(),
14478                  diag::err_duplicate_ivar_declaration);
14479             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14480             continue;
14481           }
14482           for (const auto *Ext : IDecl->known_extensions()) {
14483             if (const ObjCIvarDecl *ClsExtIvar
14484                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14485               Diag(ClsFields[i]->getLocation(),
14486                    diag::err_duplicate_ivar_declaration);
14487               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14488               continue;
14489             }
14490           }
14491         }
14492         ClsFields[i]->setLexicalDeclContext(CDecl);
14493         CDecl->addDecl(ClsFields[i]);
14494       }
14495       CDecl->setIvarLBraceLoc(LBrac);
14496       CDecl->setIvarRBraceLoc(RBrac);
14497     }
14498   }
14499 
14500   if (Attr)
14501     ProcessDeclAttributeList(S, Record, Attr);
14502 }
14503 
14504 /// \brief Determine whether the given integral value is representable within
14505 /// the given type T.
14506 static bool isRepresentableIntegerValue(ASTContext &Context,
14507                                         llvm::APSInt &Value,
14508                                         QualType T) {
14509   assert(T->isIntegralType(Context) && "Integral type required!");
14510   unsigned BitWidth = Context.getIntWidth(T);
14511 
14512   if (Value.isUnsigned() || Value.isNonNegative()) {
14513     if (T->isSignedIntegerOrEnumerationType())
14514       --BitWidth;
14515     return Value.getActiveBits() <= BitWidth;
14516   }
14517   return Value.getMinSignedBits() <= BitWidth;
14518 }
14519 
14520 // \brief Given an integral type, return the next larger integral type
14521 // (or a NULL type of no such type exists).
14522 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14523   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14524   // enum checking below.
14525   assert(T->isIntegralType(Context) && "Integral type required!");
14526   const unsigned NumTypes = 4;
14527   QualType SignedIntegralTypes[NumTypes] = {
14528     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14529   };
14530   QualType UnsignedIntegralTypes[NumTypes] = {
14531     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14532     Context.UnsignedLongLongTy
14533   };
14534 
14535   unsigned BitWidth = Context.getTypeSize(T);
14536   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14537                                                         : UnsignedIntegralTypes;
14538   for (unsigned I = 0; I != NumTypes; ++I)
14539     if (Context.getTypeSize(Types[I]) > BitWidth)
14540       return Types[I];
14541 
14542   return QualType();
14543 }
14544 
14545 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14546                                           EnumConstantDecl *LastEnumConst,
14547                                           SourceLocation IdLoc,
14548                                           IdentifierInfo *Id,
14549                                           Expr *Val) {
14550   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14551   llvm::APSInt EnumVal(IntWidth);
14552   QualType EltTy;
14553 
14554   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14555     Val = nullptr;
14556 
14557   if (Val)
14558     Val = DefaultLvalueConversion(Val).get();
14559 
14560   if (Val) {
14561     if (Enum->isDependentType() || Val->isTypeDependent())
14562       EltTy = Context.DependentTy;
14563     else {
14564       SourceLocation ExpLoc;
14565       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14566           !getLangOpts().MSVCCompat) {
14567         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14568         // constant-expression in the enumerator-definition shall be a converted
14569         // constant expression of the underlying type.
14570         EltTy = Enum->getIntegerType();
14571         ExprResult Converted =
14572           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14573                                            CCEK_Enumerator);
14574         if (Converted.isInvalid())
14575           Val = nullptr;
14576         else
14577           Val = Converted.get();
14578       } else if (!Val->isValueDependent() &&
14579                  !(Val = VerifyIntegerConstantExpression(Val,
14580                                                          &EnumVal).get())) {
14581         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14582       } else {
14583         if (Enum->isFixed()) {
14584           EltTy = Enum->getIntegerType();
14585 
14586           // In Obj-C and Microsoft mode, require the enumeration value to be
14587           // representable in the underlying type of the enumeration. In C++11,
14588           // we perform a non-narrowing conversion as part of converted constant
14589           // expression checking.
14590           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14591             if (getLangOpts().MSVCCompat) {
14592               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14593               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14594             } else
14595               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14596           } else
14597             Val = ImpCastExprToType(Val, EltTy,
14598                                     EltTy->isBooleanType() ?
14599                                     CK_IntegralToBoolean : CK_IntegralCast)
14600                     .get();
14601         } else if (getLangOpts().CPlusPlus) {
14602           // C++11 [dcl.enum]p5:
14603           //   If the underlying type is not fixed, the type of each enumerator
14604           //   is the type of its initializing value:
14605           //     - If an initializer is specified for an enumerator, the
14606           //       initializing value has the same type as the expression.
14607           EltTy = Val->getType();
14608         } else {
14609           // C99 6.7.2.2p2:
14610           //   The expression that defines the value of an enumeration constant
14611           //   shall be an integer constant expression that has a value
14612           //   representable as an int.
14613 
14614           // Complain if the value is not representable in an int.
14615           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14616             Diag(IdLoc, diag::ext_enum_value_not_int)
14617               << EnumVal.toString(10) << Val->getSourceRange()
14618               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14619           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14620             // Force the type of the expression to 'int'.
14621             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14622           }
14623           EltTy = Val->getType();
14624         }
14625       }
14626     }
14627   }
14628 
14629   if (!Val) {
14630     if (Enum->isDependentType())
14631       EltTy = Context.DependentTy;
14632     else if (!LastEnumConst) {
14633       // C++0x [dcl.enum]p5:
14634       //   If the underlying type is not fixed, the type of each enumerator
14635       //   is the type of its initializing value:
14636       //     - If no initializer is specified for the first enumerator, the
14637       //       initializing value has an unspecified integral type.
14638       //
14639       // GCC uses 'int' for its unspecified integral type, as does
14640       // C99 6.7.2.2p3.
14641       if (Enum->isFixed()) {
14642         EltTy = Enum->getIntegerType();
14643       }
14644       else {
14645         EltTy = Context.IntTy;
14646       }
14647     } else {
14648       // Assign the last value + 1.
14649       EnumVal = LastEnumConst->getInitVal();
14650       ++EnumVal;
14651       EltTy = LastEnumConst->getType();
14652 
14653       // Check for overflow on increment.
14654       if (EnumVal < LastEnumConst->getInitVal()) {
14655         // C++0x [dcl.enum]p5:
14656         //   If the underlying type is not fixed, the type of each enumerator
14657         //   is the type of its initializing value:
14658         //
14659         //     - Otherwise the type of the initializing value is the same as
14660         //       the type of the initializing value of the preceding enumerator
14661         //       unless the incremented value is not representable in that type,
14662         //       in which case the type is an unspecified integral type
14663         //       sufficient to contain the incremented value. If no such type
14664         //       exists, the program is ill-formed.
14665         QualType T = getNextLargerIntegralType(Context, EltTy);
14666         if (T.isNull() || Enum->isFixed()) {
14667           // There is no integral type larger enough to represent this
14668           // value. Complain, then allow the value to wrap around.
14669           EnumVal = LastEnumConst->getInitVal();
14670           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14671           ++EnumVal;
14672           if (Enum->isFixed())
14673             // When the underlying type is fixed, this is ill-formed.
14674             Diag(IdLoc, diag::err_enumerator_wrapped)
14675               << EnumVal.toString(10)
14676               << EltTy;
14677           else
14678             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14679               << EnumVal.toString(10);
14680         } else {
14681           EltTy = T;
14682         }
14683 
14684         // Retrieve the last enumerator's value, extent that type to the
14685         // type that is supposed to be large enough to represent the incremented
14686         // value, then increment.
14687         EnumVal = LastEnumConst->getInitVal();
14688         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14689         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14690         ++EnumVal;
14691 
14692         // If we're not in C++, diagnose the overflow of enumerator values,
14693         // which in C99 means that the enumerator value is not representable in
14694         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14695         // permits enumerator values that are representable in some larger
14696         // integral type.
14697         if (!getLangOpts().CPlusPlus && !T.isNull())
14698           Diag(IdLoc, diag::warn_enum_value_overflow);
14699       } else if (!getLangOpts().CPlusPlus &&
14700                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14701         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14702         Diag(IdLoc, diag::ext_enum_value_not_int)
14703           << EnumVal.toString(10) << 1;
14704       }
14705     }
14706   }
14707 
14708   if (!EltTy->isDependentType()) {
14709     // Make the enumerator value match the signedness and size of the
14710     // enumerator's type.
14711     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14712     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14713   }
14714 
14715   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14716                                   Val, EnumVal);
14717 }
14718 
14719 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14720                                                 SourceLocation IILoc) {
14721   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14722       !getLangOpts().CPlusPlus)
14723     return SkipBodyInfo();
14724 
14725   // We have an anonymous enum definition. Look up the first enumerator to
14726   // determine if we should merge the definition with an existing one and
14727   // skip the body.
14728   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14729                                          ForRedeclaration);
14730   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14731   if (!PrevECD)
14732     return SkipBodyInfo();
14733 
14734   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14735   NamedDecl *Hidden;
14736   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14737     SkipBodyInfo Skip;
14738     Skip.Previous = Hidden;
14739     return Skip;
14740   }
14741 
14742   return SkipBodyInfo();
14743 }
14744 
14745 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14746                               SourceLocation IdLoc, IdentifierInfo *Id,
14747                               AttributeList *Attr,
14748                               SourceLocation EqualLoc, Expr *Val) {
14749   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14750   EnumConstantDecl *LastEnumConst =
14751     cast_or_null<EnumConstantDecl>(lastEnumConst);
14752 
14753   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14754   // we find one that is.
14755   S = getNonFieldDeclScope(S);
14756 
14757   // Verify that there isn't already something declared with this name in this
14758   // scope.
14759   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14760                                          ForRedeclaration);
14761   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14762     // Maybe we will complain about the shadowed template parameter.
14763     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14764     // Just pretend that we didn't see the previous declaration.
14765     PrevDecl = nullptr;
14766   }
14767 
14768   // C++ [class.mem]p15:
14769   // If T is the name of a class, then each of the following shall have a name
14770   // different from T:
14771   // - every enumerator of every member of class T that is an unscoped
14772   // enumerated type
14773   if (!TheEnumDecl->isScoped())
14774     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14775                             DeclarationNameInfo(Id, IdLoc));
14776 
14777   EnumConstantDecl *New =
14778     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14779   if (!New)
14780     return nullptr;
14781 
14782   if (PrevDecl) {
14783     // When in C++, we may get a TagDecl with the same name; in this case the
14784     // enum constant will 'hide' the tag.
14785     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14786            "Received TagDecl when not in C++!");
14787     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14788         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14789       if (isa<EnumConstantDecl>(PrevDecl))
14790         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14791       else
14792         Diag(IdLoc, diag::err_redefinition) << Id;
14793       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14794       return nullptr;
14795     }
14796   }
14797 
14798   // Process attributes.
14799   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14800 
14801   // Register this decl in the current scope stack.
14802   New->setAccess(TheEnumDecl->getAccess());
14803   PushOnScopeChains(New, S);
14804 
14805   ActOnDocumentableDecl(New);
14806 
14807   return New;
14808 }
14809 
14810 // Returns true when the enum initial expression does not trigger the
14811 // duplicate enum warning.  A few common cases are exempted as follows:
14812 // Element2 = Element1
14813 // Element2 = Element1 + 1
14814 // Element2 = Element1 - 1
14815 // Where Element2 and Element1 are from the same enum.
14816 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14817   Expr *InitExpr = ECD->getInitExpr();
14818   if (!InitExpr)
14819     return true;
14820   InitExpr = InitExpr->IgnoreImpCasts();
14821 
14822   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14823     if (!BO->isAdditiveOp())
14824       return true;
14825     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14826     if (!IL)
14827       return true;
14828     if (IL->getValue() != 1)
14829       return true;
14830 
14831     InitExpr = BO->getLHS();
14832   }
14833 
14834   // This checks if the elements are from the same enum.
14835   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14836   if (!DRE)
14837     return true;
14838 
14839   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14840   if (!EnumConstant)
14841     return true;
14842 
14843   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14844       Enum)
14845     return true;
14846 
14847   return false;
14848 }
14849 
14850 namespace {
14851 struct DupKey {
14852   int64_t val;
14853   bool isTombstoneOrEmptyKey;
14854   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14855     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14856 };
14857 
14858 static DupKey GetDupKey(const llvm::APSInt& Val) {
14859   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14860                 false);
14861 }
14862 
14863 struct DenseMapInfoDupKey {
14864   static DupKey getEmptyKey() { return DupKey(0, true); }
14865   static DupKey getTombstoneKey() { return DupKey(1, true); }
14866   static unsigned getHashValue(const DupKey Key) {
14867     return (unsigned)(Key.val * 37);
14868   }
14869   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14870     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14871            LHS.val == RHS.val;
14872   }
14873 };
14874 } // end anonymous namespace
14875 
14876 // Emits a warning when an element is implicitly set a value that
14877 // a previous element has already been set to.
14878 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14879                                         EnumDecl *Enum,
14880                                         QualType EnumType) {
14881   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14882     return;
14883   // Avoid anonymous enums
14884   if (!Enum->getIdentifier())
14885     return;
14886 
14887   // Only check for small enums.
14888   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14889     return;
14890 
14891   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14892   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14893 
14894   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14895   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14896           ValueToVectorMap;
14897 
14898   DuplicatesVector DupVector;
14899   ValueToVectorMap EnumMap;
14900 
14901   // Populate the EnumMap with all values represented by enum constants without
14902   // an initialier.
14903   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14904     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14905 
14906     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14907     // this constant.  Skip this enum since it may be ill-formed.
14908     if (!ECD) {
14909       return;
14910     }
14911 
14912     if (ECD->getInitExpr())
14913       continue;
14914 
14915     DupKey Key = GetDupKey(ECD->getInitVal());
14916     DeclOrVector &Entry = EnumMap[Key];
14917 
14918     // First time encountering this value.
14919     if (Entry.isNull())
14920       Entry = ECD;
14921   }
14922 
14923   // Create vectors for any values that has duplicates.
14924   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14925     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14926     if (!ValidDuplicateEnum(ECD, Enum))
14927       continue;
14928 
14929     DupKey Key = GetDupKey(ECD->getInitVal());
14930 
14931     DeclOrVector& Entry = EnumMap[Key];
14932     if (Entry.isNull())
14933       continue;
14934 
14935     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14936       // Ensure constants are different.
14937       if (D == ECD)
14938         continue;
14939 
14940       // Create new vector and push values onto it.
14941       ECDVector *Vec = new ECDVector();
14942       Vec->push_back(D);
14943       Vec->push_back(ECD);
14944 
14945       // Update entry to point to the duplicates vector.
14946       Entry = Vec;
14947 
14948       // Store the vector somewhere we can consult later for quick emission of
14949       // diagnostics.
14950       DupVector.push_back(Vec);
14951       continue;
14952     }
14953 
14954     ECDVector *Vec = Entry.get<ECDVector*>();
14955     // Make sure constants are not added more than once.
14956     if (*Vec->begin() == ECD)
14957       continue;
14958 
14959     Vec->push_back(ECD);
14960   }
14961 
14962   // Emit diagnostics.
14963   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14964                                   DupVectorEnd = DupVector.end();
14965        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14966     ECDVector *Vec = *DupVectorIter;
14967     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14968 
14969     // Emit warning for one enum constant.
14970     ECDVector::iterator I = Vec->begin();
14971     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14972       << (*I)->getName() << (*I)->getInitVal().toString(10)
14973       << (*I)->getSourceRange();
14974     ++I;
14975 
14976     // Emit one note for each of the remaining enum constants with
14977     // the same value.
14978     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14979       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14980         << (*I)->getName() << (*I)->getInitVal().toString(10)
14981         << (*I)->getSourceRange();
14982     delete Vec;
14983   }
14984 }
14985 
14986 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14987                              bool AllowMask) const {
14988   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14989   assert(ED->isCompleteDefinition() && "expected enum definition");
14990 
14991   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14992   llvm::APInt &FlagBits = R.first->second;
14993 
14994   if (R.second) {
14995     for (auto *E : ED->enumerators()) {
14996       const auto &EVal = E->getInitVal();
14997       // Only single-bit enumerators introduce new flag values.
14998       if (EVal.isPowerOf2())
14999         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15000     }
15001   }
15002 
15003   // A value is in a flag enum if either its bits are a subset of the enum's
15004   // flag bits (the first condition) or we are allowing masks and the same is
15005   // true of its complement (the second condition). When masks are allowed, we
15006   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15007   //
15008   // While it's true that any value could be used as a mask, the assumption is
15009   // that a mask will have all of the insignificant bits set. Anything else is
15010   // likely a logic error.
15011   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15012   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15013 }
15014 
15015 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15016                          Decl *EnumDeclX,
15017                          ArrayRef<Decl *> Elements,
15018                          Scope *S, AttributeList *Attr) {
15019   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15020   QualType EnumType = Context.getTypeDeclType(Enum);
15021 
15022   if (Attr)
15023     ProcessDeclAttributeList(S, Enum, Attr);
15024 
15025   if (Enum->isDependentType()) {
15026     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15027       EnumConstantDecl *ECD =
15028         cast_or_null<EnumConstantDecl>(Elements[i]);
15029       if (!ECD) continue;
15030 
15031       ECD->setType(EnumType);
15032     }
15033 
15034     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15035     return;
15036   }
15037 
15038   // TODO: If the result value doesn't fit in an int, it must be a long or long
15039   // long value.  ISO C does not support this, but GCC does as an extension,
15040   // emit a warning.
15041   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15042   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15043   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15044 
15045   // Verify that all the values are okay, compute the size of the values, and
15046   // reverse the list.
15047   unsigned NumNegativeBits = 0;
15048   unsigned NumPositiveBits = 0;
15049 
15050   // Keep track of whether all elements have type int.
15051   bool AllElementsInt = true;
15052 
15053   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15054     EnumConstantDecl *ECD =
15055       cast_or_null<EnumConstantDecl>(Elements[i]);
15056     if (!ECD) continue;  // Already issued a diagnostic.
15057 
15058     const llvm::APSInt &InitVal = ECD->getInitVal();
15059 
15060     // Keep track of the size of positive and negative values.
15061     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15062       NumPositiveBits = std::max(NumPositiveBits,
15063                                  (unsigned)InitVal.getActiveBits());
15064     else
15065       NumNegativeBits = std::max(NumNegativeBits,
15066                                  (unsigned)InitVal.getMinSignedBits());
15067 
15068     // Keep track of whether every enum element has type int (very commmon).
15069     if (AllElementsInt)
15070       AllElementsInt = ECD->getType() == Context.IntTy;
15071   }
15072 
15073   // Figure out the type that should be used for this enum.
15074   QualType BestType;
15075   unsigned BestWidth;
15076 
15077   // C++0x N3000 [conv.prom]p3:
15078   //   An rvalue of an unscoped enumeration type whose underlying
15079   //   type is not fixed can be converted to an rvalue of the first
15080   //   of the following types that can represent all the values of
15081   //   the enumeration: int, unsigned int, long int, unsigned long
15082   //   int, long long int, or unsigned long long int.
15083   // C99 6.4.4.3p2:
15084   //   An identifier declared as an enumeration constant has type int.
15085   // The C99 rule is modified by a gcc extension
15086   QualType BestPromotionType;
15087 
15088   bool Packed = Enum->hasAttr<PackedAttr>();
15089   // -fshort-enums is the equivalent to specifying the packed attribute on all
15090   // enum definitions.
15091   if (LangOpts.ShortEnums)
15092     Packed = true;
15093 
15094   if (Enum->isFixed()) {
15095     BestType = Enum->getIntegerType();
15096     if (BestType->isPromotableIntegerType())
15097       BestPromotionType = Context.getPromotedIntegerType(BestType);
15098     else
15099       BestPromotionType = BestType;
15100 
15101     BestWidth = Context.getIntWidth(BestType);
15102   }
15103   else if (NumNegativeBits) {
15104     // If there is a negative value, figure out the smallest integer type (of
15105     // int/long/longlong) that fits.
15106     // If it's packed, check also if it fits a char or a short.
15107     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15108       BestType = Context.SignedCharTy;
15109       BestWidth = CharWidth;
15110     } else if (Packed && NumNegativeBits <= ShortWidth &&
15111                NumPositiveBits < ShortWidth) {
15112       BestType = Context.ShortTy;
15113       BestWidth = ShortWidth;
15114     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15115       BestType = Context.IntTy;
15116       BestWidth = IntWidth;
15117     } else {
15118       BestWidth = Context.getTargetInfo().getLongWidth();
15119 
15120       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15121         BestType = Context.LongTy;
15122       } else {
15123         BestWidth = Context.getTargetInfo().getLongLongWidth();
15124 
15125         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15126           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15127         BestType = Context.LongLongTy;
15128       }
15129     }
15130     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15131   } else {
15132     // If there is no negative value, figure out the smallest type that fits
15133     // all of the enumerator values.
15134     // If it's packed, check also if it fits a char or a short.
15135     if (Packed && NumPositiveBits <= CharWidth) {
15136       BestType = Context.UnsignedCharTy;
15137       BestPromotionType = Context.IntTy;
15138       BestWidth = CharWidth;
15139     } else if (Packed && NumPositiveBits <= ShortWidth) {
15140       BestType = Context.UnsignedShortTy;
15141       BestPromotionType = Context.IntTy;
15142       BestWidth = ShortWidth;
15143     } else if (NumPositiveBits <= IntWidth) {
15144       BestType = Context.UnsignedIntTy;
15145       BestWidth = IntWidth;
15146       BestPromotionType
15147         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15148                            ? Context.UnsignedIntTy : Context.IntTy;
15149     } else if (NumPositiveBits <=
15150                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15151       BestType = Context.UnsignedLongTy;
15152       BestPromotionType
15153         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15154                            ? Context.UnsignedLongTy : Context.LongTy;
15155     } else {
15156       BestWidth = Context.getTargetInfo().getLongLongWidth();
15157       assert(NumPositiveBits <= BestWidth &&
15158              "How could an initializer get larger than ULL?");
15159       BestType = Context.UnsignedLongLongTy;
15160       BestPromotionType
15161         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15162                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15163     }
15164   }
15165 
15166   // Loop over all of the enumerator constants, changing their types to match
15167   // the type of the enum if needed.
15168   for (auto *D : Elements) {
15169     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15170     if (!ECD) continue;  // Already issued a diagnostic.
15171 
15172     // Standard C says the enumerators have int type, but we allow, as an
15173     // extension, the enumerators to be larger than int size.  If each
15174     // enumerator value fits in an int, type it as an int, otherwise type it the
15175     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15176     // that X has type 'int', not 'unsigned'.
15177 
15178     // Determine whether the value fits into an int.
15179     llvm::APSInt InitVal = ECD->getInitVal();
15180 
15181     // If it fits into an integer type, force it.  Otherwise force it to match
15182     // the enum decl type.
15183     QualType NewTy;
15184     unsigned NewWidth;
15185     bool NewSign;
15186     if (!getLangOpts().CPlusPlus &&
15187         !Enum->isFixed() &&
15188         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15189       NewTy = Context.IntTy;
15190       NewWidth = IntWidth;
15191       NewSign = true;
15192     } else if (ECD->getType() == BestType) {
15193       // Already the right type!
15194       if (getLangOpts().CPlusPlus)
15195         // C++ [dcl.enum]p4: Following the closing brace of an
15196         // enum-specifier, each enumerator has the type of its
15197         // enumeration.
15198         ECD->setType(EnumType);
15199       continue;
15200     } else {
15201       NewTy = BestType;
15202       NewWidth = BestWidth;
15203       NewSign = BestType->isSignedIntegerOrEnumerationType();
15204     }
15205 
15206     // Adjust the APSInt value.
15207     InitVal = InitVal.extOrTrunc(NewWidth);
15208     InitVal.setIsSigned(NewSign);
15209     ECD->setInitVal(InitVal);
15210 
15211     // Adjust the Expr initializer and type.
15212     if (ECD->getInitExpr() &&
15213         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15214       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15215                                                 CK_IntegralCast,
15216                                                 ECD->getInitExpr(),
15217                                                 /*base paths*/ nullptr,
15218                                                 VK_RValue));
15219     if (getLangOpts().CPlusPlus)
15220       // C++ [dcl.enum]p4: Following the closing brace of an
15221       // enum-specifier, each enumerator has the type of its
15222       // enumeration.
15223       ECD->setType(EnumType);
15224     else
15225       ECD->setType(NewTy);
15226   }
15227 
15228   Enum->completeDefinition(BestType, BestPromotionType,
15229                            NumPositiveBits, NumNegativeBits);
15230 
15231   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15232 
15233   if (Enum->hasAttr<FlagEnumAttr>()) {
15234     for (Decl *D : Elements) {
15235       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15236       if (!ECD) continue;  // Already issued a diagnostic.
15237 
15238       llvm::APSInt InitVal = ECD->getInitVal();
15239       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15240           !IsValueInFlagEnum(Enum, InitVal, true))
15241         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15242           << ECD << Enum;
15243     }
15244   }
15245 
15246   // Now that the enum type is defined, ensure it's not been underaligned.
15247   if (Enum->hasAttrs())
15248     CheckAlignasUnderalignment(Enum);
15249 }
15250 
15251 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15252                                   SourceLocation StartLoc,
15253                                   SourceLocation EndLoc) {
15254   StringLiteral *AsmString = cast<StringLiteral>(expr);
15255 
15256   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15257                                                    AsmString, StartLoc,
15258                                                    EndLoc);
15259   CurContext->addDecl(New);
15260   return New;
15261 }
15262 
15263 static void checkModuleImportContext(Sema &S, Module *M,
15264                                      SourceLocation ImportLoc, DeclContext *DC,
15265                                      bool FromInclude = false) {
15266   SourceLocation ExternCLoc;
15267 
15268   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15269     switch (LSD->getLanguage()) {
15270     case LinkageSpecDecl::lang_c:
15271       if (ExternCLoc.isInvalid())
15272         ExternCLoc = LSD->getLocStart();
15273       break;
15274     case LinkageSpecDecl::lang_cxx:
15275       break;
15276     }
15277     DC = LSD->getParent();
15278   }
15279 
15280   while (isa<LinkageSpecDecl>(DC))
15281     DC = DC->getParent();
15282 
15283   if (!isa<TranslationUnitDecl>(DC)) {
15284     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15285                           ? diag::ext_module_import_not_at_top_level_noop
15286                           : diag::err_module_import_not_at_top_level_fatal)
15287         << M->getFullModuleName() << DC;
15288     S.Diag(cast<Decl>(DC)->getLocStart(),
15289            diag::note_module_import_not_at_top_level) << DC;
15290   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15291     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15292       << M->getFullModuleName();
15293     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15294   }
15295 }
15296 
15297 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15298   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15299 }
15300 
15301 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15302                                            ModuleDeclKind MDK,
15303                                            ModuleIdPath Path) {
15304   // 'module implementation' requires that we are not compiling a module of any
15305   // kind. 'module' and 'module partition' require that we are compiling a
15306   // module inteface (not a module map).
15307   auto CMK = getLangOpts().getCompilingModule();
15308   if (MDK == ModuleDeclKind::Implementation
15309           ? CMK != LangOptions::CMK_None
15310           : CMK != LangOptions::CMK_ModuleInterface) {
15311     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15312       << (unsigned)MDK;
15313     return nullptr;
15314   }
15315 
15316   // FIXME: Create a ModuleDecl and return it.
15317 
15318   // FIXME: Most of this work should be done by the preprocessor rather than
15319   // here, in case we look ahead across something where the current
15320   // module matters (eg a #include).
15321 
15322   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15323   // hierarchical module map modules, the dots here are just another character
15324   // that can appear in a module name. Flatten down to the actual module name.
15325   std::string ModuleName;
15326   for (auto &Piece : Path) {
15327     if (!ModuleName.empty())
15328       ModuleName += ".";
15329     ModuleName += Piece.first->getName();
15330   }
15331 
15332   // If a module name was explicitly specified on the command line, it must be
15333   // correct.
15334   if (!getLangOpts().CurrentModule.empty() &&
15335       getLangOpts().CurrentModule != ModuleName) {
15336     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15337         << SourceRange(Path.front().second, Path.back().second)
15338         << getLangOpts().CurrentModule;
15339     return nullptr;
15340   }
15341   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15342 
15343   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15344 
15345   switch (MDK) {
15346   case ModuleDeclKind::Module: {
15347     // FIXME: Check we're not in a submodule.
15348 
15349     // We can't have imported a definition of this module or parsed a module
15350     // map defining it already.
15351     if (auto *M = Map.findModule(ModuleName)) {
15352       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15353       if (M->DefinitionLoc.isValid())
15354         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15355       else if (const auto *FE = M->getASTFile())
15356         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15357             << FE->getName();
15358       return nullptr;
15359     }
15360 
15361     // Create a Module for the module that we're defining.
15362     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15363     assert(Mod && "module creation should not fail");
15364 
15365     // Enter the semantic scope of the module.
15366     ActOnModuleBegin(ModuleLoc, Mod);
15367     return nullptr;
15368   }
15369 
15370   case ModuleDeclKind::Partition:
15371     // FIXME: Check we are in a submodule of the named module.
15372     return nullptr;
15373 
15374   case ModuleDeclKind::Implementation:
15375     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15376         PP.getIdentifierInfo(ModuleName), Path[0].second);
15377 
15378     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15379     if (Import.isInvalid())
15380       return nullptr;
15381     return ConvertDeclToDeclGroup(Import.get());
15382   }
15383 
15384   llvm_unreachable("unexpected module decl kind");
15385 }
15386 
15387 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15388                                    SourceLocation ImportLoc,
15389                                    ModuleIdPath Path) {
15390   Module *Mod =
15391       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15392                                    /*IsIncludeDirective=*/false);
15393   if (!Mod)
15394     return true;
15395 
15396   VisibleModules.setVisible(Mod, ImportLoc);
15397 
15398   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15399 
15400   // FIXME: we should support importing a submodule within a different submodule
15401   // of the same top-level module. Until we do, make it an error rather than
15402   // silently ignoring the import.
15403   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15404   // warn on a redundant import of the current module?
15405   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15406       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15407     Diag(ImportLoc, getLangOpts().isCompilingModule()
15408                         ? diag::err_module_self_import
15409                         : diag::err_module_import_in_implementation)
15410         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15411 
15412   SmallVector<SourceLocation, 2> IdentifierLocs;
15413   Module *ModCheck = Mod;
15414   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15415     // If we've run out of module parents, just drop the remaining identifiers.
15416     // We need the length to be consistent.
15417     if (!ModCheck)
15418       break;
15419     ModCheck = ModCheck->Parent;
15420 
15421     IdentifierLocs.push_back(Path[I].second);
15422   }
15423 
15424   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15425   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15426                                           Mod, IdentifierLocs);
15427   if (!ModuleScopes.empty())
15428     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15429   TU->addDecl(Import);
15430   return Import;
15431 }
15432 
15433 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15434   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15435   BuildModuleInclude(DirectiveLoc, Mod);
15436 }
15437 
15438 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15439   // Determine whether we're in the #include buffer for a module. The #includes
15440   // in that buffer do not qualify as module imports; they're just an
15441   // implementation detail of us building the module.
15442   //
15443   // FIXME: Should we even get ActOnModuleInclude calls for those?
15444   bool IsInModuleIncludes =
15445       TUKind == TU_Module &&
15446       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15447 
15448   bool ShouldAddImport = !IsInModuleIncludes;
15449 
15450   // If this module import was due to an inclusion directive, create an
15451   // implicit import declaration to capture it in the AST.
15452   if (ShouldAddImport) {
15453     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15454     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15455                                                      DirectiveLoc, Mod,
15456                                                      DirectiveLoc);
15457     if (!ModuleScopes.empty())
15458       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15459     TU->addDecl(ImportD);
15460     Consumer.HandleImplicitImportDecl(ImportD);
15461   }
15462 
15463   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15464   VisibleModules.setVisible(Mod, DirectiveLoc);
15465 }
15466 
15467 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15468   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15469 
15470   ModuleScopes.push_back({});
15471   ModuleScopes.back().Module = Mod;
15472   if (getLangOpts().ModulesLocalVisibility)
15473     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15474 
15475   VisibleModules.setVisible(Mod, DirectiveLoc);
15476 }
15477 
15478 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15479   checkModuleImportContext(*this, Mod, EofLoc, CurContext);
15480 
15481   if (getLangOpts().ModulesLocalVisibility) {
15482     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15483     // Leaving a module hides namespace names, so our visible namespace cache
15484     // is now out of date.
15485     VisibleNamespaceCache.clear();
15486   }
15487 
15488   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15489          "left the wrong module scope");
15490   ModuleScopes.pop_back();
15491 
15492   // We got to the end of processing a #include of a local module. Create an
15493   // ImportDecl as we would for an imported module.
15494   FileID File = getSourceManager().getFileID(EofLoc);
15495   assert(File != getSourceManager().getMainFileID() &&
15496          "end of submodule in main source file");
15497   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15498   BuildModuleInclude(DirectiveLoc, Mod);
15499 }
15500 
15501 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15502                                                       Module *Mod) {
15503   // Bail if we're not allowed to implicitly import a module here.
15504   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15505     return;
15506 
15507   // Create the implicit import declaration.
15508   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15509   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15510                                                    Loc, Mod, Loc);
15511   TU->addDecl(ImportD);
15512   Consumer.HandleImplicitImportDecl(ImportD);
15513 
15514   // Make the module visible.
15515   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15516   VisibleModules.setVisible(Mod, Loc);
15517 }
15518 
15519 /// We have parsed the start of an export declaration, including the '{'
15520 /// (if present).
15521 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15522                                  SourceLocation LBraceLoc) {
15523   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15524 
15525   // C++ Modules TS draft:
15526   //   An export-declaration [...] shall not contain more than one
15527   //   export keyword.
15528   //
15529   // The intent here is that an export-declaration cannot appear within another
15530   // export-declaration.
15531   if (D->isExported())
15532     Diag(ExportLoc, diag::err_export_within_export);
15533 
15534   CurContext->addDecl(D);
15535   PushDeclContext(S, D);
15536   return D;
15537 }
15538 
15539 /// Complete the definition of an export declaration.
15540 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15541   auto *ED = cast<ExportDecl>(D);
15542   if (RBraceLoc.isValid())
15543     ED->setRBraceLoc(RBraceLoc);
15544 
15545   // FIXME: Diagnose export of internal-linkage declaration (including
15546   // anonymous namespace).
15547 
15548   PopDeclContext();
15549   return D;
15550 }
15551 
15552 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15553                                       IdentifierInfo* AliasName,
15554                                       SourceLocation PragmaLoc,
15555                                       SourceLocation NameLoc,
15556                                       SourceLocation AliasNameLoc) {
15557   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15558                                          LookupOrdinaryName);
15559   AsmLabelAttr *Attr =
15560       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15561 
15562   // If a declaration that:
15563   // 1) declares a function or a variable
15564   // 2) has external linkage
15565   // already exists, add a label attribute to it.
15566   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15567     if (isDeclExternC(PrevDecl))
15568       PrevDecl->addAttr(Attr);
15569     else
15570       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15571           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15572   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15573   } else
15574     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15575 }
15576 
15577 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15578                              SourceLocation PragmaLoc,
15579                              SourceLocation NameLoc) {
15580   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15581 
15582   if (PrevDecl) {
15583     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15584   } else {
15585     (void)WeakUndeclaredIdentifiers.insert(
15586       std::pair<IdentifierInfo*,WeakInfo>
15587         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15588   }
15589 }
15590 
15591 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15592                                 IdentifierInfo* AliasName,
15593                                 SourceLocation PragmaLoc,
15594                                 SourceLocation NameLoc,
15595                                 SourceLocation AliasNameLoc) {
15596   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15597                                     LookupOrdinaryName);
15598   WeakInfo W = WeakInfo(Name, NameLoc);
15599 
15600   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15601     if (!PrevDecl->hasAttr<AliasAttr>())
15602       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15603         DeclApplyPragmaWeak(TUScope, ND, W);
15604   } else {
15605     (void)WeakUndeclaredIdentifiers.insert(
15606       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15607   }
15608 }
15609 
15610 Decl *Sema::getObjCDeclContext() const {
15611   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15612 }
15613 
15614 AvailabilityResult Sema::getCurContextAvailability() const {
15615   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15616   if (!D)
15617     return AR_Available;
15618 
15619   // If we are within an Objective-C method, we should consult
15620   // both the availability of the method as well as the
15621   // enclosing class.  If the class is (say) deprecated,
15622   // the entire method is considered deprecated from the
15623   // purpose of checking if the current context is deprecated.
15624   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15625     AvailabilityResult R = MD->getAvailability();
15626     if (R != AR_Available)
15627       return R;
15628     D = MD->getClassInterface();
15629   }
15630   // If we are within an Objective-c @implementation, it
15631   // gets the same availability context as the @interface.
15632   else if (const ObjCImplementationDecl *ID =
15633             dyn_cast<ObjCImplementationDecl>(D)) {
15634     D = ID->getClassInterface();
15635   }
15636   // Recover from user error.
15637   return D ? D->getAvailability() : AR_Available;
15638 }
15639