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++1z [over.load]p2
2937     //   Certain function declarations cannot be overloaded:
2938     //     -- Function declarations that differ only in the return type,
2939     //        the exception specification, or both cannot be overloaded.
2940 
2941     // Check the exception specifications match. This may recompute the type of
2942     // both Old and New if it resolved exception specifications, so grab the
2943     // types again after this. Because this updates the type, we do this before
2944     // any of the other checks below, which may update the "de facto" NewQType
2945     // but do not necessarily update the type of New.
2946     if (CheckEquivalentExceptionSpec(Old, New))
2947       return true;
2948     OldQType = Context.getCanonicalType(Old->getType());
2949     NewQType = Context.getCanonicalType(New->getType());
2950 
2951     // Go back to the type source info to compare the declared return types,
2952     // per C++1y [dcl.type.auto]p13:
2953     //   Redeclarations or specializations of a function or function template
2954     //   with a declared return type that uses a placeholder type shall also
2955     //   use that placeholder, not a deduced type.
2956     QualType OldDeclaredReturnType =
2957         (Old->getTypeSourceInfo()
2958              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2959              : OldType)->getReturnType();
2960     QualType NewDeclaredReturnType =
2961         (New->getTypeSourceInfo()
2962              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2963              : NewType)->getReturnType();
2964     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2965         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2966           New->isLocalExternDecl())) {
2967       QualType ResQT;
2968       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2969           OldDeclaredReturnType->isObjCObjectPointerType())
2970         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2971       if (ResQT.isNull()) {
2972         if (New->isCXXClassMember() && New->isOutOfLine())
2973           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2974               << New << New->getReturnTypeSourceRange();
2975         else
2976           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2977               << New->getReturnTypeSourceRange();
2978         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2979                                     << Old->getReturnTypeSourceRange();
2980         return true;
2981       }
2982       else
2983         NewQType = ResQT;
2984     }
2985 
2986     QualType OldReturnType = OldType->getReturnType();
2987     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2988     if (OldReturnType != NewReturnType) {
2989       // If this function has a deduced return type and has already been
2990       // defined, copy the deduced value from the old declaration.
2991       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2992       if (OldAT && OldAT->isDeduced()) {
2993         New->setType(
2994             SubstAutoType(New->getType(),
2995                           OldAT->isDependentType() ? Context.DependentTy
2996                                                    : OldAT->getDeducedType()));
2997         NewQType = Context.getCanonicalType(
2998             SubstAutoType(NewQType,
2999                           OldAT->isDependentType() ? Context.DependentTy
3000                                                    : OldAT->getDeducedType()));
3001       }
3002     }
3003 
3004     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3005     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3006     if (OldMethod && NewMethod) {
3007       // Preserve triviality.
3008       NewMethod->setTrivial(OldMethod->isTrivial());
3009 
3010       // MSVC allows explicit template specialization at class scope:
3011       // 2 CXXMethodDecls referring to the same function will be injected.
3012       // We don't want a redeclaration error.
3013       bool IsClassScopeExplicitSpecialization =
3014                               OldMethod->isFunctionTemplateSpecialization() &&
3015                               NewMethod->isFunctionTemplateSpecialization();
3016       bool isFriend = NewMethod->getFriendObjectKind();
3017 
3018       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3019           !IsClassScopeExplicitSpecialization) {
3020         //    -- Member function declarations with the same name and the
3021         //       same parameter types cannot be overloaded if any of them
3022         //       is a static member function declaration.
3023         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3024           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3025           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3026           return true;
3027         }
3028 
3029         // C++ [class.mem]p1:
3030         //   [...] A member shall not be declared twice in the
3031         //   member-specification, except that a nested class or member
3032         //   class template can be declared and then later defined.
3033         if (ActiveTemplateInstantiations.empty()) {
3034           unsigned NewDiag;
3035           if (isa<CXXConstructorDecl>(OldMethod))
3036             NewDiag = diag::err_constructor_redeclared;
3037           else if (isa<CXXDestructorDecl>(NewMethod))
3038             NewDiag = diag::err_destructor_redeclared;
3039           else if (isa<CXXConversionDecl>(NewMethod))
3040             NewDiag = diag::err_conv_function_redeclared;
3041           else
3042             NewDiag = diag::err_member_redeclared;
3043 
3044           Diag(New->getLocation(), NewDiag);
3045         } else {
3046           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3047             << New << New->getType();
3048         }
3049         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3050         return true;
3051 
3052       // Complain if this is an explicit declaration of a special
3053       // member that was initially declared implicitly.
3054       //
3055       // As an exception, it's okay to befriend such methods in order
3056       // to permit the implicit constructor/destructor/operator calls.
3057       } else if (OldMethod->isImplicit()) {
3058         if (isFriend) {
3059           NewMethod->setImplicit();
3060         } else {
3061           Diag(NewMethod->getLocation(),
3062                diag::err_definition_of_implicitly_declared_member)
3063             << New << getSpecialMember(OldMethod);
3064           return true;
3065         }
3066       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3067         Diag(NewMethod->getLocation(),
3068              diag::err_definition_of_explicitly_defaulted_member)
3069           << getSpecialMember(OldMethod);
3070         return true;
3071       }
3072     }
3073 
3074     // C++11 [dcl.attr.noreturn]p1:
3075     //   The first declaration of a function shall specify the noreturn
3076     //   attribute if any declaration of that function specifies the noreturn
3077     //   attribute.
3078     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3079     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3080       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3081       Diag(Old->getFirstDecl()->getLocation(),
3082            diag::note_noreturn_missing_first_decl);
3083     }
3084 
3085     // C++11 [dcl.attr.depend]p2:
3086     //   The first declaration of a function shall specify the
3087     //   carries_dependency attribute for its declarator-id if any declaration
3088     //   of the function specifies the carries_dependency attribute.
3089     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3090     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3091       Diag(CDA->getLocation(),
3092            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3093       Diag(Old->getFirstDecl()->getLocation(),
3094            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3095     }
3096 
3097     // (C++98 8.3.5p3):
3098     //   All declarations for a function shall agree exactly in both the
3099     //   return type and the parameter-type-list.
3100     // We also want to respect all the extended bits except noreturn.
3101 
3102     // noreturn should now match unless the old type info didn't have it.
3103     QualType OldQTypeForComparison = OldQType;
3104     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3105       auto *OldType = OldQType->castAs<FunctionProtoType>();
3106       const FunctionType *OldTypeForComparison
3107         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3108       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3109       assert(OldQTypeForComparison.isCanonical());
3110     }
3111 
3112     if (haveIncompatibleLanguageLinkages(Old, New)) {
3113       // As a special case, retain the language linkage from previous
3114       // declarations of a friend function as an extension.
3115       //
3116       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3117       // and is useful because there's otherwise no way to specify language
3118       // linkage within class scope.
3119       //
3120       // Check cautiously as the friend object kind isn't yet complete.
3121       if (New->getFriendObjectKind() != Decl::FOK_None) {
3122         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3123         Diag(OldLocation, PrevDiag);
3124       } else {
3125         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3126         Diag(OldLocation, PrevDiag);
3127         return true;
3128       }
3129     }
3130 
3131     if (OldQTypeForComparison == NewQType)
3132       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3133 
3134     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3135         New->isLocalExternDecl()) {
3136       // It's OK if we couldn't merge types for a local function declaraton
3137       // if either the old or new type is dependent. We'll merge the types
3138       // when we instantiate the function.
3139       return false;
3140     }
3141 
3142     // Fall through for conflicting redeclarations and redefinitions.
3143   }
3144 
3145   // C: Function types need to be compatible, not identical. This handles
3146   // duplicate function decls like "void f(int); void f(enum X);" properly.
3147   if (!getLangOpts().CPlusPlus &&
3148       Context.typesAreCompatible(OldQType, NewQType)) {
3149     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3150     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3151     const FunctionProtoType *OldProto = nullptr;
3152     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3153         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3154       // The old declaration provided a function prototype, but the
3155       // new declaration does not. Merge in the prototype.
3156       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3157       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3158       NewQType =
3159           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3160                                   OldProto->getExtProtoInfo());
3161       New->setType(NewQType);
3162       New->setHasInheritedPrototype();
3163 
3164       // Synthesize parameters with the same types.
3165       SmallVector<ParmVarDecl*, 16> Params;
3166       for (const auto &ParamType : OldProto->param_types()) {
3167         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3168                                                  SourceLocation(), nullptr,
3169                                                  ParamType, /*TInfo=*/nullptr,
3170                                                  SC_None, nullptr);
3171         Param->setScopeInfo(0, Params.size());
3172         Param->setImplicit();
3173         Params.push_back(Param);
3174       }
3175 
3176       New->setParams(Params);
3177     }
3178 
3179     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3180   }
3181 
3182   // GNU C permits a K&R definition to follow a prototype declaration
3183   // if the declared types of the parameters in the K&R definition
3184   // match the types in the prototype declaration, even when the
3185   // promoted types of the parameters from the K&R definition differ
3186   // from the types in the prototype. GCC then keeps the types from
3187   // the prototype.
3188   //
3189   // If a variadic prototype is followed by a non-variadic K&R definition,
3190   // the K&R definition becomes variadic.  This is sort of an edge case, but
3191   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3192   // C99 6.9.1p8.
3193   if (!getLangOpts().CPlusPlus &&
3194       Old->hasPrototype() && !New->hasPrototype() &&
3195       New->getType()->getAs<FunctionProtoType>() &&
3196       Old->getNumParams() == New->getNumParams()) {
3197     SmallVector<QualType, 16> ArgTypes;
3198     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3199     const FunctionProtoType *OldProto
3200       = Old->getType()->getAs<FunctionProtoType>();
3201     const FunctionProtoType *NewProto
3202       = New->getType()->getAs<FunctionProtoType>();
3203 
3204     // Determine whether this is the GNU C extension.
3205     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3206                                                NewProto->getReturnType());
3207     bool LooseCompatible = !MergedReturn.isNull();
3208     for (unsigned Idx = 0, End = Old->getNumParams();
3209          LooseCompatible && Idx != End; ++Idx) {
3210       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3211       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3212       if (Context.typesAreCompatible(OldParm->getType(),
3213                                      NewProto->getParamType(Idx))) {
3214         ArgTypes.push_back(NewParm->getType());
3215       } else if (Context.typesAreCompatible(OldParm->getType(),
3216                                             NewParm->getType(),
3217                                             /*CompareUnqualified=*/true)) {
3218         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3219                                            NewProto->getParamType(Idx) };
3220         Warnings.push_back(Warn);
3221         ArgTypes.push_back(NewParm->getType());
3222       } else
3223         LooseCompatible = false;
3224     }
3225 
3226     if (LooseCompatible) {
3227       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3228         Diag(Warnings[Warn].NewParm->getLocation(),
3229              diag::ext_param_promoted_not_compatible_with_prototype)
3230           << Warnings[Warn].PromotedType
3231           << Warnings[Warn].OldParm->getType();
3232         if (Warnings[Warn].OldParm->getLocation().isValid())
3233           Diag(Warnings[Warn].OldParm->getLocation(),
3234                diag::note_previous_declaration);
3235       }
3236 
3237       if (MergeTypeWithOld)
3238         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3239                                              OldProto->getExtProtoInfo()));
3240       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3241     }
3242 
3243     // Fall through to diagnose conflicting types.
3244   }
3245 
3246   // A function that has already been declared has been redeclared or
3247   // defined with a different type; show an appropriate diagnostic.
3248 
3249   // If the previous declaration was an implicitly-generated builtin
3250   // declaration, then at the very least we should use a specialized note.
3251   unsigned BuiltinID;
3252   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3253     // If it's actually a library-defined builtin function like 'malloc'
3254     // or 'printf', just warn about the incompatible redeclaration.
3255     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3256       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3257       Diag(OldLocation, diag::note_previous_builtin_declaration)
3258         << Old << Old->getType();
3259 
3260       // If this is a global redeclaration, just forget hereafter
3261       // about the "builtin-ness" of the function.
3262       //
3263       // Doing this for local extern declarations is problematic.  If
3264       // the builtin declaration remains visible, a second invalid
3265       // local declaration will produce a hard error; if it doesn't
3266       // remain visible, a single bogus local redeclaration (which is
3267       // actually only a warning) could break all the downstream code.
3268       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3269         New->getIdentifier()->revertBuiltin();
3270 
3271       return false;
3272     }
3273 
3274     PrevDiag = diag::note_previous_builtin_declaration;
3275   }
3276 
3277   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3278   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3279   return true;
3280 }
3281 
3282 /// \brief Completes the merge of two function declarations that are
3283 /// known to be compatible.
3284 ///
3285 /// This routine handles the merging of attributes and other
3286 /// properties of function declarations from the old declaration to
3287 /// the new declaration, once we know that New is in fact a
3288 /// redeclaration of Old.
3289 ///
3290 /// \returns false
3291 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3292                                         Scope *S, bool MergeTypeWithOld) {
3293   // Merge the attributes
3294   mergeDeclAttributes(New, Old);
3295 
3296   // Merge "pure" flag.
3297   if (Old->isPure())
3298     New->setPure();
3299 
3300   // Merge "used" flag.
3301   if (Old->getMostRecentDecl()->isUsed(false))
3302     New->setIsUsed();
3303 
3304   // Merge attributes from the parameters.  These can mismatch with K&R
3305   // declarations.
3306   if (New->getNumParams() == Old->getNumParams())
3307       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3308         ParmVarDecl *NewParam = New->getParamDecl(i);
3309         ParmVarDecl *OldParam = Old->getParamDecl(i);
3310         mergeParamDeclAttributes(NewParam, OldParam, *this);
3311         mergeParamDeclTypes(NewParam, OldParam, *this);
3312       }
3313 
3314   if (getLangOpts().CPlusPlus)
3315     return MergeCXXFunctionDecl(New, Old, S);
3316 
3317   // Merge the function types so the we get the composite types for the return
3318   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3319   // was visible.
3320   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3321   if (!Merged.isNull() && MergeTypeWithOld)
3322     New->setType(Merged);
3323 
3324   return false;
3325 }
3326 
3327 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3328                                 ObjCMethodDecl *oldMethod) {
3329   // Merge the attributes, including deprecated/unavailable
3330   AvailabilityMergeKind MergeKind =
3331     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3332       ? AMK_ProtocolImplementation
3333       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3334                                                        : AMK_Override;
3335 
3336   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3337 
3338   // Merge attributes from the parameters.
3339   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3340                                        oe = oldMethod->param_end();
3341   for (ObjCMethodDecl::param_iterator
3342          ni = newMethod->param_begin(), ne = newMethod->param_end();
3343        ni != ne && oi != oe; ++ni, ++oi)
3344     mergeParamDeclAttributes(*ni, *oi, *this);
3345 
3346   CheckObjCMethodOverride(newMethod, oldMethod);
3347 }
3348 
3349 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3350   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3351 
3352   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3353          ? diag::err_redefinition_different_type
3354          : diag::err_redeclaration_different_type)
3355     << New->getDeclName() << New->getType() << Old->getType();
3356 
3357   diag::kind PrevDiag;
3358   SourceLocation OldLocation;
3359   std::tie(PrevDiag, OldLocation)
3360     = getNoteDiagForInvalidRedeclaration(Old, New);
3361   S.Diag(OldLocation, PrevDiag);
3362   New->setInvalidDecl();
3363 }
3364 
3365 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3366 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3367 /// emitting diagnostics as appropriate.
3368 ///
3369 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3370 /// to here in AddInitializerToDecl. We can't check them before the initializer
3371 /// is attached.
3372 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3373                              bool MergeTypeWithOld) {
3374   if (New->isInvalidDecl() || Old->isInvalidDecl())
3375     return;
3376 
3377   QualType MergedT;
3378   if (getLangOpts().CPlusPlus) {
3379     if (New->getType()->isUndeducedType()) {
3380       // We don't know what the new type is until the initializer is attached.
3381       return;
3382     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3383       // These could still be something that needs exception specs checked.
3384       return MergeVarDeclExceptionSpecs(New, Old);
3385     }
3386     // C++ [basic.link]p10:
3387     //   [...] the types specified by all declarations referring to a given
3388     //   object or function shall be identical, except that declarations for an
3389     //   array object can specify array types that differ by the presence or
3390     //   absence of a major array bound (8.3.4).
3391     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3392       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3393       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3394 
3395       // We are merging a variable declaration New into Old. If it has an array
3396       // bound, and that bound differs from Old's bound, we should diagnose the
3397       // mismatch.
3398       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3399         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3400              PrevVD = PrevVD->getPreviousDecl()) {
3401           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3402           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3403             continue;
3404 
3405           if (!Context.hasSameType(NewArray, PrevVDTy))
3406             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3407         }
3408       }
3409 
3410       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3411         if (Context.hasSameType(OldArray->getElementType(),
3412                                 NewArray->getElementType()))
3413           MergedT = New->getType();
3414       }
3415       // FIXME: Check visibility. New is hidden but has a complete type. If New
3416       // has no array bound, it should not inherit one from Old, if Old is not
3417       // visible.
3418       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3419         if (Context.hasSameType(OldArray->getElementType(),
3420                                 NewArray->getElementType()))
3421           MergedT = Old->getType();
3422       }
3423     }
3424     else if (New->getType()->isObjCObjectPointerType() &&
3425                Old->getType()->isObjCObjectPointerType()) {
3426       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3427                                               Old->getType());
3428     }
3429   } else {
3430     // C 6.2.7p2:
3431     //   All declarations that refer to the same object or function shall have
3432     //   compatible type.
3433     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3434   }
3435   if (MergedT.isNull()) {
3436     // It's OK if we couldn't merge types if either type is dependent, for a
3437     // block-scope variable. In other cases (static data members of class
3438     // templates, variable templates, ...), we require the types to be
3439     // equivalent.
3440     // FIXME: The C++ standard doesn't say anything about this.
3441     if ((New->getType()->isDependentType() ||
3442          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3443       // If the old type was dependent, we can't merge with it, so the new type
3444       // becomes dependent for now. We'll reproduce the original type when we
3445       // instantiate the TypeSourceInfo for the variable.
3446       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3447         New->setType(Context.DependentTy);
3448       return;
3449     }
3450     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3451   }
3452 
3453   // Don't actually update the type on the new declaration if the old
3454   // declaration was an extern declaration in a different scope.
3455   if (MergeTypeWithOld)
3456     New->setType(MergedT);
3457 }
3458 
3459 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3460                                   LookupResult &Previous) {
3461   // C11 6.2.7p4:
3462   //   For an identifier with internal or external linkage declared
3463   //   in a scope in which a prior declaration of that identifier is
3464   //   visible, if the prior declaration specifies internal or
3465   //   external linkage, the type of the identifier at the later
3466   //   declaration becomes the composite type.
3467   //
3468   // If the variable isn't visible, we do not merge with its type.
3469   if (Previous.isShadowed())
3470     return false;
3471 
3472   if (S.getLangOpts().CPlusPlus) {
3473     // C++11 [dcl.array]p3:
3474     //   If there is a preceding declaration of the entity in the same
3475     //   scope in which the bound was specified, an omitted array bound
3476     //   is taken to be the same as in that earlier declaration.
3477     return NewVD->isPreviousDeclInSameBlockScope() ||
3478            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3479             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3480   } else {
3481     // If the old declaration was function-local, don't merge with its
3482     // type unless we're in the same function.
3483     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3484            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3485   }
3486 }
3487 
3488 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3489 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3490 /// situation, merging decls or emitting diagnostics as appropriate.
3491 ///
3492 /// Tentative definition rules (C99 6.9.2p2) are checked by
3493 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3494 /// definitions here, since the initializer hasn't been attached.
3495 ///
3496 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3497   // If the new decl is already invalid, don't do any other checking.
3498   if (New->isInvalidDecl())
3499     return;
3500 
3501   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3502     return;
3503 
3504   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3505 
3506   // Verify the old decl was also a variable or variable template.
3507   VarDecl *Old = nullptr;
3508   VarTemplateDecl *OldTemplate = nullptr;
3509   if (Previous.isSingleResult()) {
3510     if (NewTemplate) {
3511       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3512       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3513 
3514       if (auto *Shadow =
3515               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3516         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3517           return New->setInvalidDecl();
3518     } else {
3519       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3520 
3521       if (auto *Shadow =
3522               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3523         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3524           return New->setInvalidDecl();
3525     }
3526   }
3527   if (!Old) {
3528     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3529       << New->getDeclName();
3530     Diag(Previous.getRepresentativeDecl()->getLocation(),
3531          diag::note_previous_definition);
3532     return New->setInvalidDecl();
3533   }
3534 
3535   // Ensure the template parameters are compatible.
3536   if (NewTemplate &&
3537       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3538                                       OldTemplate->getTemplateParameters(),
3539                                       /*Complain=*/true, TPL_TemplateMatch))
3540     return New->setInvalidDecl();
3541 
3542   // C++ [class.mem]p1:
3543   //   A member shall not be declared twice in the member-specification [...]
3544   //
3545   // Here, we need only consider static data members.
3546   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3547     Diag(New->getLocation(), diag::err_duplicate_member)
3548       << New->getIdentifier();
3549     Diag(Old->getLocation(), diag::note_previous_declaration);
3550     New->setInvalidDecl();
3551   }
3552 
3553   mergeDeclAttributes(New, Old);
3554   // Warn if an already-declared variable is made a weak_import in a subsequent
3555   // declaration
3556   if (New->hasAttr<WeakImportAttr>() &&
3557       Old->getStorageClass() == SC_None &&
3558       !Old->hasAttr<WeakImportAttr>()) {
3559     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3560     Diag(Old->getLocation(), diag::note_previous_definition);
3561     // Remove weak_import attribute on new declaration.
3562     New->dropAttr<WeakImportAttr>();
3563   }
3564 
3565   if (New->hasAttr<InternalLinkageAttr>() &&
3566       !Old->hasAttr<InternalLinkageAttr>()) {
3567     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3568         << New->getDeclName();
3569     Diag(Old->getLocation(), diag::note_previous_definition);
3570     New->dropAttr<InternalLinkageAttr>();
3571   }
3572 
3573   // Merge the types.
3574   VarDecl *MostRecent = Old->getMostRecentDecl();
3575   if (MostRecent != Old) {
3576     MergeVarDeclTypes(New, MostRecent,
3577                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3578     if (New->isInvalidDecl())
3579       return;
3580   }
3581 
3582   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3583   if (New->isInvalidDecl())
3584     return;
3585 
3586   diag::kind PrevDiag;
3587   SourceLocation OldLocation;
3588   std::tie(PrevDiag, OldLocation) =
3589       getNoteDiagForInvalidRedeclaration(Old, New);
3590 
3591   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3592   if (New->getStorageClass() == SC_Static &&
3593       !New->isStaticDataMember() &&
3594       Old->hasExternalFormalLinkage()) {
3595     if (getLangOpts().MicrosoftExt) {
3596       Diag(New->getLocation(), diag::ext_static_non_static)
3597           << New->getDeclName();
3598       Diag(OldLocation, PrevDiag);
3599     } else {
3600       Diag(New->getLocation(), diag::err_static_non_static)
3601           << New->getDeclName();
3602       Diag(OldLocation, PrevDiag);
3603       return New->setInvalidDecl();
3604     }
3605   }
3606   // C99 6.2.2p4:
3607   //   For an identifier declared with the storage-class specifier
3608   //   extern in a scope in which a prior declaration of that
3609   //   identifier is visible,23) if the prior declaration specifies
3610   //   internal or external linkage, the linkage of the identifier at
3611   //   the later declaration is the same as the linkage specified at
3612   //   the prior declaration. If no prior declaration is visible, or
3613   //   if the prior declaration specifies no linkage, then the
3614   //   identifier has external linkage.
3615   if (New->hasExternalStorage() && Old->hasLinkage())
3616     /* Okay */;
3617   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3618            !New->isStaticDataMember() &&
3619            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3620     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3621     Diag(OldLocation, PrevDiag);
3622     return New->setInvalidDecl();
3623   }
3624 
3625   // Check if extern is followed by non-extern and vice-versa.
3626   if (New->hasExternalStorage() &&
3627       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3628     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3629     Diag(OldLocation, PrevDiag);
3630     return New->setInvalidDecl();
3631   }
3632   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3633       !New->hasExternalStorage()) {
3634     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3635     Diag(OldLocation, PrevDiag);
3636     return New->setInvalidDecl();
3637   }
3638 
3639   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3640 
3641   // FIXME: The test for external storage here seems wrong? We still
3642   // need to check for mismatches.
3643   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3644       // Don't complain about out-of-line definitions of static members.
3645       !(Old->getLexicalDeclContext()->isRecord() &&
3646         !New->getLexicalDeclContext()->isRecord())) {
3647     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3648     Diag(OldLocation, PrevDiag);
3649     return New->setInvalidDecl();
3650   }
3651 
3652   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3653     if (VarDecl *Def = Old->getDefinition()) {
3654       // C++1z [dcl.fcn.spec]p4:
3655       //   If the definition of a variable appears in a translation unit before
3656       //   its first declaration as inline, the program is ill-formed.
3657       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3658       Diag(Def->getLocation(), diag::note_previous_definition);
3659     }
3660   }
3661 
3662   // If this redeclaration makes the function inline, we may need to add it to
3663   // UndefinedButUsed.
3664   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3665       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3666     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3667                                            SourceLocation()));
3668 
3669   if (New->getTLSKind() != Old->getTLSKind()) {
3670     if (!Old->getTLSKind()) {
3671       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3672       Diag(OldLocation, PrevDiag);
3673     } else if (!New->getTLSKind()) {
3674       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3675       Diag(OldLocation, PrevDiag);
3676     } else {
3677       // Do not allow redeclaration to change the variable between requiring
3678       // static and dynamic initialization.
3679       // FIXME: GCC allows this, but uses the TLS keyword on the first
3680       // declaration to determine the kind. Do we need to be compatible here?
3681       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3682         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3683       Diag(OldLocation, PrevDiag);
3684     }
3685   }
3686 
3687   // C++ doesn't have tentative definitions, so go right ahead and check here.
3688   if (getLangOpts().CPlusPlus &&
3689       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3690     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3691         Old->getCanonicalDecl()->isConstexpr()) {
3692       // This definition won't be a definition any more once it's been merged.
3693       Diag(New->getLocation(),
3694            diag::warn_deprecated_redundant_constexpr_static_def);
3695     } else if (VarDecl *Def = Old->getDefinition()) {
3696       if (checkVarDeclRedefinition(Def, New))
3697         return;
3698     }
3699   }
3700 
3701   if (haveIncompatibleLanguageLinkages(Old, New)) {
3702     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3703     Diag(OldLocation, PrevDiag);
3704     New->setInvalidDecl();
3705     return;
3706   }
3707 
3708   // Merge "used" flag.
3709   if (Old->getMostRecentDecl()->isUsed(false))
3710     New->setIsUsed();
3711 
3712   // Keep a chain of previous declarations.
3713   New->setPreviousDecl(Old);
3714   if (NewTemplate)
3715     NewTemplate->setPreviousDecl(OldTemplate);
3716 
3717   // Inherit access appropriately.
3718   New->setAccess(Old->getAccess());
3719   if (NewTemplate)
3720     NewTemplate->setAccess(New->getAccess());
3721 
3722   if (Old->isInline())
3723     New->setImplicitlyInline();
3724 }
3725 
3726 /// We've just determined that \p Old and \p New both appear to be definitions
3727 /// of the same variable. Either diagnose or fix the problem.
3728 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3729   if (!hasVisibleDefinition(Old) &&
3730       (New->getFormalLinkage() == InternalLinkage ||
3731        New->isInline() ||
3732        New->getDescribedVarTemplate() ||
3733        New->getNumTemplateParameterLists() ||
3734        New->getDeclContext()->isDependentContext())) {
3735     // The previous definition is hidden, and multiple definitions are
3736     // permitted (in separate TUs). Demote this to a declaration.
3737     New->demoteThisDefinitionToDeclaration();
3738 
3739     // Make the canonical definition visible.
3740     if (auto *OldTD = Old->getDescribedVarTemplate())
3741       makeMergedDefinitionVisible(OldTD, New->getLocation());
3742     makeMergedDefinitionVisible(Old, New->getLocation());
3743     return false;
3744   } else {
3745     Diag(New->getLocation(), diag::err_redefinition) << New;
3746     Diag(Old->getLocation(), diag::note_previous_definition);
3747     New->setInvalidDecl();
3748     return true;
3749   }
3750 }
3751 
3752 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3753 /// no declarator (e.g. "struct foo;") is parsed.
3754 Decl *
3755 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3756                                  RecordDecl *&AnonRecord) {
3757   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3758                                     AnonRecord);
3759 }
3760 
3761 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3762 // disambiguate entities defined in different scopes.
3763 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3764 // compatibility.
3765 // We will pick our mangling number depending on which version of MSVC is being
3766 // targeted.
3767 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3768   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3769              ? S->getMSCurManglingNumber()
3770              : S->getMSLastManglingNumber();
3771 }
3772 
3773 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3774   if (!Context.getLangOpts().CPlusPlus)
3775     return;
3776 
3777   if (isa<CXXRecordDecl>(Tag->getParent())) {
3778     // If this tag is the direct child of a class, number it if
3779     // it is anonymous.
3780     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3781       return;
3782     MangleNumberingContext &MCtx =
3783         Context.getManglingNumberContext(Tag->getParent());
3784     Context.setManglingNumber(
3785         Tag, MCtx.getManglingNumber(
3786                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3787     return;
3788   }
3789 
3790   // If this tag isn't a direct child of a class, number it if it is local.
3791   Decl *ManglingContextDecl;
3792   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3793           Tag->getDeclContext(), ManglingContextDecl)) {
3794     Context.setManglingNumber(
3795         Tag, MCtx->getManglingNumber(
3796                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3797   }
3798 }
3799 
3800 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3801                                         TypedefNameDecl *NewTD) {
3802   if (TagFromDeclSpec->isInvalidDecl())
3803     return;
3804 
3805   // Do nothing if the tag already has a name for linkage purposes.
3806   if (TagFromDeclSpec->hasNameForLinkage())
3807     return;
3808 
3809   // A well-formed anonymous tag must always be a TUK_Definition.
3810   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3811 
3812   // The type must match the tag exactly;  no qualifiers allowed.
3813   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3814                            Context.getTagDeclType(TagFromDeclSpec))) {
3815     if (getLangOpts().CPlusPlus)
3816       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3817     return;
3818   }
3819 
3820   // If we've already computed linkage for the anonymous tag, then
3821   // adding a typedef name for the anonymous decl can change that
3822   // linkage, which might be a serious problem.  Diagnose this as
3823   // unsupported and ignore the typedef name.  TODO: we should
3824   // pursue this as a language defect and establish a formal rule
3825   // for how to handle it.
3826   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3827     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3828 
3829     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3830     tagLoc = getLocForEndOfToken(tagLoc);
3831 
3832     llvm::SmallString<40> textToInsert;
3833     textToInsert += ' ';
3834     textToInsert += NewTD->getIdentifier()->getName();
3835     Diag(tagLoc, diag::note_typedef_changes_linkage)
3836         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3837     return;
3838   }
3839 
3840   // Otherwise, set this is the anon-decl typedef for the tag.
3841   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3842 }
3843 
3844 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3845   switch (T) {
3846   case DeclSpec::TST_class:
3847     return 0;
3848   case DeclSpec::TST_struct:
3849     return 1;
3850   case DeclSpec::TST_interface:
3851     return 2;
3852   case DeclSpec::TST_union:
3853     return 3;
3854   case DeclSpec::TST_enum:
3855     return 4;
3856   default:
3857     llvm_unreachable("unexpected type specifier");
3858   }
3859 }
3860 
3861 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3862 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3863 /// parameters to cope with template friend declarations.
3864 Decl *
3865 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3866                                  MultiTemplateParamsArg TemplateParams,
3867                                  bool IsExplicitInstantiation,
3868                                  RecordDecl *&AnonRecord) {
3869   Decl *TagD = nullptr;
3870   TagDecl *Tag = nullptr;
3871   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3872       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3873       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3874       DS.getTypeSpecType() == DeclSpec::TST_union ||
3875       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3876     TagD = DS.getRepAsDecl();
3877 
3878     if (!TagD) // We probably had an error
3879       return nullptr;
3880 
3881     // Note that the above type specs guarantee that the
3882     // type rep is a Decl, whereas in many of the others
3883     // it's a Type.
3884     if (isa<TagDecl>(TagD))
3885       Tag = cast<TagDecl>(TagD);
3886     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3887       Tag = CTD->getTemplatedDecl();
3888   }
3889 
3890   if (Tag) {
3891     handleTagNumbering(Tag, S);
3892     Tag->setFreeStanding();
3893     if (Tag->isInvalidDecl())
3894       return Tag;
3895   }
3896 
3897   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3898     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3899     // or incomplete types shall not be restrict-qualified."
3900     if (TypeQuals & DeclSpec::TQ_restrict)
3901       Diag(DS.getRestrictSpecLoc(),
3902            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3903            << DS.getSourceRange();
3904   }
3905 
3906   if (DS.isInlineSpecified())
3907     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3908         << getLangOpts().CPlusPlus1z;
3909 
3910   if (DS.isConstexprSpecified()) {
3911     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3912     // and definitions of functions and variables.
3913     if (Tag)
3914       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3915           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3916     else
3917       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3918     // Don't emit warnings after this error.
3919     return TagD;
3920   }
3921 
3922   if (DS.isConceptSpecified()) {
3923     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3924     // either a function concept and its definition or a variable concept and
3925     // its initializer.
3926     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3927     return TagD;
3928   }
3929 
3930   DiagnoseFunctionSpecifiers(DS);
3931 
3932   if (DS.isFriendSpecified()) {
3933     // If we're dealing with a decl but not a TagDecl, assume that
3934     // whatever routines created it handled the friendship aspect.
3935     if (TagD && !Tag)
3936       return nullptr;
3937     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3938   }
3939 
3940   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3941   bool IsExplicitSpecialization =
3942     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3943   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3944       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3945       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3946     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3947     // nested-name-specifier unless it is an explicit instantiation
3948     // or an explicit specialization.
3949     //
3950     // FIXME: We allow class template partial specializations here too, per the
3951     // obvious intent of DR1819.
3952     //
3953     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3954     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3955         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3956     return nullptr;
3957   }
3958 
3959   // Track whether this decl-specifier declares anything.
3960   bool DeclaresAnything = true;
3961 
3962   // Handle anonymous struct definitions.
3963   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3964     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3965         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3966       if (getLangOpts().CPlusPlus ||
3967           Record->getDeclContext()->isRecord()) {
3968         // If CurContext is a DeclContext that can contain statements,
3969         // RecursiveASTVisitor won't visit the decls that
3970         // BuildAnonymousStructOrUnion() will put into CurContext.
3971         // Also store them here so that they can be part of the
3972         // DeclStmt that gets created in this case.
3973         // FIXME: Also return the IndirectFieldDecls created by
3974         // BuildAnonymousStructOr union, for the same reason?
3975         if (CurContext->isFunctionOrMethod())
3976           AnonRecord = Record;
3977         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3978                                            Context.getPrintingPolicy());
3979       }
3980 
3981       DeclaresAnything = false;
3982     }
3983   }
3984 
3985   // C11 6.7.2.1p2:
3986   //   A struct-declaration that does not declare an anonymous structure or
3987   //   anonymous union shall contain a struct-declarator-list.
3988   //
3989   // This rule also existed in C89 and C99; the grammar for struct-declaration
3990   // did not permit a struct-declaration without a struct-declarator-list.
3991   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3992       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3993     // Check for Microsoft C extension: anonymous struct/union member.
3994     // Handle 2 kinds of anonymous struct/union:
3995     //   struct STRUCT;
3996     //   union UNION;
3997     // and
3998     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3999     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4000     if ((Tag && Tag->getDeclName()) ||
4001         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4002       RecordDecl *Record = nullptr;
4003       if (Tag)
4004         Record = dyn_cast<RecordDecl>(Tag);
4005       else if (const RecordType *RT =
4006                    DS.getRepAsType().get()->getAsStructureType())
4007         Record = RT->getDecl();
4008       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4009         Record = UT->getDecl();
4010 
4011       if (Record && getLangOpts().MicrosoftExt) {
4012         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4013           << Record->isUnion() << DS.getSourceRange();
4014         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4015       }
4016 
4017       DeclaresAnything = false;
4018     }
4019   }
4020 
4021   // Skip all the checks below if we have a type error.
4022   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4023       (TagD && TagD->isInvalidDecl()))
4024     return TagD;
4025 
4026   if (getLangOpts().CPlusPlus &&
4027       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4028     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4029       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4030           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4031         DeclaresAnything = false;
4032 
4033   if (!DS.isMissingDeclaratorOk()) {
4034     // Customize diagnostic for a typedef missing a name.
4035     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4036       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4037         << DS.getSourceRange();
4038     else
4039       DeclaresAnything = false;
4040   }
4041 
4042   if (DS.isModulePrivateSpecified() &&
4043       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4044     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4045       << Tag->getTagKind()
4046       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4047 
4048   ActOnDocumentableDecl(TagD);
4049 
4050   // C 6.7/2:
4051   //   A declaration [...] shall declare at least a declarator [...], a tag,
4052   //   or the members of an enumeration.
4053   // C++ [dcl.dcl]p3:
4054   //   [If there are no declarators], and except for the declaration of an
4055   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4056   //   names into the program, or shall redeclare a name introduced by a
4057   //   previous declaration.
4058   if (!DeclaresAnything) {
4059     // In C, we allow this as a (popular) extension / bug. Don't bother
4060     // producing further diagnostics for redundant qualifiers after this.
4061     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4062     return TagD;
4063   }
4064 
4065   // C++ [dcl.stc]p1:
4066   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4067   //   init-declarator-list of the declaration shall not be empty.
4068   // C++ [dcl.fct.spec]p1:
4069   //   If a cv-qualifier appears in a decl-specifier-seq, the
4070   //   init-declarator-list of the declaration shall not be empty.
4071   //
4072   // Spurious qualifiers here appear to be valid in C.
4073   unsigned DiagID = diag::warn_standalone_specifier;
4074   if (getLangOpts().CPlusPlus)
4075     DiagID = diag::ext_standalone_specifier;
4076 
4077   // Note that a linkage-specification sets a storage class, but
4078   // 'extern "C" struct foo;' is actually valid and not theoretically
4079   // useless.
4080   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4081     if (SCS == DeclSpec::SCS_mutable)
4082       // Since mutable is not a viable storage class specifier in C, there is
4083       // no reason to treat it as an extension. Instead, diagnose as an error.
4084       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4085     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4086       Diag(DS.getStorageClassSpecLoc(), DiagID)
4087         << DeclSpec::getSpecifierName(SCS);
4088   }
4089 
4090   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4091     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4092       << DeclSpec::getSpecifierName(TSCS);
4093   if (DS.getTypeQualifiers()) {
4094     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4095       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4096     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4097       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4098     // Restrict is covered above.
4099     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4100       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4101     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4102       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4103   }
4104 
4105   // Warn about ignored type attributes, for example:
4106   // __attribute__((aligned)) struct A;
4107   // Attributes should be placed after tag to apply to type declaration.
4108   if (!DS.getAttributes().empty()) {
4109     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4110     if (TypeSpecType == DeclSpec::TST_class ||
4111         TypeSpecType == DeclSpec::TST_struct ||
4112         TypeSpecType == DeclSpec::TST_interface ||
4113         TypeSpecType == DeclSpec::TST_union ||
4114         TypeSpecType == DeclSpec::TST_enum) {
4115       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4116            attrs = attrs->getNext())
4117         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4118             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4119     }
4120   }
4121 
4122   return TagD;
4123 }
4124 
4125 /// We are trying to inject an anonymous member into the given scope;
4126 /// check if there's an existing declaration that can't be overloaded.
4127 ///
4128 /// \return true if this is a forbidden redeclaration
4129 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4130                                          Scope *S,
4131                                          DeclContext *Owner,
4132                                          DeclarationName Name,
4133                                          SourceLocation NameLoc,
4134                                          bool IsUnion) {
4135   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4136                  Sema::ForRedeclaration);
4137   if (!SemaRef.LookupName(R, S)) return false;
4138 
4139   // Pick a representative declaration.
4140   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4141   assert(PrevDecl && "Expected a non-null Decl");
4142 
4143   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4144     return false;
4145 
4146   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4147     << IsUnion << Name;
4148   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4149 
4150   return true;
4151 }
4152 
4153 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4154 /// anonymous struct or union AnonRecord into the owning context Owner
4155 /// and scope S. This routine will be invoked just after we realize
4156 /// that an unnamed union or struct is actually an anonymous union or
4157 /// struct, e.g.,
4158 ///
4159 /// @code
4160 /// union {
4161 ///   int i;
4162 ///   float f;
4163 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4164 ///    // f into the surrounding scope.x
4165 /// @endcode
4166 ///
4167 /// This routine is recursive, injecting the names of nested anonymous
4168 /// structs/unions into the owning context and scope as well.
4169 static bool
4170 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4171                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4172                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4173   bool Invalid = false;
4174 
4175   // Look every FieldDecl and IndirectFieldDecl with a name.
4176   for (auto *D : AnonRecord->decls()) {
4177     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4178         cast<NamedDecl>(D)->getDeclName()) {
4179       ValueDecl *VD = cast<ValueDecl>(D);
4180       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4181                                        VD->getLocation(),
4182                                        AnonRecord->isUnion())) {
4183         // C++ [class.union]p2:
4184         //   The names of the members of an anonymous union shall be
4185         //   distinct from the names of any other entity in the
4186         //   scope in which the anonymous union is declared.
4187         Invalid = true;
4188       } else {
4189         // C++ [class.union]p2:
4190         //   For the purpose of name lookup, after the anonymous union
4191         //   definition, the members of the anonymous union are
4192         //   considered to have been defined in the scope in which the
4193         //   anonymous union is declared.
4194         unsigned OldChainingSize = Chaining.size();
4195         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4196           Chaining.append(IF->chain_begin(), IF->chain_end());
4197         else
4198           Chaining.push_back(VD);
4199 
4200         assert(Chaining.size() >= 2);
4201         NamedDecl **NamedChain =
4202           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4203         for (unsigned i = 0; i < Chaining.size(); i++)
4204           NamedChain[i] = Chaining[i];
4205 
4206         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4207             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4208             VD->getType(), {NamedChain, Chaining.size()});
4209 
4210         for (const auto *Attr : VD->attrs())
4211           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4212 
4213         IndirectField->setAccess(AS);
4214         IndirectField->setImplicit();
4215         SemaRef.PushOnScopeChains(IndirectField, S);
4216 
4217         // That includes picking up the appropriate access specifier.
4218         if (AS != AS_none) IndirectField->setAccess(AS);
4219 
4220         Chaining.resize(OldChainingSize);
4221       }
4222     }
4223   }
4224 
4225   return Invalid;
4226 }
4227 
4228 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4229 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4230 /// illegal input values are mapped to SC_None.
4231 static StorageClass
4232 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4233   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4234   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4235          "Parser allowed 'typedef' as storage class VarDecl.");
4236   switch (StorageClassSpec) {
4237   case DeclSpec::SCS_unspecified:    return SC_None;
4238   case DeclSpec::SCS_extern:
4239     if (DS.isExternInLinkageSpec())
4240       return SC_None;
4241     return SC_Extern;
4242   case DeclSpec::SCS_static:         return SC_Static;
4243   case DeclSpec::SCS_auto:           return SC_Auto;
4244   case DeclSpec::SCS_register:       return SC_Register;
4245   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4246     // Illegal SCSs map to None: error reporting is up to the caller.
4247   case DeclSpec::SCS_mutable:        // Fall through.
4248   case DeclSpec::SCS_typedef:        return SC_None;
4249   }
4250   llvm_unreachable("unknown storage class specifier");
4251 }
4252 
4253 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4254   assert(Record->hasInClassInitializer());
4255 
4256   for (const auto *I : Record->decls()) {
4257     const auto *FD = dyn_cast<FieldDecl>(I);
4258     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4259       FD = IFD->getAnonField();
4260     if (FD && FD->hasInClassInitializer())
4261       return FD->getLocation();
4262   }
4263 
4264   llvm_unreachable("couldn't find in-class initializer");
4265 }
4266 
4267 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4268                                       SourceLocation DefaultInitLoc) {
4269   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4270     return;
4271 
4272   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4273   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4274 }
4275 
4276 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4277                                       CXXRecordDecl *AnonUnion) {
4278   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4279     return;
4280 
4281   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4282 }
4283 
4284 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4285 /// anonymous structure or union. Anonymous unions are a C++ feature
4286 /// (C++ [class.union]) and a C11 feature; anonymous structures
4287 /// are a C11 feature and GNU C++ extension.
4288 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4289                                         AccessSpecifier AS,
4290                                         RecordDecl *Record,
4291                                         const PrintingPolicy &Policy) {
4292   DeclContext *Owner = Record->getDeclContext();
4293 
4294   // Diagnose whether this anonymous struct/union is an extension.
4295   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4296     Diag(Record->getLocation(), diag::ext_anonymous_union);
4297   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4298     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4299   else if (!Record->isUnion() && !getLangOpts().C11)
4300     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4301 
4302   // C and C++ require different kinds of checks for anonymous
4303   // structs/unions.
4304   bool Invalid = false;
4305   if (getLangOpts().CPlusPlus) {
4306     const char *PrevSpec = nullptr;
4307     unsigned DiagID;
4308     if (Record->isUnion()) {
4309       // C++ [class.union]p6:
4310       //   Anonymous unions declared in a named namespace or in the
4311       //   global namespace shall be declared static.
4312       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4313           (isa<TranslationUnitDecl>(Owner) ||
4314            (isa<NamespaceDecl>(Owner) &&
4315             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4316         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4317           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4318 
4319         // Recover by adding 'static'.
4320         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4321                                PrevSpec, DiagID, Policy);
4322       }
4323       // C++ [class.union]p6:
4324       //   A storage class is not allowed in a declaration of an
4325       //   anonymous union in a class scope.
4326       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4327                isa<RecordDecl>(Owner)) {
4328         Diag(DS.getStorageClassSpecLoc(),
4329              diag::err_anonymous_union_with_storage_spec)
4330           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4331 
4332         // Recover by removing the storage specifier.
4333         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4334                                SourceLocation(),
4335                                PrevSpec, DiagID, Context.getPrintingPolicy());
4336       }
4337     }
4338 
4339     // Ignore const/volatile/restrict qualifiers.
4340     if (DS.getTypeQualifiers()) {
4341       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4342         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4343           << Record->isUnion() << "const"
4344           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4345       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4346         Diag(DS.getVolatileSpecLoc(),
4347              diag::ext_anonymous_struct_union_qualified)
4348           << Record->isUnion() << "volatile"
4349           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4350       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4351         Diag(DS.getRestrictSpecLoc(),
4352              diag::ext_anonymous_struct_union_qualified)
4353           << Record->isUnion() << "restrict"
4354           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4355       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4356         Diag(DS.getAtomicSpecLoc(),
4357              diag::ext_anonymous_struct_union_qualified)
4358           << Record->isUnion() << "_Atomic"
4359           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4360       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4361         Diag(DS.getUnalignedSpecLoc(),
4362              diag::ext_anonymous_struct_union_qualified)
4363           << Record->isUnion() << "__unaligned"
4364           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4365 
4366       DS.ClearTypeQualifiers();
4367     }
4368 
4369     // C++ [class.union]p2:
4370     //   The member-specification of an anonymous union shall only
4371     //   define non-static data members. [Note: nested types and
4372     //   functions cannot be declared within an anonymous union. ]
4373     for (auto *Mem : Record->decls()) {
4374       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4375         // C++ [class.union]p3:
4376         //   An anonymous union shall not have private or protected
4377         //   members (clause 11).
4378         assert(FD->getAccess() != AS_none);
4379         if (FD->getAccess() != AS_public) {
4380           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4381             << Record->isUnion() << (FD->getAccess() == AS_protected);
4382           Invalid = true;
4383         }
4384 
4385         // C++ [class.union]p1
4386         //   An object of a class with a non-trivial constructor, a non-trivial
4387         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4388         //   assignment operator cannot be a member of a union, nor can an
4389         //   array of such objects.
4390         if (CheckNontrivialField(FD))
4391           Invalid = true;
4392       } else if (Mem->isImplicit()) {
4393         // Any implicit members are fine.
4394       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4395         // This is a type that showed up in an
4396         // elaborated-type-specifier inside the anonymous struct or
4397         // union, but which actually declares a type outside of the
4398         // anonymous struct or union. It's okay.
4399       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4400         if (!MemRecord->isAnonymousStructOrUnion() &&
4401             MemRecord->getDeclName()) {
4402           // Visual C++ allows type definition in anonymous struct or union.
4403           if (getLangOpts().MicrosoftExt)
4404             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4405               << Record->isUnion();
4406           else {
4407             // This is a nested type declaration.
4408             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4409               << Record->isUnion();
4410             Invalid = true;
4411           }
4412         } else {
4413           // This is an anonymous type definition within another anonymous type.
4414           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4415           // not part of standard C++.
4416           Diag(MemRecord->getLocation(),
4417                diag::ext_anonymous_record_with_anonymous_type)
4418             << Record->isUnion();
4419         }
4420       } else if (isa<AccessSpecDecl>(Mem)) {
4421         // Any access specifier is fine.
4422       } else if (isa<StaticAssertDecl>(Mem)) {
4423         // In C++1z, static_assert declarations are also fine.
4424       } else {
4425         // We have something that isn't a non-static data
4426         // member. Complain about it.
4427         unsigned DK = diag::err_anonymous_record_bad_member;
4428         if (isa<TypeDecl>(Mem))
4429           DK = diag::err_anonymous_record_with_type;
4430         else if (isa<FunctionDecl>(Mem))
4431           DK = diag::err_anonymous_record_with_function;
4432         else if (isa<VarDecl>(Mem))
4433           DK = diag::err_anonymous_record_with_static;
4434 
4435         // Visual C++ allows type definition in anonymous struct or union.
4436         if (getLangOpts().MicrosoftExt &&
4437             DK == diag::err_anonymous_record_with_type)
4438           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4439             << Record->isUnion();
4440         else {
4441           Diag(Mem->getLocation(), DK) << Record->isUnion();
4442           Invalid = true;
4443         }
4444       }
4445     }
4446 
4447     // C++11 [class.union]p8 (DR1460):
4448     //   At most one variant member of a union may have a
4449     //   brace-or-equal-initializer.
4450     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4451         Owner->isRecord())
4452       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4453                                 cast<CXXRecordDecl>(Record));
4454   }
4455 
4456   if (!Record->isUnion() && !Owner->isRecord()) {
4457     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4458       << getLangOpts().CPlusPlus;
4459     Invalid = true;
4460   }
4461 
4462   // Mock up a declarator.
4463   Declarator Dc(DS, Declarator::MemberContext);
4464   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4465   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4466 
4467   // Create a declaration for this anonymous struct/union.
4468   NamedDecl *Anon = nullptr;
4469   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4470     Anon = FieldDecl::Create(Context, OwningClass,
4471                              DS.getLocStart(),
4472                              Record->getLocation(),
4473                              /*IdentifierInfo=*/nullptr,
4474                              Context.getTypeDeclType(Record),
4475                              TInfo,
4476                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4477                              /*InitStyle=*/ICIS_NoInit);
4478     Anon->setAccess(AS);
4479     if (getLangOpts().CPlusPlus)
4480       FieldCollector->Add(cast<FieldDecl>(Anon));
4481   } else {
4482     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4483     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4484     if (SCSpec == DeclSpec::SCS_mutable) {
4485       // mutable can only appear on non-static class members, so it's always
4486       // an error here
4487       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4488       Invalid = true;
4489       SC = SC_None;
4490     }
4491 
4492     Anon = VarDecl::Create(Context, Owner,
4493                            DS.getLocStart(),
4494                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4495                            Context.getTypeDeclType(Record),
4496                            TInfo, SC);
4497 
4498     // Default-initialize the implicit variable. This initialization will be
4499     // trivial in almost all cases, except if a union member has an in-class
4500     // initializer:
4501     //   union { int n = 0; };
4502     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4503   }
4504   Anon->setImplicit();
4505 
4506   // Mark this as an anonymous struct/union type.
4507   Record->setAnonymousStructOrUnion(true);
4508 
4509   // Add the anonymous struct/union object to the current
4510   // context. We'll be referencing this object when we refer to one of
4511   // its members.
4512   Owner->addDecl(Anon);
4513 
4514   // Inject the members of the anonymous struct/union into the owning
4515   // context and into the identifier resolver chain for name lookup
4516   // purposes.
4517   SmallVector<NamedDecl*, 2> Chain;
4518   Chain.push_back(Anon);
4519 
4520   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4521     Invalid = true;
4522 
4523   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4524     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4525       Decl *ManglingContextDecl;
4526       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4527               NewVD->getDeclContext(), ManglingContextDecl)) {
4528         Context.setManglingNumber(
4529             NewVD, MCtx->getManglingNumber(
4530                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4531         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4532       }
4533     }
4534   }
4535 
4536   if (Invalid)
4537     Anon->setInvalidDecl();
4538 
4539   return Anon;
4540 }
4541 
4542 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4543 /// Microsoft C anonymous structure.
4544 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4545 /// Example:
4546 ///
4547 /// struct A { int a; };
4548 /// struct B { struct A; int b; };
4549 ///
4550 /// void foo() {
4551 ///   B var;
4552 ///   var.a = 3;
4553 /// }
4554 ///
4555 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4556                                            RecordDecl *Record) {
4557   assert(Record && "expected a record!");
4558 
4559   // Mock up a declarator.
4560   Declarator Dc(DS, Declarator::TypeNameContext);
4561   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4562   assert(TInfo && "couldn't build declarator info for anonymous struct");
4563 
4564   auto *ParentDecl = cast<RecordDecl>(CurContext);
4565   QualType RecTy = Context.getTypeDeclType(Record);
4566 
4567   // Create a declaration for this anonymous struct.
4568   NamedDecl *Anon = FieldDecl::Create(Context,
4569                              ParentDecl,
4570                              DS.getLocStart(),
4571                              DS.getLocStart(),
4572                              /*IdentifierInfo=*/nullptr,
4573                              RecTy,
4574                              TInfo,
4575                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4576                              /*InitStyle=*/ICIS_NoInit);
4577   Anon->setImplicit();
4578 
4579   // Add the anonymous struct object to the current context.
4580   CurContext->addDecl(Anon);
4581 
4582   // Inject the members of the anonymous struct into the current
4583   // context and into the identifier resolver chain for name lookup
4584   // purposes.
4585   SmallVector<NamedDecl*, 2> Chain;
4586   Chain.push_back(Anon);
4587 
4588   RecordDecl *RecordDef = Record->getDefinition();
4589   if (RequireCompleteType(Anon->getLocation(), RecTy,
4590                           diag::err_field_incomplete) ||
4591       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4592                                           AS_none, Chain)) {
4593     Anon->setInvalidDecl();
4594     ParentDecl->setInvalidDecl();
4595   }
4596 
4597   return Anon;
4598 }
4599 
4600 /// GetNameForDeclarator - Determine the full declaration name for the
4601 /// given Declarator.
4602 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4603   return GetNameFromUnqualifiedId(D.getName());
4604 }
4605 
4606 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4607 DeclarationNameInfo
4608 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4609   DeclarationNameInfo NameInfo;
4610   NameInfo.setLoc(Name.StartLocation);
4611 
4612   switch (Name.getKind()) {
4613 
4614   case UnqualifiedId::IK_ImplicitSelfParam:
4615   case UnqualifiedId::IK_Identifier:
4616     NameInfo.setName(Name.Identifier);
4617     NameInfo.setLoc(Name.StartLocation);
4618     return NameInfo;
4619 
4620   case UnqualifiedId::IK_OperatorFunctionId:
4621     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4622                                            Name.OperatorFunctionId.Operator));
4623     NameInfo.setLoc(Name.StartLocation);
4624     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4625       = Name.OperatorFunctionId.SymbolLocations[0];
4626     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4627       = Name.EndLocation.getRawEncoding();
4628     return NameInfo;
4629 
4630   case UnqualifiedId::IK_LiteralOperatorId:
4631     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4632                                                            Name.Identifier));
4633     NameInfo.setLoc(Name.StartLocation);
4634     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4635     return NameInfo;
4636 
4637   case UnqualifiedId::IK_ConversionFunctionId: {
4638     TypeSourceInfo *TInfo;
4639     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4640     if (Ty.isNull())
4641       return DeclarationNameInfo();
4642     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4643                                                Context.getCanonicalType(Ty)));
4644     NameInfo.setLoc(Name.StartLocation);
4645     NameInfo.setNamedTypeInfo(TInfo);
4646     return NameInfo;
4647   }
4648 
4649   case UnqualifiedId::IK_ConstructorName: {
4650     TypeSourceInfo *TInfo;
4651     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4652     if (Ty.isNull())
4653       return DeclarationNameInfo();
4654     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4655                                               Context.getCanonicalType(Ty)));
4656     NameInfo.setLoc(Name.StartLocation);
4657     NameInfo.setNamedTypeInfo(TInfo);
4658     return NameInfo;
4659   }
4660 
4661   case UnqualifiedId::IK_ConstructorTemplateId: {
4662     // In well-formed code, we can only have a constructor
4663     // template-id that refers to the current context, so go there
4664     // to find the actual type being constructed.
4665     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4666     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4667       return DeclarationNameInfo();
4668 
4669     // Determine the type of the class being constructed.
4670     QualType CurClassType = Context.getTypeDeclType(CurClass);
4671 
4672     // FIXME: Check two things: that the template-id names the same type as
4673     // CurClassType, and that the template-id does not occur when the name
4674     // was qualified.
4675 
4676     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4677                                     Context.getCanonicalType(CurClassType)));
4678     NameInfo.setLoc(Name.StartLocation);
4679     // FIXME: should we retrieve TypeSourceInfo?
4680     NameInfo.setNamedTypeInfo(nullptr);
4681     return NameInfo;
4682   }
4683 
4684   case UnqualifiedId::IK_DestructorName: {
4685     TypeSourceInfo *TInfo;
4686     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4687     if (Ty.isNull())
4688       return DeclarationNameInfo();
4689     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4690                                               Context.getCanonicalType(Ty)));
4691     NameInfo.setLoc(Name.StartLocation);
4692     NameInfo.setNamedTypeInfo(TInfo);
4693     return NameInfo;
4694   }
4695 
4696   case UnqualifiedId::IK_TemplateId: {
4697     TemplateName TName = Name.TemplateId->Template.get();
4698     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4699     return Context.getNameForTemplate(TName, TNameLoc);
4700   }
4701 
4702   } // switch (Name.getKind())
4703 
4704   llvm_unreachable("Unknown name kind");
4705 }
4706 
4707 static QualType getCoreType(QualType Ty) {
4708   do {
4709     if (Ty->isPointerType() || Ty->isReferenceType())
4710       Ty = Ty->getPointeeType();
4711     else if (Ty->isArrayType())
4712       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4713     else
4714       return Ty.withoutLocalFastQualifiers();
4715   } while (true);
4716 }
4717 
4718 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4719 /// and Definition have "nearly" matching parameters. This heuristic is
4720 /// used to improve diagnostics in the case where an out-of-line function
4721 /// definition doesn't match any declaration within the class or namespace.
4722 /// Also sets Params to the list of indices to the parameters that differ
4723 /// between the declaration and the definition. If hasSimilarParameters
4724 /// returns true and Params is empty, then all of the parameters match.
4725 static bool hasSimilarParameters(ASTContext &Context,
4726                                      FunctionDecl *Declaration,
4727                                      FunctionDecl *Definition,
4728                                      SmallVectorImpl<unsigned> &Params) {
4729   Params.clear();
4730   if (Declaration->param_size() != Definition->param_size())
4731     return false;
4732   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4733     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4734     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4735 
4736     // The parameter types are identical
4737     if (Context.hasSameType(DefParamTy, DeclParamTy))
4738       continue;
4739 
4740     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4741     QualType DefParamBaseTy = getCoreType(DefParamTy);
4742     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4743     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4744 
4745     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4746         (DeclTyName && DeclTyName == DefTyName))
4747       Params.push_back(Idx);
4748     else  // The two parameters aren't even close
4749       return false;
4750   }
4751 
4752   return true;
4753 }
4754 
4755 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4756 /// declarator needs to be rebuilt in the current instantiation.
4757 /// Any bits of declarator which appear before the name are valid for
4758 /// consideration here.  That's specifically the type in the decl spec
4759 /// and the base type in any member-pointer chunks.
4760 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4761                                                     DeclarationName Name) {
4762   // The types we specifically need to rebuild are:
4763   //   - typenames, typeofs, and decltypes
4764   //   - types which will become injected class names
4765   // Of course, we also need to rebuild any type referencing such a
4766   // type.  It's safest to just say "dependent", but we call out a
4767   // few cases here.
4768 
4769   DeclSpec &DS = D.getMutableDeclSpec();
4770   switch (DS.getTypeSpecType()) {
4771   case DeclSpec::TST_typename:
4772   case DeclSpec::TST_typeofType:
4773   case DeclSpec::TST_underlyingType:
4774   case DeclSpec::TST_atomic: {
4775     // Grab the type from the parser.
4776     TypeSourceInfo *TSI = nullptr;
4777     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4778     if (T.isNull() || !T->isDependentType()) break;
4779 
4780     // Make sure there's a type source info.  This isn't really much
4781     // of a waste; most dependent types should have type source info
4782     // attached already.
4783     if (!TSI)
4784       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4785 
4786     // Rebuild the type in the current instantiation.
4787     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4788     if (!TSI) return true;
4789 
4790     // Store the new type back in the decl spec.
4791     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4792     DS.UpdateTypeRep(LocType);
4793     break;
4794   }
4795 
4796   case DeclSpec::TST_decltype:
4797   case DeclSpec::TST_typeofExpr: {
4798     Expr *E = DS.getRepAsExpr();
4799     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4800     if (Result.isInvalid()) return true;
4801     DS.UpdateExprRep(Result.get());
4802     break;
4803   }
4804 
4805   default:
4806     // Nothing to do for these decl specs.
4807     break;
4808   }
4809 
4810   // It doesn't matter what order we do this in.
4811   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4812     DeclaratorChunk &Chunk = D.getTypeObject(I);
4813 
4814     // The only type information in the declarator which can come
4815     // before the declaration name is the base type of a member
4816     // pointer.
4817     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4818       continue;
4819 
4820     // Rebuild the scope specifier in-place.
4821     CXXScopeSpec &SS = Chunk.Mem.Scope();
4822     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4823       return true;
4824   }
4825 
4826   return false;
4827 }
4828 
4829 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4830   D.setFunctionDefinitionKind(FDK_Declaration);
4831   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4832 
4833   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4834       Dcl && Dcl->getDeclContext()->isFileContext())
4835     Dcl->setTopLevelDeclInObjCContainer();
4836 
4837   return Dcl;
4838 }
4839 
4840 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4841 ///   If T is the name of a class, then each of the following shall have a
4842 ///   name different from T:
4843 ///     - every static data member of class T;
4844 ///     - every member function of class T
4845 ///     - every member of class T that is itself a type;
4846 /// \returns true if the declaration name violates these rules.
4847 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4848                                    DeclarationNameInfo NameInfo) {
4849   DeclarationName Name = NameInfo.getName();
4850 
4851   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4852   while (Record && Record->isAnonymousStructOrUnion())
4853     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4854   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4855     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4856     return true;
4857   }
4858 
4859   return false;
4860 }
4861 
4862 /// \brief Diagnose a declaration whose declarator-id has the given
4863 /// nested-name-specifier.
4864 ///
4865 /// \param SS The nested-name-specifier of the declarator-id.
4866 ///
4867 /// \param DC The declaration context to which the nested-name-specifier
4868 /// resolves.
4869 ///
4870 /// \param Name The name of the entity being declared.
4871 ///
4872 /// \param Loc The location of the name of the entity being declared.
4873 ///
4874 /// \returns true if we cannot safely recover from this error, false otherwise.
4875 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4876                                         DeclarationName Name,
4877                                         SourceLocation Loc) {
4878   DeclContext *Cur = CurContext;
4879   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4880     Cur = Cur->getParent();
4881 
4882   // If the user provided a superfluous scope specifier that refers back to the
4883   // class in which the entity is already declared, diagnose and ignore it.
4884   //
4885   // class X {
4886   //   void X::f();
4887   // };
4888   //
4889   // Note, it was once ill-formed to give redundant qualification in all
4890   // contexts, but that rule was removed by DR482.
4891   if (Cur->Equals(DC)) {
4892     if (Cur->isRecord()) {
4893       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4894                                       : diag::err_member_extra_qualification)
4895         << Name << FixItHint::CreateRemoval(SS.getRange());
4896       SS.clear();
4897     } else {
4898       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4899     }
4900     return false;
4901   }
4902 
4903   // Check whether the qualifying scope encloses the scope of the original
4904   // declaration.
4905   if (!Cur->Encloses(DC)) {
4906     if (Cur->isRecord())
4907       Diag(Loc, diag::err_member_qualification)
4908         << Name << SS.getRange();
4909     else if (isa<TranslationUnitDecl>(DC))
4910       Diag(Loc, diag::err_invalid_declarator_global_scope)
4911         << Name << SS.getRange();
4912     else if (isa<FunctionDecl>(Cur))
4913       Diag(Loc, diag::err_invalid_declarator_in_function)
4914         << Name << SS.getRange();
4915     else if (isa<BlockDecl>(Cur))
4916       Diag(Loc, diag::err_invalid_declarator_in_block)
4917         << Name << SS.getRange();
4918     else
4919       Diag(Loc, diag::err_invalid_declarator_scope)
4920       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4921 
4922     return true;
4923   }
4924 
4925   if (Cur->isRecord()) {
4926     // Cannot qualify members within a class.
4927     Diag(Loc, diag::err_member_qualification)
4928       << Name << SS.getRange();
4929     SS.clear();
4930 
4931     // C++ constructors and destructors with incorrect scopes can break
4932     // our AST invariants by having the wrong underlying types. If
4933     // that's the case, then drop this declaration entirely.
4934     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4935          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4936         !Context.hasSameType(Name.getCXXNameType(),
4937                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4938       return true;
4939 
4940     return false;
4941   }
4942 
4943   // C++11 [dcl.meaning]p1:
4944   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4945   //   not begin with a decltype-specifer"
4946   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4947   while (SpecLoc.getPrefix())
4948     SpecLoc = SpecLoc.getPrefix();
4949   if (dyn_cast_or_null<DecltypeType>(
4950         SpecLoc.getNestedNameSpecifier()->getAsType()))
4951     Diag(Loc, diag::err_decltype_in_declarator)
4952       << SpecLoc.getTypeLoc().getSourceRange();
4953 
4954   return false;
4955 }
4956 
4957 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4958                                   MultiTemplateParamsArg TemplateParamLists) {
4959   // TODO: consider using NameInfo for diagnostic.
4960   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4961   DeclarationName Name = NameInfo.getName();
4962 
4963   // All of these full declarators require an identifier.  If it doesn't have
4964   // one, the ParsedFreeStandingDeclSpec action should be used.
4965   if (D.isDecompositionDeclarator()) {
4966     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
4967   } else if (!Name) {
4968     if (!D.isInvalidType())  // Reject this if we think it is valid.
4969       Diag(D.getDeclSpec().getLocStart(),
4970            diag::err_declarator_need_ident)
4971         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4972     return nullptr;
4973   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4974     return nullptr;
4975 
4976   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4977   // we find one that is.
4978   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4979          (S->getFlags() & Scope::TemplateParamScope) != 0)
4980     S = S->getParent();
4981 
4982   DeclContext *DC = CurContext;
4983   if (D.getCXXScopeSpec().isInvalid())
4984     D.setInvalidType();
4985   else if (D.getCXXScopeSpec().isSet()) {
4986     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4987                                         UPPC_DeclarationQualifier))
4988       return nullptr;
4989 
4990     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4991     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4992     if (!DC || isa<EnumDecl>(DC)) {
4993       // If we could not compute the declaration context, it's because the
4994       // declaration context is dependent but does not refer to a class,
4995       // class template, or class template partial specialization. Complain
4996       // and return early, to avoid the coming semantic disaster.
4997       Diag(D.getIdentifierLoc(),
4998            diag::err_template_qualified_declarator_no_match)
4999         << D.getCXXScopeSpec().getScopeRep()
5000         << D.getCXXScopeSpec().getRange();
5001       return nullptr;
5002     }
5003     bool IsDependentContext = DC->isDependentContext();
5004 
5005     if (!IsDependentContext &&
5006         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5007       return nullptr;
5008 
5009     // If a class is incomplete, do not parse entities inside it.
5010     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5011       Diag(D.getIdentifierLoc(),
5012            diag::err_member_def_undefined_record)
5013         << Name << DC << D.getCXXScopeSpec().getRange();
5014       return nullptr;
5015     }
5016     if (!D.getDeclSpec().isFriendSpecified()) {
5017       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5018                                       Name, D.getIdentifierLoc())) {
5019         if (DC->isRecord())
5020           return nullptr;
5021 
5022         D.setInvalidType();
5023       }
5024     }
5025 
5026     // Check whether we need to rebuild the type of the given
5027     // declaration in the current instantiation.
5028     if (EnteringContext && IsDependentContext &&
5029         TemplateParamLists.size() != 0) {
5030       ContextRAII SavedContext(*this, DC);
5031       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5032         D.setInvalidType();
5033     }
5034   }
5035 
5036   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5037   QualType R = TInfo->getType();
5038 
5039   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5040     // If this is a typedef, we'll end up spewing multiple diagnostics.
5041     // Just return early; it's safer. If this is a function, let the
5042     // "constructor cannot have a return type" diagnostic handle it.
5043     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5044       return nullptr;
5045 
5046   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5047                                       UPPC_DeclarationType))
5048     D.setInvalidType();
5049 
5050   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5051                         ForRedeclaration);
5052 
5053   // See if this is a redefinition of a variable in the same scope.
5054   if (!D.getCXXScopeSpec().isSet()) {
5055     bool IsLinkageLookup = false;
5056     bool CreateBuiltins = false;
5057 
5058     // If the declaration we're planning to build will be a function
5059     // or object with linkage, then look for another declaration with
5060     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5061     //
5062     // If the declaration we're planning to build will be declared with
5063     // external linkage in the translation unit, create any builtin with
5064     // the same name.
5065     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5066       /* Do nothing*/;
5067     else if (CurContext->isFunctionOrMethod() &&
5068              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5069               R->isFunctionType())) {
5070       IsLinkageLookup = true;
5071       CreateBuiltins =
5072           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5073     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5074                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5075       CreateBuiltins = true;
5076 
5077     if (IsLinkageLookup)
5078       Previous.clear(LookupRedeclarationWithLinkage);
5079 
5080     LookupName(Previous, S, CreateBuiltins);
5081   } else { // Something like "int foo::x;"
5082     LookupQualifiedName(Previous, DC);
5083 
5084     // C++ [dcl.meaning]p1:
5085     //   When the declarator-id is qualified, the declaration shall refer to a
5086     //  previously declared member of the class or namespace to which the
5087     //  qualifier refers (or, in the case of a namespace, of an element of the
5088     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5089     //  thereof; [...]
5090     //
5091     // Note that we already checked the context above, and that we do not have
5092     // enough information to make sure that Previous contains the declaration
5093     // we want to match. For example, given:
5094     //
5095     //   class X {
5096     //     void f();
5097     //     void f(float);
5098     //   };
5099     //
5100     //   void X::f(int) { } // ill-formed
5101     //
5102     // In this case, Previous will point to the overload set
5103     // containing the two f's declared in X, but neither of them
5104     // matches.
5105 
5106     // C++ [dcl.meaning]p1:
5107     //   [...] the member shall not merely have been introduced by a
5108     //   using-declaration in the scope of the class or namespace nominated by
5109     //   the nested-name-specifier of the declarator-id.
5110     RemoveUsingDecls(Previous);
5111   }
5112 
5113   if (Previous.isSingleResult() &&
5114       Previous.getFoundDecl()->isTemplateParameter()) {
5115     // Maybe we will complain about the shadowed template parameter.
5116     if (!D.isInvalidType())
5117       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5118                                       Previous.getFoundDecl());
5119 
5120     // Just pretend that we didn't see the previous declaration.
5121     Previous.clear();
5122   }
5123 
5124   // In C++, the previous declaration we find might be a tag type
5125   // (class or enum). In this case, the new declaration will hide the
5126   // tag type. Note that this does does not apply if we're declaring a
5127   // typedef (C++ [dcl.typedef]p4).
5128   if (Previous.isSingleTagDecl() &&
5129       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5130     Previous.clear();
5131 
5132   // Check that there are no default arguments other than in the parameters
5133   // of a function declaration (C++ only).
5134   if (getLangOpts().CPlusPlus)
5135     CheckExtraCXXDefaultArguments(D);
5136 
5137   if (D.getDeclSpec().isConceptSpecified()) {
5138     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5139     // applied only to the definition of a function template or variable
5140     // template, declared in namespace scope
5141     if (!TemplateParamLists.size()) {
5142       Diag(D.getDeclSpec().getConceptSpecLoc(),
5143            diag:: err_concept_wrong_decl_kind);
5144       return nullptr;
5145     }
5146 
5147     if (!DC->getRedeclContext()->isFileContext()) {
5148       Diag(D.getIdentifierLoc(),
5149            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5150       return nullptr;
5151     }
5152   }
5153 
5154   NamedDecl *New;
5155 
5156   bool AddToScope = true;
5157   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5158     if (TemplateParamLists.size()) {
5159       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5160       return nullptr;
5161     }
5162 
5163     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5164   } else if (R->isFunctionType()) {
5165     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5166                                   TemplateParamLists,
5167                                   AddToScope);
5168   } else {
5169     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5170                                   AddToScope);
5171   }
5172 
5173   if (!New)
5174     return nullptr;
5175 
5176   // If this has an identifier and is not a function template specialization,
5177   // add it to the scope stack.
5178   if (New->getDeclName() && AddToScope) {
5179     // Only make a locally-scoped extern declaration visible if it is the first
5180     // declaration of this entity. Qualified lookup for such an entity should
5181     // only find this declaration if there is no visible declaration of it.
5182     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5183     PushOnScopeChains(New, S, AddToContext);
5184     if (!AddToContext)
5185       CurContext->addHiddenDecl(New);
5186   }
5187 
5188   if (isInOpenMPDeclareTargetContext())
5189     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5190 
5191   return New;
5192 }
5193 
5194 /// Helper method to turn variable array types into constant array
5195 /// types in certain situations which would otherwise be errors (for
5196 /// GCC compatibility).
5197 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5198                                                     ASTContext &Context,
5199                                                     bool &SizeIsNegative,
5200                                                     llvm::APSInt &Oversized) {
5201   // This method tries to turn a variable array into a constant
5202   // array even when the size isn't an ICE.  This is necessary
5203   // for compatibility with code that depends on gcc's buggy
5204   // constant expression folding, like struct {char x[(int)(char*)2];}
5205   SizeIsNegative = false;
5206   Oversized = 0;
5207 
5208   if (T->isDependentType())
5209     return QualType();
5210 
5211   QualifierCollector Qs;
5212   const Type *Ty = Qs.strip(T);
5213 
5214   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5215     QualType Pointee = PTy->getPointeeType();
5216     QualType FixedType =
5217         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5218                                             Oversized);
5219     if (FixedType.isNull()) return FixedType;
5220     FixedType = Context.getPointerType(FixedType);
5221     return Qs.apply(Context, FixedType);
5222   }
5223   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5224     QualType Inner = PTy->getInnerType();
5225     QualType FixedType =
5226         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5227                                             Oversized);
5228     if (FixedType.isNull()) return FixedType;
5229     FixedType = Context.getParenType(FixedType);
5230     return Qs.apply(Context, FixedType);
5231   }
5232 
5233   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5234   if (!VLATy)
5235     return QualType();
5236   // FIXME: We should probably handle this case
5237   if (VLATy->getElementType()->isVariablyModifiedType())
5238     return QualType();
5239 
5240   llvm::APSInt Res;
5241   if (!VLATy->getSizeExpr() ||
5242       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5243     return QualType();
5244 
5245   // Check whether the array size is negative.
5246   if (Res.isSigned() && Res.isNegative()) {
5247     SizeIsNegative = true;
5248     return QualType();
5249   }
5250 
5251   // Check whether the array is too large to be addressed.
5252   unsigned ActiveSizeBits
5253     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5254                                               Res);
5255   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5256     Oversized = Res;
5257     return QualType();
5258   }
5259 
5260   return Context.getConstantArrayType(VLATy->getElementType(),
5261                                       Res, ArrayType::Normal, 0);
5262 }
5263 
5264 static void
5265 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5266   SrcTL = SrcTL.getUnqualifiedLoc();
5267   DstTL = DstTL.getUnqualifiedLoc();
5268   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5269     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5270     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5271                                       DstPTL.getPointeeLoc());
5272     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5273     return;
5274   }
5275   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5276     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5277     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5278                                       DstPTL.getInnerLoc());
5279     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5280     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5281     return;
5282   }
5283   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5284   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5285   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5286   TypeLoc DstElemTL = DstATL.getElementLoc();
5287   DstElemTL.initializeFullCopy(SrcElemTL);
5288   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5289   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5290   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5291 }
5292 
5293 /// Helper method to turn variable array types into constant array
5294 /// types in certain situations which would otherwise be errors (for
5295 /// GCC compatibility).
5296 static TypeSourceInfo*
5297 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5298                                               ASTContext &Context,
5299                                               bool &SizeIsNegative,
5300                                               llvm::APSInt &Oversized) {
5301   QualType FixedTy
5302     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5303                                           SizeIsNegative, Oversized);
5304   if (FixedTy.isNull())
5305     return nullptr;
5306   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5307   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5308                                     FixedTInfo->getTypeLoc());
5309   return FixedTInfo;
5310 }
5311 
5312 /// \brief Register the given locally-scoped extern "C" declaration so
5313 /// that it can be found later for redeclarations. We include any extern "C"
5314 /// declaration that is not visible in the translation unit here, not just
5315 /// function-scope declarations.
5316 void
5317 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5318   if (!getLangOpts().CPlusPlus &&
5319       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5320     // Don't need to track declarations in the TU in C.
5321     return;
5322 
5323   // Note that we have a locally-scoped external with this name.
5324   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5325 }
5326 
5327 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5328   // FIXME: We can have multiple results via __attribute__((overloadable)).
5329   auto Result = Context.getExternCContextDecl()->lookup(Name);
5330   return Result.empty() ? nullptr : *Result.begin();
5331 }
5332 
5333 /// \brief Diagnose function specifiers on a declaration of an identifier that
5334 /// does not identify a function.
5335 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5336   // FIXME: We should probably indicate the identifier in question to avoid
5337   // confusion for constructs like "virtual int a(), b;"
5338   if (DS.isVirtualSpecified())
5339     Diag(DS.getVirtualSpecLoc(),
5340          diag::err_virtual_non_function);
5341 
5342   if (DS.isExplicitSpecified())
5343     Diag(DS.getExplicitSpecLoc(),
5344          diag::err_explicit_non_function);
5345 
5346   if (DS.isNoreturnSpecified())
5347     Diag(DS.getNoreturnSpecLoc(),
5348          diag::err_noreturn_non_function);
5349 }
5350 
5351 NamedDecl*
5352 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5353                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5354   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5355   if (D.getCXXScopeSpec().isSet()) {
5356     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5357       << D.getCXXScopeSpec().getRange();
5358     D.setInvalidType();
5359     // Pretend we didn't see the scope specifier.
5360     DC = CurContext;
5361     Previous.clear();
5362   }
5363 
5364   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5365 
5366   if (D.getDeclSpec().isInlineSpecified())
5367     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5368         << getLangOpts().CPlusPlus1z;
5369   if (D.getDeclSpec().isConstexprSpecified())
5370     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5371       << 1;
5372   if (D.getDeclSpec().isConceptSpecified())
5373     Diag(D.getDeclSpec().getConceptSpecLoc(),
5374          diag::err_concept_wrong_decl_kind);
5375 
5376   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5377     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5378       << D.getName().getSourceRange();
5379     return nullptr;
5380   }
5381 
5382   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5383   if (!NewTD) return nullptr;
5384 
5385   // Handle attributes prior to checking for duplicates in MergeVarDecl
5386   ProcessDeclAttributes(S, NewTD, D);
5387 
5388   CheckTypedefForVariablyModifiedType(S, NewTD);
5389 
5390   bool Redeclaration = D.isRedeclaration();
5391   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5392   D.setRedeclaration(Redeclaration);
5393   return ND;
5394 }
5395 
5396 void
5397 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5398   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5399   // then it shall have block scope.
5400   // Note that variably modified types must be fixed before merging the decl so
5401   // that redeclarations will match.
5402   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5403   QualType T = TInfo->getType();
5404   if (T->isVariablyModifiedType()) {
5405     getCurFunction()->setHasBranchProtectedScope();
5406 
5407     if (S->getFnParent() == nullptr) {
5408       bool SizeIsNegative;
5409       llvm::APSInt Oversized;
5410       TypeSourceInfo *FixedTInfo =
5411         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5412                                                       SizeIsNegative,
5413                                                       Oversized);
5414       if (FixedTInfo) {
5415         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5416         NewTD->setTypeSourceInfo(FixedTInfo);
5417       } else {
5418         if (SizeIsNegative)
5419           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5420         else if (T->isVariableArrayType())
5421           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5422         else if (Oversized.getBoolValue())
5423           Diag(NewTD->getLocation(), diag::err_array_too_large)
5424             << Oversized.toString(10);
5425         else
5426           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5427         NewTD->setInvalidDecl();
5428       }
5429     }
5430   }
5431 }
5432 
5433 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5434 /// declares a typedef-name, either using the 'typedef' type specifier or via
5435 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5436 NamedDecl*
5437 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5438                            LookupResult &Previous, bool &Redeclaration) {
5439   // Merge the decl with the existing one if appropriate. If the decl is
5440   // in an outer scope, it isn't the same thing.
5441   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5442                        /*AllowInlineNamespace*/false);
5443   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5444   if (!Previous.empty()) {
5445     Redeclaration = true;
5446     MergeTypedefNameDecl(S, NewTD, Previous);
5447   }
5448 
5449   // If this is the C FILE type, notify the AST context.
5450   if (IdentifierInfo *II = NewTD->getIdentifier())
5451     if (!NewTD->isInvalidDecl() &&
5452         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5453       if (II->isStr("FILE"))
5454         Context.setFILEDecl(NewTD);
5455       else if (II->isStr("jmp_buf"))
5456         Context.setjmp_bufDecl(NewTD);
5457       else if (II->isStr("sigjmp_buf"))
5458         Context.setsigjmp_bufDecl(NewTD);
5459       else if (II->isStr("ucontext_t"))
5460         Context.setucontext_tDecl(NewTD);
5461     }
5462 
5463   return NewTD;
5464 }
5465 
5466 /// \brief Determines whether the given declaration is an out-of-scope
5467 /// previous declaration.
5468 ///
5469 /// This routine should be invoked when name lookup has found a
5470 /// previous declaration (PrevDecl) that is not in the scope where a
5471 /// new declaration by the same name is being introduced. If the new
5472 /// declaration occurs in a local scope, previous declarations with
5473 /// linkage may still be considered previous declarations (C99
5474 /// 6.2.2p4-5, C++ [basic.link]p6).
5475 ///
5476 /// \param PrevDecl the previous declaration found by name
5477 /// lookup
5478 ///
5479 /// \param DC the context in which the new declaration is being
5480 /// declared.
5481 ///
5482 /// \returns true if PrevDecl is an out-of-scope previous declaration
5483 /// for a new delcaration with the same name.
5484 static bool
5485 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5486                                 ASTContext &Context) {
5487   if (!PrevDecl)
5488     return false;
5489 
5490   if (!PrevDecl->hasLinkage())
5491     return false;
5492 
5493   if (Context.getLangOpts().CPlusPlus) {
5494     // C++ [basic.link]p6:
5495     //   If there is a visible declaration of an entity with linkage
5496     //   having the same name and type, ignoring entities declared
5497     //   outside the innermost enclosing namespace scope, the block
5498     //   scope declaration declares that same entity and receives the
5499     //   linkage of the previous declaration.
5500     DeclContext *OuterContext = DC->getRedeclContext();
5501     if (!OuterContext->isFunctionOrMethod())
5502       // This rule only applies to block-scope declarations.
5503       return false;
5504 
5505     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5506     if (PrevOuterContext->isRecord())
5507       // We found a member function: ignore it.
5508       return false;
5509 
5510     // Find the innermost enclosing namespace for the new and
5511     // previous declarations.
5512     OuterContext = OuterContext->getEnclosingNamespaceContext();
5513     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5514 
5515     // The previous declaration is in a different namespace, so it
5516     // isn't the same function.
5517     if (!OuterContext->Equals(PrevOuterContext))
5518       return false;
5519   }
5520 
5521   return true;
5522 }
5523 
5524 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5525   CXXScopeSpec &SS = D.getCXXScopeSpec();
5526   if (!SS.isSet()) return;
5527   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5528 }
5529 
5530 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5531   QualType type = decl->getType();
5532   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5533   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5534     // Various kinds of declaration aren't allowed to be __autoreleasing.
5535     unsigned kind = -1U;
5536     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5537       if (var->hasAttr<BlocksAttr>())
5538         kind = 0; // __block
5539       else if (!var->hasLocalStorage())
5540         kind = 1; // global
5541     } else if (isa<ObjCIvarDecl>(decl)) {
5542       kind = 3; // ivar
5543     } else if (isa<FieldDecl>(decl)) {
5544       kind = 2; // field
5545     }
5546 
5547     if (kind != -1U) {
5548       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5549         << kind;
5550     }
5551   } else if (lifetime == Qualifiers::OCL_None) {
5552     // Try to infer lifetime.
5553     if (!type->isObjCLifetimeType())
5554       return false;
5555 
5556     lifetime = type->getObjCARCImplicitLifetime();
5557     type = Context.getLifetimeQualifiedType(type, lifetime);
5558     decl->setType(type);
5559   }
5560 
5561   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5562     // Thread-local variables cannot have lifetime.
5563     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5564         var->getTLSKind()) {
5565       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5566         << var->getType();
5567       return true;
5568     }
5569   }
5570 
5571   return false;
5572 }
5573 
5574 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5575   // Ensure that an auto decl is deduced otherwise the checks below might cache
5576   // the wrong linkage.
5577   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5578 
5579   // 'weak' only applies to declarations with external linkage.
5580   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5581     if (!ND.isExternallyVisible()) {
5582       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5583       ND.dropAttr<WeakAttr>();
5584     }
5585   }
5586   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5587     if (ND.isExternallyVisible()) {
5588       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5589       ND.dropAttr<WeakRefAttr>();
5590       ND.dropAttr<AliasAttr>();
5591     }
5592   }
5593 
5594   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5595     if (VD->hasInit()) {
5596       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5597         assert(VD->isThisDeclarationADefinition() &&
5598                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5599         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5600         VD->dropAttr<AliasAttr>();
5601       }
5602     }
5603   }
5604 
5605   // 'selectany' only applies to externally visible variable declarations.
5606   // It does not apply to functions.
5607   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5608     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5609       S.Diag(Attr->getLocation(),
5610              diag::err_attribute_selectany_non_extern_data);
5611       ND.dropAttr<SelectAnyAttr>();
5612     }
5613   }
5614 
5615   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5616     // dll attributes require external linkage. Static locals may have external
5617     // linkage but still cannot be explicitly imported or exported.
5618     auto *VD = dyn_cast<VarDecl>(&ND);
5619     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5620       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5621         << &ND << Attr;
5622       ND.setInvalidDecl();
5623     }
5624   }
5625 
5626   // Virtual functions cannot be marked as 'notail'.
5627   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5628     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5629       if (MD->isVirtual()) {
5630         S.Diag(ND.getLocation(),
5631                diag::err_invalid_attribute_on_virtual_function)
5632             << Attr;
5633         ND.dropAttr<NotTailCalledAttr>();
5634       }
5635 }
5636 
5637 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5638                                            NamedDecl *NewDecl,
5639                                            bool IsSpecialization,
5640                                            bool IsDefinition) {
5641   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5642     OldDecl = OldTD->getTemplatedDecl();
5643     if (!IsSpecialization)
5644       IsDefinition = false;
5645   }
5646   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5647     NewDecl = NewTD->getTemplatedDecl();
5648 
5649   if (!OldDecl || !NewDecl)
5650     return;
5651 
5652   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5653   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5654   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5655   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5656 
5657   // dllimport and dllexport are inheritable attributes so we have to exclude
5658   // inherited attribute instances.
5659   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5660                     (NewExportAttr && !NewExportAttr->isInherited());
5661 
5662   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5663   // the only exception being explicit specializations.
5664   // Implicitly generated declarations are also excluded for now because there
5665   // is no other way to switch these to use dllimport or dllexport.
5666   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5667 
5668   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5669     // Allow with a warning for free functions and global variables.
5670     bool JustWarn = false;
5671     if (!OldDecl->isCXXClassMember()) {
5672       auto *VD = dyn_cast<VarDecl>(OldDecl);
5673       if (VD && !VD->getDescribedVarTemplate())
5674         JustWarn = true;
5675       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5676       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5677         JustWarn = true;
5678     }
5679 
5680     // We cannot change a declaration that's been used because IR has already
5681     // been emitted. Dllimported functions will still work though (modulo
5682     // address equality) as they can use the thunk.
5683     if (OldDecl->isUsed())
5684       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5685         JustWarn = false;
5686 
5687     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5688                                : diag::err_attribute_dll_redeclaration;
5689     S.Diag(NewDecl->getLocation(), DiagID)
5690         << NewDecl
5691         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5692     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5693     if (!JustWarn) {
5694       NewDecl->setInvalidDecl();
5695       return;
5696     }
5697   }
5698 
5699   // A redeclaration is not allowed to drop a dllimport attribute, the only
5700   // exceptions being inline function definitions, local extern declarations,
5701   // qualified friend declarations or special MSVC extension: in the last case,
5702   // the declaration is treated as if it were marked dllexport.
5703   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5704   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5705   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5706     // Ignore static data because out-of-line definitions are diagnosed
5707     // separately.
5708     IsStaticDataMember = VD->isStaticDataMember();
5709     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5710                    VarDecl::DeclarationOnly;
5711   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5712     IsInline = FD->isInlined();
5713     IsQualifiedFriend = FD->getQualifier() &&
5714                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5715   }
5716 
5717   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5718       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5719     if (IsMicrosoft && IsDefinition) {
5720       S.Diag(NewDecl->getLocation(),
5721              diag::warn_redeclaration_without_import_attribute)
5722           << NewDecl;
5723       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5724       NewDecl->dropAttr<DLLImportAttr>();
5725       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5726           NewImportAttr->getRange(), S.Context,
5727           NewImportAttr->getSpellingListIndex()));
5728     } else {
5729       S.Diag(NewDecl->getLocation(),
5730              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5731           << NewDecl << OldImportAttr;
5732       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5733       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5734       OldDecl->dropAttr<DLLImportAttr>();
5735       NewDecl->dropAttr<DLLImportAttr>();
5736     }
5737   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5738     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5739     OldDecl->dropAttr<DLLImportAttr>();
5740     NewDecl->dropAttr<DLLImportAttr>();
5741     S.Diag(NewDecl->getLocation(),
5742            diag::warn_dllimport_dropped_from_inline_function)
5743         << NewDecl << OldImportAttr;
5744   }
5745 }
5746 
5747 /// Given that we are within the definition of the given function,
5748 /// will that definition behave like C99's 'inline', where the
5749 /// definition is discarded except for optimization purposes?
5750 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5751   // Try to avoid calling GetGVALinkageForFunction.
5752 
5753   // All cases of this require the 'inline' keyword.
5754   if (!FD->isInlined()) return false;
5755 
5756   // This is only possible in C++ with the gnu_inline attribute.
5757   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5758     return false;
5759 
5760   // Okay, go ahead and call the relatively-more-expensive function.
5761 
5762 #ifndef NDEBUG
5763   // AST quite reasonably asserts that it's working on a function
5764   // definition.  We don't really have a way to tell it that we're
5765   // currently defining the function, so just lie to it in +Asserts
5766   // builds.  This is an awful hack.
5767   FD->setLazyBody(1);
5768 #endif
5769 
5770   bool isC99Inline =
5771       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5772 
5773 #ifndef NDEBUG
5774   FD->setLazyBody(0);
5775 #endif
5776 
5777   return isC99Inline;
5778 }
5779 
5780 /// Determine whether a variable is extern "C" prior to attaching
5781 /// an initializer. We can't just call isExternC() here, because that
5782 /// will also compute and cache whether the declaration is externally
5783 /// visible, which might change when we attach the initializer.
5784 ///
5785 /// This can only be used if the declaration is known to not be a
5786 /// redeclaration of an internal linkage declaration.
5787 ///
5788 /// For instance:
5789 ///
5790 ///   auto x = []{};
5791 ///
5792 /// Attaching the initializer here makes this declaration not externally
5793 /// visible, because its type has internal linkage.
5794 ///
5795 /// FIXME: This is a hack.
5796 template<typename T>
5797 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5798   if (S.getLangOpts().CPlusPlus) {
5799     // In C++, the overloadable attribute negates the effects of extern "C".
5800     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5801       return false;
5802 
5803     // So do CUDA's host/device attributes.
5804     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5805                                  D->template hasAttr<CUDAHostAttr>()))
5806       return false;
5807   }
5808   return D->isExternC();
5809 }
5810 
5811 static bool shouldConsiderLinkage(const VarDecl *VD) {
5812   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5813   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5814     return VD->hasExternalStorage();
5815   if (DC->isFileContext())
5816     return true;
5817   if (DC->isRecord())
5818     return false;
5819   llvm_unreachable("Unexpected context");
5820 }
5821 
5822 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5823   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5824   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5825       isa<OMPDeclareReductionDecl>(DC))
5826     return true;
5827   if (DC->isRecord())
5828     return false;
5829   llvm_unreachable("Unexpected context");
5830 }
5831 
5832 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5833                           AttributeList::Kind Kind) {
5834   for (const AttributeList *L = AttrList; L; L = L->getNext())
5835     if (L->getKind() == Kind)
5836       return true;
5837   return false;
5838 }
5839 
5840 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5841                           AttributeList::Kind Kind) {
5842   // Check decl attributes on the DeclSpec.
5843   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5844     return true;
5845 
5846   // Walk the declarator structure, checking decl attributes that were in a type
5847   // position to the decl itself.
5848   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5849     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5850       return true;
5851   }
5852 
5853   // Finally, check attributes on the decl itself.
5854   return hasParsedAttr(S, PD.getAttributes(), Kind);
5855 }
5856 
5857 /// Adjust the \c DeclContext for a function or variable that might be a
5858 /// function-local external declaration.
5859 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5860   if (!DC->isFunctionOrMethod())
5861     return false;
5862 
5863   // If this is a local extern function or variable declared within a function
5864   // template, don't add it into the enclosing namespace scope until it is
5865   // instantiated; it might have a dependent type right now.
5866   if (DC->isDependentContext())
5867     return true;
5868 
5869   // C++11 [basic.link]p7:
5870   //   When a block scope declaration of an entity with linkage is not found to
5871   //   refer to some other declaration, then that entity is a member of the
5872   //   innermost enclosing namespace.
5873   //
5874   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5875   // semantically-enclosing namespace, not a lexically-enclosing one.
5876   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5877     DC = DC->getParent();
5878   return true;
5879 }
5880 
5881 /// \brief Returns true if given declaration has external C language linkage.
5882 static bool isDeclExternC(const Decl *D) {
5883   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5884     return FD->isExternC();
5885   if (const auto *VD = dyn_cast<VarDecl>(D))
5886     return VD->isExternC();
5887 
5888   llvm_unreachable("Unknown type of decl!");
5889 }
5890 
5891 NamedDecl *Sema::ActOnVariableDeclarator(
5892     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5893     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5894     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5895   QualType R = TInfo->getType();
5896   DeclarationName Name = GetNameForDeclarator(D).getName();
5897 
5898   IdentifierInfo *II = Name.getAsIdentifierInfo();
5899 
5900   if (D.isDecompositionDeclarator()) {
5901     AddToScope = false;
5902     // Take the name of the first declarator as our name for diagnostic
5903     // purposes.
5904     auto &Decomp = D.getDecompositionDeclarator();
5905     if (!Decomp.bindings().empty()) {
5906       II = Decomp.bindings()[0].Name;
5907       Name = II;
5908     }
5909   } else if (!II) {
5910     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5911       << Name;
5912     return nullptr;
5913   }
5914 
5915   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5916   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5917   // argument.
5918   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5919     Diag(D.getIdentifierLoc(),
5920          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5921         << R;
5922     D.setInvalidType();
5923     return nullptr;
5924   }
5925 
5926   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5927   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5928 
5929   // dllimport globals without explicit storage class are treated as extern. We
5930   // have to change the storage class this early to get the right DeclContext.
5931   if (SC == SC_None && !DC->isRecord() &&
5932       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5933       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5934     SC = SC_Extern;
5935 
5936   DeclContext *OriginalDC = DC;
5937   bool IsLocalExternDecl = SC == SC_Extern &&
5938                            adjustContextForLocalExternDecl(DC);
5939 
5940   if (getLangOpts().OpenCL) {
5941     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5942     QualType NR = R;
5943     while (NR->isPointerType()) {
5944       if (NR->isFunctionPointerType()) {
5945         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5946         D.setInvalidType();
5947         break;
5948       }
5949       NR = NR->getPointeeType();
5950     }
5951 
5952     if (!getOpenCLOptions().cl_khr_fp16) {
5953       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5954       // half array type (unless the cl_khr_fp16 extension is enabled).
5955       if (Context.getBaseElementType(R)->isHalfType()) {
5956         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5957         D.setInvalidType();
5958       }
5959     }
5960   }
5961 
5962   if (SCSpec == DeclSpec::SCS_mutable) {
5963     // mutable can only appear on non-static class members, so it's always
5964     // an error here
5965     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5966     D.setInvalidType();
5967     SC = SC_None;
5968   }
5969 
5970   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5971       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5972                               D.getDeclSpec().getStorageClassSpecLoc())) {
5973     // In C++11, the 'register' storage class specifier is deprecated.
5974     // Suppress the warning in system macros, it's used in macros in some
5975     // popular C system headers, such as in glibc's htonl() macro.
5976     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5977          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5978                                    : diag::warn_deprecated_register)
5979       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5980   }
5981 
5982   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5983 
5984   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5985     // C99 6.9p2: The storage-class specifiers auto and register shall not
5986     // appear in the declaration specifiers in an external declaration.
5987     // Global Register+Asm is a GNU extension we support.
5988     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5989       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5990       D.setInvalidType();
5991     }
5992   }
5993 
5994   if (getLangOpts().OpenCL) {
5995     // OpenCL v1.2 s6.9.b p4:
5996     // The sampler type cannot be used with the __local and __global address
5997     // space qualifiers.
5998     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5999       R.getAddressSpace() == LangAS::opencl_global)) {
6000       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6001     }
6002 
6003     // OpenCL 1.2 spec, p6.9 r:
6004     // The event type cannot be used to declare a program scope variable.
6005     // The event type cannot be used with the __local, __constant and __global
6006     // address space qualifiers.
6007     if (R->isEventT()) {
6008       if (S->getParent() == nullptr) {
6009         Diag(D.getLocStart(), diag::err_event_t_global_var);
6010         D.setInvalidType();
6011       }
6012 
6013       if (R.getAddressSpace()) {
6014         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6015         D.setInvalidType();
6016       }
6017     }
6018   }
6019 
6020   bool IsExplicitSpecialization = false;
6021   bool IsVariableTemplateSpecialization = false;
6022   bool IsPartialSpecialization = false;
6023   bool IsVariableTemplate = false;
6024   VarDecl *NewVD = nullptr;
6025   VarTemplateDecl *NewTemplate = nullptr;
6026   TemplateParameterList *TemplateParams = nullptr;
6027   if (!getLangOpts().CPlusPlus) {
6028     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6029                             D.getIdentifierLoc(), II,
6030                             R, TInfo, SC);
6031 
6032     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6033       ParsingInitForAutoVars.insert(NewVD);
6034 
6035     if (D.isInvalidType())
6036       NewVD->setInvalidDecl();
6037   } else {
6038     bool Invalid = false;
6039 
6040     if (DC->isRecord() && !CurContext->isRecord()) {
6041       // This is an out-of-line definition of a static data member.
6042       switch (SC) {
6043       case SC_None:
6044         break;
6045       case SC_Static:
6046         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6047              diag::err_static_out_of_line)
6048           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6049         break;
6050       case SC_Auto:
6051       case SC_Register:
6052       case SC_Extern:
6053         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6054         // to names of variables declared in a block or to function parameters.
6055         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6056         // of class members
6057 
6058         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6059              diag::err_storage_class_for_static_member)
6060           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6061         break;
6062       case SC_PrivateExtern:
6063         llvm_unreachable("C storage class in c++!");
6064       }
6065     }
6066 
6067     if (SC == SC_Static && CurContext->isRecord()) {
6068       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6069         if (RD->isLocalClass())
6070           Diag(D.getIdentifierLoc(),
6071                diag::err_static_data_member_not_allowed_in_local_class)
6072             << Name << RD->getDeclName();
6073 
6074         // C++98 [class.union]p1: If a union contains a static data member,
6075         // the program is ill-formed. C++11 drops this restriction.
6076         if (RD->isUnion())
6077           Diag(D.getIdentifierLoc(),
6078                getLangOpts().CPlusPlus11
6079                  ? diag::warn_cxx98_compat_static_data_member_in_union
6080                  : diag::ext_static_data_member_in_union) << Name;
6081         // We conservatively disallow static data members in anonymous structs.
6082         else if (!RD->getDeclName())
6083           Diag(D.getIdentifierLoc(),
6084                diag::err_static_data_member_not_allowed_in_anon_struct)
6085             << Name << RD->isUnion();
6086       }
6087     }
6088 
6089     // Match up the template parameter lists with the scope specifier, then
6090     // determine whether we have a template or a template specialization.
6091     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6092         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6093         D.getCXXScopeSpec(),
6094         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6095             ? D.getName().TemplateId
6096             : nullptr,
6097         TemplateParamLists,
6098         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6099 
6100     if (TemplateParams) {
6101       if (!TemplateParams->size() &&
6102           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6103         // There is an extraneous 'template<>' for this variable. Complain
6104         // about it, but allow the declaration of the variable.
6105         Diag(TemplateParams->getTemplateLoc(),
6106              diag::err_template_variable_noparams)
6107           << II
6108           << SourceRange(TemplateParams->getTemplateLoc(),
6109                          TemplateParams->getRAngleLoc());
6110         TemplateParams = nullptr;
6111       } else {
6112         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6113           // This is an explicit specialization or a partial specialization.
6114           // FIXME: Check that we can declare a specialization here.
6115           IsVariableTemplateSpecialization = true;
6116           IsPartialSpecialization = TemplateParams->size() > 0;
6117         } else { // if (TemplateParams->size() > 0)
6118           // This is a template declaration.
6119           IsVariableTemplate = true;
6120 
6121           // Check that we can declare a template here.
6122           if (CheckTemplateDeclScope(S, TemplateParams))
6123             return nullptr;
6124 
6125           // Only C++1y supports variable templates (N3651).
6126           Diag(D.getIdentifierLoc(),
6127                getLangOpts().CPlusPlus14
6128                    ? diag::warn_cxx11_compat_variable_template
6129                    : diag::ext_variable_template);
6130         }
6131       }
6132     } else {
6133       assert(
6134           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6135           "should have a 'template<>' for this decl");
6136     }
6137 
6138     if (IsVariableTemplateSpecialization) {
6139       SourceLocation TemplateKWLoc =
6140           TemplateParamLists.size() > 0
6141               ? TemplateParamLists[0]->getTemplateLoc()
6142               : SourceLocation();
6143       DeclResult Res = ActOnVarTemplateSpecialization(
6144           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6145           IsPartialSpecialization);
6146       if (Res.isInvalid())
6147         return nullptr;
6148       NewVD = cast<VarDecl>(Res.get());
6149       AddToScope = false;
6150     } else if (D.isDecompositionDeclarator()) {
6151       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6152                                         D.getIdentifierLoc(), R, TInfo, SC,
6153                                         Bindings);
6154     } else
6155       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6156                               D.getIdentifierLoc(), II, R, TInfo, SC);
6157 
6158     // If this is supposed to be a variable template, create it as such.
6159     if (IsVariableTemplate) {
6160       NewTemplate =
6161           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6162                                   TemplateParams, NewVD);
6163       NewVD->setDescribedVarTemplate(NewTemplate);
6164     }
6165 
6166     // If this decl has an auto type in need of deduction, make a note of the
6167     // Decl so we can diagnose uses of it in its own initializer.
6168     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6169       ParsingInitForAutoVars.insert(NewVD);
6170 
6171     if (D.isInvalidType() || Invalid) {
6172       NewVD->setInvalidDecl();
6173       if (NewTemplate)
6174         NewTemplate->setInvalidDecl();
6175     }
6176 
6177     SetNestedNameSpecifier(NewVD, D);
6178 
6179     // If we have any template parameter lists that don't directly belong to
6180     // the variable (matching the scope specifier), store them.
6181     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6182     if (TemplateParamLists.size() > VDTemplateParamLists)
6183       NewVD->setTemplateParameterListsInfo(
6184           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6185 
6186     if (D.getDeclSpec().isConstexprSpecified()) {
6187       NewVD->setConstexpr(true);
6188       // C++1z [dcl.spec.constexpr]p1:
6189       //   A static data member declared with the constexpr specifier is
6190       //   implicitly an inline variable.
6191       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6192         NewVD->setImplicitlyInline();
6193     }
6194 
6195     if (D.getDeclSpec().isConceptSpecified()) {
6196       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6197         VTD->setConcept();
6198 
6199       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6200       // be declared with the thread_local, inline, friend, or constexpr
6201       // specifiers, [...]
6202       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6203         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6204              diag::err_concept_decl_invalid_specifiers)
6205             << 0 << 0;
6206         NewVD->setInvalidDecl(true);
6207       }
6208 
6209       if (D.getDeclSpec().isConstexprSpecified()) {
6210         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6211              diag::err_concept_decl_invalid_specifiers)
6212             << 0 << 3;
6213         NewVD->setInvalidDecl(true);
6214       }
6215 
6216       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6217       // applied only to the definition of a function template or variable
6218       // template, declared in namespace scope.
6219       if (IsVariableTemplateSpecialization) {
6220         Diag(D.getDeclSpec().getConceptSpecLoc(),
6221              diag::err_concept_specified_specialization)
6222             << (IsPartialSpecialization ? 2 : 1);
6223       }
6224 
6225       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6226       // following restrictions:
6227       // - The declared type shall have the type bool.
6228       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6229           !NewVD->isInvalidDecl()) {
6230         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6231         NewVD->setInvalidDecl(true);
6232       }
6233     }
6234   }
6235 
6236   if (D.getDeclSpec().isInlineSpecified()) {
6237     if (!getLangOpts().CPlusPlus) {
6238       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6239           << 0;
6240     } else if (CurContext->isFunctionOrMethod()) {
6241       // 'inline' is not allowed on block scope variable declaration.
6242       Diag(D.getDeclSpec().getInlineSpecLoc(),
6243            diag::err_inline_declaration_block_scope) << Name
6244         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6245     } else {
6246       Diag(D.getDeclSpec().getInlineSpecLoc(),
6247            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6248                                      : diag::ext_inline_variable);
6249       NewVD->setInlineSpecified();
6250     }
6251   }
6252 
6253   // Set the lexical context. If the declarator has a C++ scope specifier, the
6254   // lexical context will be different from the semantic context.
6255   NewVD->setLexicalDeclContext(CurContext);
6256   if (NewTemplate)
6257     NewTemplate->setLexicalDeclContext(CurContext);
6258 
6259   if (IsLocalExternDecl) {
6260     if (D.isDecompositionDeclarator())
6261       for (auto *B : Bindings)
6262         B->setLocalExternDecl();
6263     else
6264       NewVD->setLocalExternDecl();
6265   }
6266 
6267   bool EmitTLSUnsupportedError = false;
6268   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6269     // C++11 [dcl.stc]p4:
6270     //   When thread_local is applied to a variable of block scope the
6271     //   storage-class-specifier static is implied if it does not appear
6272     //   explicitly.
6273     // Core issue: 'static' is not implied if the variable is declared
6274     //   'extern'.
6275     if (NewVD->hasLocalStorage() &&
6276         (SCSpec != DeclSpec::SCS_unspecified ||
6277          TSCS != DeclSpec::TSCS_thread_local ||
6278          !DC->isFunctionOrMethod()))
6279       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6280            diag::err_thread_non_global)
6281         << DeclSpec::getSpecifierName(TSCS);
6282     else if (!Context.getTargetInfo().isTLSSupported()) {
6283       if (getLangOpts().CUDA) {
6284         // Postpone error emission until we've collected attributes required to
6285         // figure out whether it's a host or device variable and whether the
6286         // error should be ignored.
6287         EmitTLSUnsupportedError = true;
6288         // We still need to mark the variable as TLS so it shows up in AST with
6289         // proper storage class for other tools to use even if we're not going
6290         // to emit any code for it.
6291         NewVD->setTSCSpec(TSCS);
6292       } else
6293         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6294              diag::err_thread_unsupported);
6295     } else
6296       NewVD->setTSCSpec(TSCS);
6297   }
6298 
6299   // C99 6.7.4p3
6300   //   An inline definition of a function with external linkage shall
6301   //   not contain a definition of a modifiable object with static or
6302   //   thread storage duration...
6303   // We only apply this when the function is required to be defined
6304   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6305   // that a local variable with thread storage duration still has to
6306   // be marked 'static'.  Also note that it's possible to get these
6307   // semantics in C++ using __attribute__((gnu_inline)).
6308   if (SC == SC_Static && S->getFnParent() != nullptr &&
6309       !NewVD->getType().isConstQualified()) {
6310     FunctionDecl *CurFD = getCurFunctionDecl();
6311     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6312       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6313            diag::warn_static_local_in_extern_inline);
6314       MaybeSuggestAddingStaticToDecl(CurFD);
6315     }
6316   }
6317 
6318   if (D.getDeclSpec().isModulePrivateSpecified()) {
6319     if (IsVariableTemplateSpecialization)
6320       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6321           << (IsPartialSpecialization ? 1 : 0)
6322           << FixItHint::CreateRemoval(
6323                  D.getDeclSpec().getModulePrivateSpecLoc());
6324     else if (IsExplicitSpecialization)
6325       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6326         << 2
6327         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6328     else if (NewVD->hasLocalStorage())
6329       Diag(NewVD->getLocation(), diag::err_module_private_local)
6330         << 0 << NewVD->getDeclName()
6331         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6332         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6333     else {
6334       NewVD->setModulePrivate();
6335       if (NewTemplate)
6336         NewTemplate->setModulePrivate();
6337       for (auto *B : Bindings)
6338         B->setModulePrivate();
6339     }
6340   }
6341 
6342   // Handle attributes prior to checking for duplicates in MergeVarDecl
6343   ProcessDeclAttributes(S, NewVD, D);
6344 
6345   if (getLangOpts().CUDA) {
6346     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6347       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6348            diag::err_thread_unsupported);
6349     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6350     // storage [duration]."
6351     if (SC == SC_None && S->getFnParent() != nullptr &&
6352         (NewVD->hasAttr<CUDASharedAttr>() ||
6353          NewVD->hasAttr<CUDAConstantAttr>())) {
6354       NewVD->setStorageClass(SC_Static);
6355     }
6356   }
6357 
6358   // Ensure that dllimport globals without explicit storage class are treated as
6359   // extern. The storage class is set above using parsed attributes. Now we can
6360   // check the VarDecl itself.
6361   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6362          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6363          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6364 
6365   // In auto-retain/release, infer strong retension for variables of
6366   // retainable type.
6367   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6368     NewVD->setInvalidDecl();
6369 
6370   // Handle GNU asm-label extension (encoded as an attribute).
6371   if (Expr *E = (Expr*)D.getAsmLabel()) {
6372     // The parser guarantees this is a string.
6373     StringLiteral *SE = cast<StringLiteral>(E);
6374     StringRef Label = SE->getString();
6375     if (S->getFnParent() != nullptr) {
6376       switch (SC) {
6377       case SC_None:
6378       case SC_Auto:
6379         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6380         break;
6381       case SC_Register:
6382         // Local Named register
6383         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6384             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6385           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6386         break;
6387       case SC_Static:
6388       case SC_Extern:
6389       case SC_PrivateExtern:
6390         break;
6391       }
6392     } else if (SC == SC_Register) {
6393       // Global Named register
6394       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6395         const auto &TI = Context.getTargetInfo();
6396         bool HasSizeMismatch;
6397 
6398         if (!TI.isValidGCCRegisterName(Label))
6399           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6400         else if (!TI.validateGlobalRegisterVariable(Label,
6401                                                     Context.getTypeSize(R),
6402                                                     HasSizeMismatch))
6403           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6404         else if (HasSizeMismatch)
6405           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6406       }
6407 
6408       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6409         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6410         NewVD->setInvalidDecl(true);
6411       }
6412     }
6413 
6414     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6415                                                 Context, Label, 0));
6416   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6417     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6418       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6419     if (I != ExtnameUndeclaredIdentifiers.end()) {
6420       if (isDeclExternC(NewVD)) {
6421         NewVD->addAttr(I->second);
6422         ExtnameUndeclaredIdentifiers.erase(I);
6423       } else
6424         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6425             << /*Variable*/1 << NewVD;
6426     }
6427   }
6428 
6429   // Diagnose shadowed variables before filtering for scope.
6430   if (D.getCXXScopeSpec().isEmpty())
6431     CheckShadow(S, NewVD, Previous);
6432 
6433   // Don't consider existing declarations that are in a different
6434   // scope and are out-of-semantic-context declarations (if the new
6435   // declaration has linkage).
6436   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6437                        D.getCXXScopeSpec().isNotEmpty() ||
6438                        IsExplicitSpecialization ||
6439                        IsVariableTemplateSpecialization);
6440 
6441   // Check whether the previous declaration is in the same block scope. This
6442   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6443   if (getLangOpts().CPlusPlus &&
6444       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6445     NewVD->setPreviousDeclInSameBlockScope(
6446         Previous.isSingleResult() && !Previous.isShadowed() &&
6447         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6448 
6449   if (!getLangOpts().CPlusPlus) {
6450     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6451   } else {
6452     // If this is an explicit specialization of a static data member, check it.
6453     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6454         CheckMemberSpecialization(NewVD, Previous))
6455       NewVD->setInvalidDecl();
6456 
6457     // Merge the decl with the existing one if appropriate.
6458     if (!Previous.empty()) {
6459       if (Previous.isSingleResult() &&
6460           isa<FieldDecl>(Previous.getFoundDecl()) &&
6461           D.getCXXScopeSpec().isSet()) {
6462         // The user tried to define a non-static data member
6463         // out-of-line (C++ [dcl.meaning]p1).
6464         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6465           << D.getCXXScopeSpec().getRange();
6466         Previous.clear();
6467         NewVD->setInvalidDecl();
6468       }
6469     } else if (D.getCXXScopeSpec().isSet()) {
6470       // No previous declaration in the qualifying scope.
6471       Diag(D.getIdentifierLoc(), diag::err_no_member)
6472         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6473         << D.getCXXScopeSpec().getRange();
6474       NewVD->setInvalidDecl();
6475     }
6476 
6477     if (!IsVariableTemplateSpecialization)
6478       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6479 
6480     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6481     // an explicit specialization (14.8.3) or a partial specialization of a
6482     // concept definition.
6483     if (IsVariableTemplateSpecialization &&
6484         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6485         Previous.isSingleResult()) {
6486       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6487       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6488         if (VarTmpl->isConcept()) {
6489           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6490               << 1                            /*variable*/
6491               << (IsPartialSpecialization ? 2 /*partially specialized*/
6492                                           : 1 /*explicitly specialized*/);
6493           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6494           NewVD->setInvalidDecl();
6495         }
6496       }
6497     }
6498 
6499     if (NewTemplate) {
6500       VarTemplateDecl *PrevVarTemplate =
6501           NewVD->getPreviousDecl()
6502               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6503               : nullptr;
6504 
6505       // Check the template parameter list of this declaration, possibly
6506       // merging in the template parameter list from the previous variable
6507       // template declaration.
6508       if (CheckTemplateParameterList(
6509               TemplateParams,
6510               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6511                               : nullptr,
6512               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6513                DC->isDependentContext())
6514                   ? TPC_ClassTemplateMember
6515                   : TPC_VarTemplate))
6516         NewVD->setInvalidDecl();
6517 
6518       // If we are providing an explicit specialization of a static variable
6519       // template, make a note of that.
6520       if (PrevVarTemplate &&
6521           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6522         PrevVarTemplate->setMemberSpecialization();
6523     }
6524   }
6525 
6526   ProcessPragmaWeak(S, NewVD);
6527 
6528   // If this is the first declaration of an extern C variable, update
6529   // the map of such variables.
6530   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6531       isIncompleteDeclExternC(*this, NewVD))
6532     RegisterLocallyScopedExternCDecl(NewVD, S);
6533 
6534   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6535     Decl *ManglingContextDecl;
6536     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6537             NewVD->getDeclContext(), ManglingContextDecl)) {
6538       Context.setManglingNumber(
6539           NewVD, MCtx->getManglingNumber(
6540                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6541       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6542     }
6543   }
6544 
6545   // Special handling of variable named 'main'.
6546   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6547       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6548       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6549 
6550     // C++ [basic.start.main]p3
6551     // A program that declares a variable main at global scope is ill-formed.
6552     if (getLangOpts().CPlusPlus)
6553       Diag(D.getLocStart(), diag::err_main_global_variable);
6554 
6555     // In C, and external-linkage variable named main results in undefined
6556     // behavior.
6557     else if (NewVD->hasExternalFormalLinkage())
6558       Diag(D.getLocStart(), diag::warn_main_redefined);
6559   }
6560 
6561   if (D.isRedeclaration() && !Previous.empty()) {
6562     checkDLLAttributeRedeclaration(
6563         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6564         IsExplicitSpecialization, D.isFunctionDefinition());
6565   }
6566 
6567   if (NewTemplate) {
6568     if (NewVD->isInvalidDecl())
6569       NewTemplate->setInvalidDecl();
6570     ActOnDocumentableDecl(NewTemplate);
6571     return NewTemplate;
6572   }
6573 
6574   return NewVD;
6575 }
6576 
6577 /// Enum describing the %select options in diag::warn_decl_shadow.
6578 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6579 
6580 /// Determine what kind of declaration we're shadowing.
6581 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6582                                                 const DeclContext *OldDC) {
6583   if (isa<RecordDecl>(OldDC))
6584     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6585   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6586 }
6587 
6588 /// \brief Diagnose variable or built-in function shadowing.  Implements
6589 /// -Wshadow.
6590 ///
6591 /// This method is called whenever a VarDecl is added to a "useful"
6592 /// scope.
6593 ///
6594 /// \param S the scope in which the shadowing name is being declared
6595 /// \param R the lookup of the name
6596 ///
6597 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6598   // Return if warning is ignored.
6599   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6600     return;
6601 
6602   // Don't diagnose declarations at file scope.
6603   if (D->hasGlobalStorage())
6604     return;
6605 
6606   DeclContext *NewDC = D->getDeclContext();
6607 
6608   // Only diagnose if we're shadowing an unambiguous field or variable.
6609   if (R.getResultKind() != LookupResult::Found)
6610     return;
6611 
6612   NamedDecl* ShadowedDecl = R.getFoundDecl();
6613   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6614     return;
6615 
6616   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6617     // Fields are not shadowed by variables in C++ static methods.
6618     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6619       if (MD->isStatic())
6620         return;
6621 
6622     // Fields shadowed by constructor parameters are a special case. Usually
6623     // the constructor initializes the field with the parameter.
6624     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6625       // Remember that this was shadowed so we can either warn about its
6626       // modification or its existence depending on warning settings.
6627       D = D->getCanonicalDecl();
6628       ShadowingDecls.insert({D, FD});
6629       return;
6630     }
6631   }
6632 
6633   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6634     if (shadowedVar->isExternC()) {
6635       // For shadowing external vars, make sure that we point to the global
6636       // declaration, not a locally scoped extern declaration.
6637       for (auto I : shadowedVar->redecls())
6638         if (I->isFileVarDecl()) {
6639           ShadowedDecl = I;
6640           break;
6641         }
6642     }
6643 
6644   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6645 
6646   // Only warn about certain kinds of shadowing for class members.
6647   if (NewDC && NewDC->isRecord()) {
6648     // In particular, don't warn about shadowing non-class members.
6649     if (!OldDC->isRecord())
6650       return;
6651 
6652     // TODO: should we warn about static data members shadowing
6653     // static data members from base classes?
6654 
6655     // TODO: don't diagnose for inaccessible shadowed members.
6656     // This is hard to do perfectly because we might friend the
6657     // shadowing context, but that's just a false negative.
6658   }
6659 
6660 
6661   DeclarationName Name = R.getLookupName();
6662 
6663   // Emit warning and note.
6664   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6665     return;
6666   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6667   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6668   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6669 }
6670 
6671 /// \brief Check -Wshadow without the advantage of a previous lookup.
6672 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6673   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6674     return;
6675 
6676   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6677                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6678   LookupName(R, S);
6679   CheckShadow(S, D, R);
6680 }
6681 
6682 /// Check if 'E', which is an expression that is about to be modified, refers
6683 /// to a constructor parameter that shadows a field.
6684 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6685   // Quickly ignore expressions that can't be shadowing ctor parameters.
6686   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6687     return;
6688   E = E->IgnoreParenImpCasts();
6689   auto *DRE = dyn_cast<DeclRefExpr>(E);
6690   if (!DRE)
6691     return;
6692   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6693   auto I = ShadowingDecls.find(D);
6694   if (I == ShadowingDecls.end())
6695     return;
6696   const NamedDecl *ShadowedDecl = I->second;
6697   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6698   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6699   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6700   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6701 
6702   // Avoid issuing multiple warnings about the same decl.
6703   ShadowingDecls.erase(I);
6704 }
6705 
6706 /// Check for conflict between this global or extern "C" declaration and
6707 /// previous global or extern "C" declarations. This is only used in C++.
6708 template<typename T>
6709 static bool checkGlobalOrExternCConflict(
6710     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6711   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6712   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6713 
6714   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6715     // The common case: this global doesn't conflict with any extern "C"
6716     // declaration.
6717     return false;
6718   }
6719 
6720   if (Prev) {
6721     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6722       // Both the old and new declarations have C language linkage. This is a
6723       // redeclaration.
6724       Previous.clear();
6725       Previous.addDecl(Prev);
6726       return true;
6727     }
6728 
6729     // This is a global, non-extern "C" declaration, and there is a previous
6730     // non-global extern "C" declaration. Diagnose if this is a variable
6731     // declaration.
6732     if (!isa<VarDecl>(ND))
6733       return false;
6734   } else {
6735     // The declaration is extern "C". Check for any declaration in the
6736     // translation unit which might conflict.
6737     if (IsGlobal) {
6738       // We have already performed the lookup into the translation unit.
6739       IsGlobal = false;
6740       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6741            I != E; ++I) {
6742         if (isa<VarDecl>(*I)) {
6743           Prev = *I;
6744           break;
6745         }
6746       }
6747     } else {
6748       DeclContext::lookup_result R =
6749           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6750       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6751            I != E; ++I) {
6752         if (isa<VarDecl>(*I)) {
6753           Prev = *I;
6754           break;
6755         }
6756         // FIXME: If we have any other entity with this name in global scope,
6757         // the declaration is ill-formed, but that is a defect: it breaks the
6758         // 'stat' hack, for instance. Only variables can have mangled name
6759         // clashes with extern "C" declarations, so only they deserve a
6760         // diagnostic.
6761       }
6762     }
6763 
6764     if (!Prev)
6765       return false;
6766   }
6767 
6768   // Use the first declaration's location to ensure we point at something which
6769   // is lexically inside an extern "C" linkage-spec.
6770   assert(Prev && "should have found a previous declaration to diagnose");
6771   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6772     Prev = FD->getFirstDecl();
6773   else
6774     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6775 
6776   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6777     << IsGlobal << ND;
6778   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6779     << IsGlobal;
6780   return false;
6781 }
6782 
6783 /// Apply special rules for handling extern "C" declarations. Returns \c true
6784 /// if we have found that this is a redeclaration of some prior entity.
6785 ///
6786 /// Per C++ [dcl.link]p6:
6787 ///   Two declarations [for a function or variable] with C language linkage
6788 ///   with the same name that appear in different scopes refer to the same
6789 ///   [entity]. An entity with C language linkage shall not be declared with
6790 ///   the same name as an entity in global scope.
6791 template<typename T>
6792 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6793                                                   LookupResult &Previous) {
6794   if (!S.getLangOpts().CPlusPlus) {
6795     // In C, when declaring a global variable, look for a corresponding 'extern'
6796     // variable declared in function scope. We don't need this in C++, because
6797     // we find local extern decls in the surrounding file-scope DeclContext.
6798     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6799       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6800         Previous.clear();
6801         Previous.addDecl(Prev);
6802         return true;
6803       }
6804     }
6805     return false;
6806   }
6807 
6808   // A declaration in the translation unit can conflict with an extern "C"
6809   // declaration.
6810   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6811     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6812 
6813   // An extern "C" declaration can conflict with a declaration in the
6814   // translation unit or can be a redeclaration of an extern "C" declaration
6815   // in another scope.
6816   if (isIncompleteDeclExternC(S,ND))
6817     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6818 
6819   // Neither global nor extern "C": nothing to do.
6820   return false;
6821 }
6822 
6823 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6824   // If the decl is already known invalid, don't check it.
6825   if (NewVD->isInvalidDecl())
6826     return;
6827 
6828   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6829   QualType T = TInfo->getType();
6830 
6831   // Defer checking an 'auto' type until its initializer is attached.
6832   if (T->isUndeducedType())
6833     return;
6834 
6835   if (NewVD->hasAttrs())
6836     CheckAlignasUnderalignment(NewVD);
6837 
6838   if (T->isObjCObjectType()) {
6839     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6840       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6841     T = Context.getObjCObjectPointerType(T);
6842     NewVD->setType(T);
6843   }
6844 
6845   // Emit an error if an address space was applied to decl with local storage.
6846   // This includes arrays of objects with address space qualifiers, but not
6847   // automatic variables that point to other address spaces.
6848   // ISO/IEC TR 18037 S5.1.2
6849   if (!getLangOpts().OpenCL
6850       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6851     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6852     NewVD->setInvalidDecl();
6853     return;
6854   }
6855 
6856   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6857   // scope.
6858   if (getLangOpts().OpenCLVersion == 120 &&
6859       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6860       NewVD->isStaticLocal()) {
6861     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6862     NewVD->setInvalidDecl();
6863     return;
6864   }
6865 
6866   if (getLangOpts().OpenCL) {
6867     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6868     if (NewVD->hasAttr<BlocksAttr>()) {
6869       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6870       return;
6871     }
6872 
6873     if (T->isBlockPointerType()) {
6874       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6875       // can't use 'extern' storage class.
6876       if (!T.isConstQualified()) {
6877         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6878             << 0 /*const*/;
6879         NewVD->setInvalidDecl();
6880         return;
6881       }
6882       if (NewVD->hasExternalStorage()) {
6883         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6884         NewVD->setInvalidDecl();
6885         return;
6886       }
6887       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6888       // TODO: this check is not enough as it doesn't diagnose the typedef
6889       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6890       const FunctionProtoType *FTy =
6891           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6892       if (FTy && FTy->isVariadic()) {
6893         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6894             << T << NewVD->getSourceRange();
6895         NewVD->setInvalidDecl();
6896         return;
6897       }
6898     }
6899     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6900     // __constant address space.
6901     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6902     // variables inside a function can also be declared in the global
6903     // address space.
6904     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6905         NewVD->hasExternalStorage()) {
6906       if (!T->isSamplerT() &&
6907           !(T.getAddressSpace() == LangAS::opencl_constant ||
6908             (T.getAddressSpace() == LangAS::opencl_global &&
6909              getLangOpts().OpenCLVersion == 200))) {
6910         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6911         if (getLangOpts().OpenCLVersion == 200)
6912           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6913               << Scope << "global or constant";
6914         else
6915           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6916               << Scope << "constant";
6917         NewVD->setInvalidDecl();
6918         return;
6919       }
6920     } else {
6921       if (T.getAddressSpace() == LangAS::opencl_global) {
6922         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6923             << 1 /*is any function*/ << "global";
6924         NewVD->setInvalidDecl();
6925         return;
6926       }
6927       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6928       // in functions.
6929       if (T.getAddressSpace() == LangAS::opencl_constant ||
6930           T.getAddressSpace() == LangAS::opencl_local) {
6931         FunctionDecl *FD = getCurFunctionDecl();
6932         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6933           if (T.getAddressSpace() == LangAS::opencl_constant)
6934             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6935                 << 0 /*non-kernel only*/ << "constant";
6936           else
6937             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6938                 << 0 /*non-kernel only*/ << "local";
6939           NewVD->setInvalidDecl();
6940           return;
6941         }
6942       }
6943     }
6944   }
6945 
6946   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6947       && !NewVD->hasAttr<BlocksAttr>()) {
6948     if (getLangOpts().getGC() != LangOptions::NonGC)
6949       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6950     else {
6951       assert(!getLangOpts().ObjCAutoRefCount);
6952       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6953     }
6954   }
6955 
6956   bool isVM = T->isVariablyModifiedType();
6957   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6958       NewVD->hasAttr<BlocksAttr>())
6959     getCurFunction()->setHasBranchProtectedScope();
6960 
6961   if ((isVM && NewVD->hasLinkage()) ||
6962       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6963     bool SizeIsNegative;
6964     llvm::APSInt Oversized;
6965     TypeSourceInfo *FixedTInfo =
6966       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6967                                                     SizeIsNegative, Oversized);
6968     if (!FixedTInfo && T->isVariableArrayType()) {
6969       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6970       // FIXME: This won't give the correct result for
6971       // int a[10][n];
6972       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6973 
6974       if (NewVD->isFileVarDecl())
6975         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6976         << SizeRange;
6977       else if (NewVD->isStaticLocal())
6978         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6979         << SizeRange;
6980       else
6981         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6982         << SizeRange;
6983       NewVD->setInvalidDecl();
6984       return;
6985     }
6986 
6987     if (!FixedTInfo) {
6988       if (NewVD->isFileVarDecl())
6989         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6990       else
6991         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6992       NewVD->setInvalidDecl();
6993       return;
6994     }
6995 
6996     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6997     NewVD->setType(FixedTInfo->getType());
6998     NewVD->setTypeSourceInfo(FixedTInfo);
6999   }
7000 
7001   if (T->isVoidType()) {
7002     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7003     //                    of objects and functions.
7004     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7005       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7006         << T;
7007       NewVD->setInvalidDecl();
7008       return;
7009     }
7010   }
7011 
7012   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7013     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7014     NewVD->setInvalidDecl();
7015     return;
7016   }
7017 
7018   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7019     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7020     NewVD->setInvalidDecl();
7021     return;
7022   }
7023 
7024   if (NewVD->isConstexpr() && !T->isDependentType() &&
7025       RequireLiteralType(NewVD->getLocation(), T,
7026                          diag::err_constexpr_var_non_literal)) {
7027     NewVD->setInvalidDecl();
7028     return;
7029   }
7030 }
7031 
7032 /// \brief Perform semantic checking on a newly-created variable
7033 /// declaration.
7034 ///
7035 /// This routine performs all of the type-checking required for a
7036 /// variable declaration once it has been built. It is used both to
7037 /// check variables after they have been parsed and their declarators
7038 /// have been translated into a declaration, and to check variables
7039 /// that have been instantiated from a template.
7040 ///
7041 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7042 ///
7043 /// Returns true if the variable declaration is a redeclaration.
7044 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7045   CheckVariableDeclarationType(NewVD);
7046 
7047   // If the decl is already known invalid, don't check it.
7048   if (NewVD->isInvalidDecl())
7049     return false;
7050 
7051   // If we did not find anything by this name, look for a non-visible
7052   // extern "C" declaration with the same name.
7053   if (Previous.empty() &&
7054       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7055     Previous.setShadowed();
7056 
7057   if (!Previous.empty()) {
7058     MergeVarDecl(NewVD, Previous);
7059     return true;
7060   }
7061   return false;
7062 }
7063 
7064 namespace {
7065 struct FindOverriddenMethod {
7066   Sema *S;
7067   CXXMethodDecl *Method;
7068 
7069   /// Member lookup function that determines whether a given C++
7070   /// method overrides a method in a base class, to be used with
7071   /// CXXRecordDecl::lookupInBases().
7072   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7073     RecordDecl *BaseRecord =
7074         Specifier->getType()->getAs<RecordType>()->getDecl();
7075 
7076     DeclarationName Name = Method->getDeclName();
7077 
7078     // FIXME: Do we care about other names here too?
7079     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7080       // We really want to find the base class destructor here.
7081       QualType T = S->Context.getTypeDeclType(BaseRecord);
7082       CanQualType CT = S->Context.getCanonicalType(T);
7083 
7084       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7085     }
7086 
7087     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7088          Path.Decls = Path.Decls.slice(1)) {
7089       NamedDecl *D = Path.Decls.front();
7090       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7091         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7092           return true;
7093       }
7094     }
7095 
7096     return false;
7097   }
7098 };
7099 
7100 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7101 } // end anonymous namespace
7102 
7103 /// \brief Report an error regarding overriding, along with any relevant
7104 /// overriden methods.
7105 ///
7106 /// \param DiagID the primary error to report.
7107 /// \param MD the overriding method.
7108 /// \param OEK which overrides to include as notes.
7109 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7110                             OverrideErrorKind OEK = OEK_All) {
7111   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7112   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7113                                       E = MD->end_overridden_methods();
7114        I != E; ++I) {
7115     // This check (& the OEK parameter) could be replaced by a predicate, but
7116     // without lambdas that would be overkill. This is still nicer than writing
7117     // out the diag loop 3 times.
7118     if ((OEK == OEK_All) ||
7119         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7120         (OEK == OEK_Deleted && (*I)->isDeleted()))
7121       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7122   }
7123 }
7124 
7125 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7126 /// and if so, check that it's a valid override and remember it.
7127 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7128   // Look for methods in base classes that this method might override.
7129   CXXBasePaths Paths;
7130   FindOverriddenMethod FOM;
7131   FOM.Method = MD;
7132   FOM.S = this;
7133   bool hasDeletedOverridenMethods = false;
7134   bool hasNonDeletedOverridenMethods = false;
7135   bool AddedAny = false;
7136   if (DC->lookupInBases(FOM, Paths)) {
7137     for (auto *I : Paths.found_decls()) {
7138       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7139         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7140         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7141             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7142             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7143             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7144           hasDeletedOverridenMethods |= OldMD->isDeleted();
7145           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7146           AddedAny = true;
7147         }
7148       }
7149     }
7150   }
7151 
7152   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7153     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7154   }
7155   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7156     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7157   }
7158 
7159   return AddedAny;
7160 }
7161 
7162 namespace {
7163   // Struct for holding all of the extra arguments needed by
7164   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7165   struct ActOnFDArgs {
7166     Scope *S;
7167     Declarator &D;
7168     MultiTemplateParamsArg TemplateParamLists;
7169     bool AddToScope;
7170   };
7171 } // end anonymous namespace
7172 
7173 namespace {
7174 
7175 // Callback to only accept typo corrections that have a non-zero edit distance.
7176 // Also only accept corrections that have the same parent decl.
7177 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7178  public:
7179   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7180                             CXXRecordDecl *Parent)
7181       : Context(Context), OriginalFD(TypoFD),
7182         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7183 
7184   bool ValidateCandidate(const TypoCorrection &candidate) override {
7185     if (candidate.getEditDistance() == 0)
7186       return false;
7187 
7188     SmallVector<unsigned, 1> MismatchedParams;
7189     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7190                                           CDeclEnd = candidate.end();
7191          CDecl != CDeclEnd; ++CDecl) {
7192       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7193 
7194       if (FD && !FD->hasBody() &&
7195           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7196         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7197           CXXRecordDecl *Parent = MD->getParent();
7198           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7199             return true;
7200         } else if (!ExpectedParent) {
7201           return true;
7202         }
7203       }
7204     }
7205 
7206     return false;
7207   }
7208 
7209  private:
7210   ASTContext &Context;
7211   FunctionDecl *OriginalFD;
7212   CXXRecordDecl *ExpectedParent;
7213 };
7214 
7215 } // end anonymous namespace
7216 
7217 /// \brief Generate diagnostics for an invalid function redeclaration.
7218 ///
7219 /// This routine handles generating the diagnostic messages for an invalid
7220 /// function redeclaration, including finding possible similar declarations
7221 /// or performing typo correction if there are no previous declarations with
7222 /// the same name.
7223 ///
7224 /// Returns a NamedDecl iff typo correction was performed and substituting in
7225 /// the new declaration name does not cause new errors.
7226 static NamedDecl *DiagnoseInvalidRedeclaration(
7227     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7228     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7229   DeclarationName Name = NewFD->getDeclName();
7230   DeclContext *NewDC = NewFD->getDeclContext();
7231   SmallVector<unsigned, 1> MismatchedParams;
7232   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7233   TypoCorrection Correction;
7234   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7235   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7236                                    : diag::err_member_decl_does_not_match;
7237   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7238                     IsLocalFriend ? Sema::LookupLocalFriendName
7239                                   : Sema::LookupOrdinaryName,
7240                     Sema::ForRedeclaration);
7241 
7242   NewFD->setInvalidDecl();
7243   if (IsLocalFriend)
7244     SemaRef.LookupName(Prev, S);
7245   else
7246     SemaRef.LookupQualifiedName(Prev, NewDC);
7247   assert(!Prev.isAmbiguous() &&
7248          "Cannot have an ambiguity in previous-declaration lookup");
7249   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7250   if (!Prev.empty()) {
7251     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7252          Func != FuncEnd; ++Func) {
7253       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7254       if (FD &&
7255           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7256         // Add 1 to the index so that 0 can mean the mismatch didn't
7257         // involve a parameter
7258         unsigned ParamNum =
7259             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7260         NearMatches.push_back(std::make_pair(FD, ParamNum));
7261       }
7262     }
7263   // If the qualified name lookup yielded nothing, try typo correction
7264   } else if ((Correction = SemaRef.CorrectTypo(
7265                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7266                   &ExtraArgs.D.getCXXScopeSpec(),
7267                   llvm::make_unique<DifferentNameValidatorCCC>(
7268                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7269                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7270     // Set up everything for the call to ActOnFunctionDeclarator
7271     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7272                               ExtraArgs.D.getIdentifierLoc());
7273     Previous.clear();
7274     Previous.setLookupName(Correction.getCorrection());
7275     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7276                                     CDeclEnd = Correction.end();
7277          CDecl != CDeclEnd; ++CDecl) {
7278       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7279       if (FD && !FD->hasBody() &&
7280           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7281         Previous.addDecl(FD);
7282       }
7283     }
7284     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7285 
7286     NamedDecl *Result;
7287     // Retry building the function declaration with the new previous
7288     // declarations, and with errors suppressed.
7289     {
7290       // Trap errors.
7291       Sema::SFINAETrap Trap(SemaRef);
7292 
7293       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7294       // pieces need to verify the typo-corrected C++ declaration and hopefully
7295       // eliminate the need for the parameter pack ExtraArgs.
7296       Result = SemaRef.ActOnFunctionDeclarator(
7297           ExtraArgs.S, ExtraArgs.D,
7298           Correction.getCorrectionDecl()->getDeclContext(),
7299           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7300           ExtraArgs.AddToScope);
7301 
7302       if (Trap.hasErrorOccurred())
7303         Result = nullptr;
7304     }
7305 
7306     if (Result) {
7307       // Determine which correction we picked.
7308       Decl *Canonical = Result->getCanonicalDecl();
7309       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7310            I != E; ++I)
7311         if ((*I)->getCanonicalDecl() == Canonical)
7312           Correction.setCorrectionDecl(*I);
7313 
7314       SemaRef.diagnoseTypo(
7315           Correction,
7316           SemaRef.PDiag(IsLocalFriend
7317                           ? diag::err_no_matching_local_friend_suggest
7318                           : diag::err_member_decl_does_not_match_suggest)
7319             << Name << NewDC << IsDefinition);
7320       return Result;
7321     }
7322 
7323     // Pretend the typo correction never occurred
7324     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7325                               ExtraArgs.D.getIdentifierLoc());
7326     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7327     Previous.clear();
7328     Previous.setLookupName(Name);
7329   }
7330 
7331   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7332       << Name << NewDC << IsDefinition << NewFD->getLocation();
7333 
7334   bool NewFDisConst = false;
7335   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7336     NewFDisConst = NewMD->isConst();
7337 
7338   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7339        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7340        NearMatch != NearMatchEnd; ++NearMatch) {
7341     FunctionDecl *FD = NearMatch->first;
7342     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7343     bool FDisConst = MD && MD->isConst();
7344     bool IsMember = MD || !IsLocalFriend;
7345 
7346     // FIXME: These notes are poorly worded for the local friend case.
7347     if (unsigned Idx = NearMatch->second) {
7348       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7349       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7350       if (Loc.isInvalid()) Loc = FD->getLocation();
7351       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7352                                  : diag::note_local_decl_close_param_match)
7353         << Idx << FDParam->getType()
7354         << NewFD->getParamDecl(Idx - 1)->getType();
7355     } else if (FDisConst != NewFDisConst) {
7356       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7357           << NewFDisConst << FD->getSourceRange().getEnd();
7358     } else
7359       SemaRef.Diag(FD->getLocation(),
7360                    IsMember ? diag::note_member_def_close_match
7361                             : diag::note_local_decl_close_match);
7362   }
7363   return nullptr;
7364 }
7365 
7366 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7367   switch (D.getDeclSpec().getStorageClassSpec()) {
7368   default: llvm_unreachable("Unknown storage class!");
7369   case DeclSpec::SCS_auto:
7370   case DeclSpec::SCS_register:
7371   case DeclSpec::SCS_mutable:
7372     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7373                  diag::err_typecheck_sclass_func);
7374     D.setInvalidType();
7375     break;
7376   case DeclSpec::SCS_unspecified: break;
7377   case DeclSpec::SCS_extern:
7378     if (D.getDeclSpec().isExternInLinkageSpec())
7379       return SC_None;
7380     return SC_Extern;
7381   case DeclSpec::SCS_static: {
7382     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7383       // C99 6.7.1p5:
7384       //   The declaration of an identifier for a function that has
7385       //   block scope shall have no explicit storage-class specifier
7386       //   other than extern
7387       // See also (C++ [dcl.stc]p4).
7388       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7389                    diag::err_static_block_func);
7390       break;
7391     } else
7392       return SC_Static;
7393   }
7394   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7395   }
7396 
7397   // No explicit storage class has already been returned
7398   return SC_None;
7399 }
7400 
7401 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7402                                            DeclContext *DC, QualType &R,
7403                                            TypeSourceInfo *TInfo,
7404                                            StorageClass SC,
7405                                            bool &IsVirtualOkay) {
7406   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7407   DeclarationName Name = NameInfo.getName();
7408 
7409   FunctionDecl *NewFD = nullptr;
7410   bool isInline = D.getDeclSpec().isInlineSpecified();
7411 
7412   if (!SemaRef.getLangOpts().CPlusPlus) {
7413     // Determine whether the function was written with a
7414     // prototype. This true when:
7415     //   - there is a prototype in the declarator, or
7416     //   - the type R of the function is some kind of typedef or other reference
7417     //     to a type name (which eventually refers to a function type).
7418     bool HasPrototype =
7419       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7420       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7421 
7422     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7423                                  D.getLocStart(), NameInfo, R,
7424                                  TInfo, SC, isInline,
7425                                  HasPrototype, false);
7426     if (D.isInvalidType())
7427       NewFD->setInvalidDecl();
7428 
7429     return NewFD;
7430   }
7431 
7432   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7433   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7434 
7435   // Check that the return type is not an abstract class type.
7436   // For record types, this is done by the AbstractClassUsageDiagnoser once
7437   // the class has been completely parsed.
7438   if (!DC->isRecord() &&
7439       SemaRef.RequireNonAbstractType(
7440           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7441           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7442     D.setInvalidType();
7443 
7444   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7445     // This is a C++ constructor declaration.
7446     assert(DC->isRecord() &&
7447            "Constructors can only be declared in a member context");
7448 
7449     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7450     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7451                                       D.getLocStart(), NameInfo,
7452                                       R, TInfo, isExplicit, isInline,
7453                                       /*isImplicitlyDeclared=*/false,
7454                                       isConstexpr);
7455 
7456   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7457     // This is a C++ destructor declaration.
7458     if (DC->isRecord()) {
7459       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7460       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7461       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7462                                         SemaRef.Context, Record,
7463                                         D.getLocStart(),
7464                                         NameInfo, R, TInfo, isInline,
7465                                         /*isImplicitlyDeclared=*/false);
7466 
7467       // If the class is complete, then we now create the implicit exception
7468       // specification. If the class is incomplete or dependent, we can't do
7469       // it yet.
7470       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7471           Record->getDefinition() && !Record->isBeingDefined() &&
7472           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7473         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7474       }
7475 
7476       IsVirtualOkay = true;
7477       return NewDD;
7478 
7479     } else {
7480       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7481       D.setInvalidType();
7482 
7483       // Create a FunctionDecl to satisfy the function definition parsing
7484       // code path.
7485       return FunctionDecl::Create(SemaRef.Context, DC,
7486                                   D.getLocStart(),
7487                                   D.getIdentifierLoc(), Name, R, TInfo,
7488                                   SC, isInline,
7489                                   /*hasPrototype=*/true, isConstexpr);
7490     }
7491 
7492   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7493     if (!DC->isRecord()) {
7494       SemaRef.Diag(D.getIdentifierLoc(),
7495            diag::err_conv_function_not_member);
7496       return nullptr;
7497     }
7498 
7499     SemaRef.CheckConversionDeclarator(D, R, SC);
7500     IsVirtualOkay = true;
7501     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7502                                      D.getLocStart(), NameInfo,
7503                                      R, TInfo, isInline, isExplicit,
7504                                      isConstexpr, SourceLocation());
7505 
7506   } else if (DC->isRecord()) {
7507     // If the name of the function is the same as the name of the record,
7508     // then this must be an invalid constructor that has a return type.
7509     // (The parser checks for a return type and makes the declarator a
7510     // constructor if it has no return type).
7511     if (Name.getAsIdentifierInfo() &&
7512         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7513       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7514         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7515         << SourceRange(D.getIdentifierLoc());
7516       return nullptr;
7517     }
7518 
7519     // This is a C++ method declaration.
7520     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7521                                                cast<CXXRecordDecl>(DC),
7522                                                D.getLocStart(), NameInfo, R,
7523                                                TInfo, SC, isInline,
7524                                                isConstexpr, SourceLocation());
7525     IsVirtualOkay = !Ret->isStatic();
7526     return Ret;
7527   } else {
7528     bool isFriend =
7529         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7530     if (!isFriend && SemaRef.CurContext->isRecord())
7531       return nullptr;
7532 
7533     // Determine whether the function was written with a
7534     // prototype. This true when:
7535     //   - we're in C++ (where every function has a prototype),
7536     return FunctionDecl::Create(SemaRef.Context, DC,
7537                                 D.getLocStart(),
7538                                 NameInfo, R, TInfo, SC, isInline,
7539                                 true/*HasPrototype*/, isConstexpr);
7540   }
7541 }
7542 
7543 enum OpenCLParamType {
7544   ValidKernelParam,
7545   PtrPtrKernelParam,
7546   PtrKernelParam,
7547   PrivatePtrKernelParam,
7548   InvalidKernelParam,
7549   RecordKernelParam
7550 };
7551 
7552 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7553   if (PT->isPointerType()) {
7554     QualType PointeeType = PT->getPointeeType();
7555     if (PointeeType->isPointerType())
7556       return PtrPtrKernelParam;
7557     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7558                                               : PtrKernelParam;
7559   }
7560 
7561   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7562   // be used as builtin types.
7563 
7564   if (PT->isImageType())
7565     return PtrKernelParam;
7566 
7567   if (PT->isBooleanType())
7568     return InvalidKernelParam;
7569 
7570   if (PT->isEventT())
7571     return InvalidKernelParam;
7572 
7573   // OpenCL extension spec v1.2 s9.5:
7574   // This extension adds support for half scalar and vector types as built-in
7575   // types that can be used for arithmetic operations, conversions etc.
7576   if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType())
7577     return InvalidKernelParam;
7578 
7579   if (PT->isRecordType())
7580     return RecordKernelParam;
7581 
7582   return ValidKernelParam;
7583 }
7584 
7585 static void checkIsValidOpenCLKernelParameter(
7586   Sema &S,
7587   Declarator &D,
7588   ParmVarDecl *Param,
7589   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7590   QualType PT = Param->getType();
7591 
7592   // Cache the valid types we encounter to avoid rechecking structs that are
7593   // used again
7594   if (ValidTypes.count(PT.getTypePtr()))
7595     return;
7596 
7597   switch (getOpenCLKernelParameterType(S, PT)) {
7598   case PtrPtrKernelParam:
7599     // OpenCL v1.2 s6.9.a:
7600     // A kernel function argument cannot be declared as a
7601     // pointer to a pointer type.
7602     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7603     D.setInvalidType();
7604     return;
7605 
7606   case PrivatePtrKernelParam:
7607     // OpenCL v1.2 s6.9.a:
7608     // A kernel function argument cannot be declared as a
7609     // pointer to the private address space.
7610     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7611     D.setInvalidType();
7612     return;
7613 
7614     // OpenCL v1.2 s6.9.k:
7615     // Arguments to kernel functions in a program cannot be declared with the
7616     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7617     // uintptr_t or a struct and/or union that contain fields declared to be
7618     // one of these built-in scalar types.
7619 
7620   case InvalidKernelParam:
7621     // OpenCL v1.2 s6.8 n:
7622     // A kernel function argument cannot be declared
7623     // of event_t type.
7624     // Do not diagnose half type since it is diagnosed as invalid argument
7625     // type for any function elsewhere.
7626     if (!PT->isHalfType())
7627       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7628     D.setInvalidType();
7629     return;
7630 
7631   case PtrKernelParam:
7632   case ValidKernelParam:
7633     ValidTypes.insert(PT.getTypePtr());
7634     return;
7635 
7636   case RecordKernelParam:
7637     break;
7638   }
7639 
7640   // Track nested structs we will inspect
7641   SmallVector<const Decl *, 4> VisitStack;
7642 
7643   // Track where we are in the nested structs. Items will migrate from
7644   // VisitStack to HistoryStack as we do the DFS for bad field.
7645   SmallVector<const FieldDecl *, 4> HistoryStack;
7646   HistoryStack.push_back(nullptr);
7647 
7648   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7649   VisitStack.push_back(PD);
7650 
7651   assert(VisitStack.back() && "First decl null?");
7652 
7653   do {
7654     const Decl *Next = VisitStack.pop_back_val();
7655     if (!Next) {
7656       assert(!HistoryStack.empty());
7657       // Found a marker, we have gone up a level
7658       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7659         ValidTypes.insert(Hist->getType().getTypePtr());
7660 
7661       continue;
7662     }
7663 
7664     // Adds everything except the original parameter declaration (which is not a
7665     // field itself) to the history stack.
7666     const RecordDecl *RD;
7667     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7668       HistoryStack.push_back(Field);
7669       RD = Field->getType()->castAs<RecordType>()->getDecl();
7670     } else {
7671       RD = cast<RecordDecl>(Next);
7672     }
7673 
7674     // Add a null marker so we know when we've gone back up a level
7675     VisitStack.push_back(nullptr);
7676 
7677     for (const auto *FD : RD->fields()) {
7678       QualType QT = FD->getType();
7679 
7680       if (ValidTypes.count(QT.getTypePtr()))
7681         continue;
7682 
7683       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7684       if (ParamType == ValidKernelParam)
7685         continue;
7686 
7687       if (ParamType == RecordKernelParam) {
7688         VisitStack.push_back(FD);
7689         continue;
7690       }
7691 
7692       // OpenCL v1.2 s6.9.p:
7693       // Arguments to kernel functions that are declared to be a struct or union
7694       // do not allow OpenCL objects to be passed as elements of the struct or
7695       // union.
7696       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7697           ParamType == PrivatePtrKernelParam) {
7698         S.Diag(Param->getLocation(),
7699                diag::err_record_with_pointers_kernel_param)
7700           << PT->isUnionType()
7701           << PT;
7702       } else {
7703         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7704       }
7705 
7706       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7707         << PD->getDeclName();
7708 
7709       // We have an error, now let's go back up through history and show where
7710       // the offending field came from
7711       for (ArrayRef<const FieldDecl *>::const_iterator
7712                I = HistoryStack.begin() + 1,
7713                E = HistoryStack.end();
7714            I != E; ++I) {
7715         const FieldDecl *OuterField = *I;
7716         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7717           << OuterField->getType();
7718       }
7719 
7720       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7721         << QT->isPointerType()
7722         << QT;
7723       D.setInvalidType();
7724       return;
7725     }
7726   } while (!VisitStack.empty());
7727 }
7728 
7729 NamedDecl*
7730 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7731                               TypeSourceInfo *TInfo, LookupResult &Previous,
7732                               MultiTemplateParamsArg TemplateParamLists,
7733                               bool &AddToScope) {
7734   QualType R = TInfo->getType();
7735 
7736   assert(R.getTypePtr()->isFunctionType());
7737 
7738   // TODO: consider using NameInfo for diagnostic.
7739   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7740   DeclarationName Name = NameInfo.getName();
7741   StorageClass SC = getFunctionStorageClass(*this, D);
7742 
7743   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7744     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7745          diag::err_invalid_thread)
7746       << DeclSpec::getSpecifierName(TSCS);
7747 
7748   if (D.isFirstDeclarationOfMember())
7749     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7750                            D.getIdentifierLoc());
7751 
7752   bool isFriend = false;
7753   FunctionTemplateDecl *FunctionTemplate = nullptr;
7754   bool isExplicitSpecialization = false;
7755   bool isFunctionTemplateSpecialization = false;
7756 
7757   bool isDependentClassScopeExplicitSpecialization = false;
7758   bool HasExplicitTemplateArgs = false;
7759   TemplateArgumentListInfo TemplateArgs;
7760 
7761   bool isVirtualOkay = false;
7762 
7763   DeclContext *OriginalDC = DC;
7764   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7765 
7766   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7767                                               isVirtualOkay);
7768   if (!NewFD) return nullptr;
7769 
7770   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7771     NewFD->setTopLevelDeclInObjCContainer();
7772 
7773   // Set the lexical context. If this is a function-scope declaration, or has a
7774   // C++ scope specifier, or is the object of a friend declaration, the lexical
7775   // context will be different from the semantic context.
7776   NewFD->setLexicalDeclContext(CurContext);
7777 
7778   if (IsLocalExternDecl)
7779     NewFD->setLocalExternDecl();
7780 
7781   if (getLangOpts().CPlusPlus) {
7782     bool isInline = D.getDeclSpec().isInlineSpecified();
7783     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7784     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7785     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7786     bool isConcept = D.getDeclSpec().isConceptSpecified();
7787     isFriend = D.getDeclSpec().isFriendSpecified();
7788     if (isFriend && !isInline && D.isFunctionDefinition()) {
7789       // C++ [class.friend]p5
7790       //   A function can be defined in a friend declaration of a
7791       //   class . . . . Such a function is implicitly inline.
7792       NewFD->setImplicitlyInline();
7793     }
7794 
7795     // If this is a method defined in an __interface, and is not a constructor
7796     // or an overloaded operator, then set the pure flag (isVirtual will already
7797     // return true).
7798     if (const CXXRecordDecl *Parent =
7799           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7800       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7801         NewFD->setPure(true);
7802 
7803       // C++ [class.union]p2
7804       //   A union can have member functions, but not virtual functions.
7805       if (isVirtual && Parent->isUnion())
7806         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7807     }
7808 
7809     SetNestedNameSpecifier(NewFD, D);
7810     isExplicitSpecialization = false;
7811     isFunctionTemplateSpecialization = false;
7812     if (D.isInvalidType())
7813       NewFD->setInvalidDecl();
7814 
7815     // Match up the template parameter lists with the scope specifier, then
7816     // determine whether we have a template or a template specialization.
7817     bool Invalid = false;
7818     if (TemplateParameterList *TemplateParams =
7819             MatchTemplateParametersToScopeSpecifier(
7820                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7821                 D.getCXXScopeSpec(),
7822                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7823                     ? D.getName().TemplateId
7824                     : nullptr,
7825                 TemplateParamLists, isFriend, isExplicitSpecialization,
7826                 Invalid)) {
7827       if (TemplateParams->size() > 0) {
7828         // This is a function template
7829 
7830         // Check that we can declare a template here.
7831         if (CheckTemplateDeclScope(S, TemplateParams))
7832           NewFD->setInvalidDecl();
7833 
7834         // A destructor cannot be a template.
7835         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7836           Diag(NewFD->getLocation(), diag::err_destructor_template);
7837           NewFD->setInvalidDecl();
7838         }
7839 
7840         // If we're adding a template to a dependent context, we may need to
7841         // rebuilding some of the types used within the template parameter list,
7842         // now that we know what the current instantiation is.
7843         if (DC->isDependentContext()) {
7844           ContextRAII SavedContext(*this, DC);
7845           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7846             Invalid = true;
7847         }
7848 
7849         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7850                                                         NewFD->getLocation(),
7851                                                         Name, TemplateParams,
7852                                                         NewFD);
7853         FunctionTemplate->setLexicalDeclContext(CurContext);
7854         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7855 
7856         // For source fidelity, store the other template param lists.
7857         if (TemplateParamLists.size() > 1) {
7858           NewFD->setTemplateParameterListsInfo(Context,
7859                                                TemplateParamLists.drop_back(1));
7860         }
7861       } else {
7862         // This is a function template specialization.
7863         isFunctionTemplateSpecialization = true;
7864         // For source fidelity, store all the template param lists.
7865         if (TemplateParamLists.size() > 0)
7866           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7867 
7868         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7869         if (isFriend) {
7870           // We want to remove the "template<>", found here.
7871           SourceRange RemoveRange = TemplateParams->getSourceRange();
7872 
7873           // If we remove the template<> and the name is not a
7874           // template-id, we're actually silently creating a problem:
7875           // the friend declaration will refer to an untemplated decl,
7876           // and clearly the user wants a template specialization.  So
7877           // we need to insert '<>' after the name.
7878           SourceLocation InsertLoc;
7879           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7880             InsertLoc = D.getName().getSourceRange().getEnd();
7881             InsertLoc = getLocForEndOfToken(InsertLoc);
7882           }
7883 
7884           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7885             << Name << RemoveRange
7886             << FixItHint::CreateRemoval(RemoveRange)
7887             << FixItHint::CreateInsertion(InsertLoc, "<>");
7888         }
7889       }
7890     }
7891     else {
7892       // All template param lists were matched against the scope specifier:
7893       // this is NOT (an explicit specialization of) a template.
7894       if (TemplateParamLists.size() > 0)
7895         // For source fidelity, store all the template param lists.
7896         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7897     }
7898 
7899     if (Invalid) {
7900       NewFD->setInvalidDecl();
7901       if (FunctionTemplate)
7902         FunctionTemplate->setInvalidDecl();
7903     }
7904 
7905     // C++ [dcl.fct.spec]p5:
7906     //   The virtual specifier shall only be used in declarations of
7907     //   nonstatic class member functions that appear within a
7908     //   member-specification of a class declaration; see 10.3.
7909     //
7910     if (isVirtual && !NewFD->isInvalidDecl()) {
7911       if (!isVirtualOkay) {
7912         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7913              diag::err_virtual_non_function);
7914       } else if (!CurContext->isRecord()) {
7915         // 'virtual' was specified outside of the class.
7916         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7917              diag::err_virtual_out_of_class)
7918           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7919       } else if (NewFD->getDescribedFunctionTemplate()) {
7920         // C++ [temp.mem]p3:
7921         //  A member function template shall not be virtual.
7922         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7923              diag::err_virtual_member_function_template)
7924           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7925       } else {
7926         // Okay: Add virtual to the method.
7927         NewFD->setVirtualAsWritten(true);
7928       }
7929 
7930       if (getLangOpts().CPlusPlus14 &&
7931           NewFD->getReturnType()->isUndeducedType())
7932         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7933     }
7934 
7935     if (getLangOpts().CPlusPlus14 &&
7936         (NewFD->isDependentContext() ||
7937          (isFriend && CurContext->isDependentContext())) &&
7938         NewFD->getReturnType()->isUndeducedType()) {
7939       // If the function template is referenced directly (for instance, as a
7940       // member of the current instantiation), pretend it has a dependent type.
7941       // This is not really justified by the standard, but is the only sane
7942       // thing to do.
7943       // FIXME: For a friend function, we have not marked the function as being
7944       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7945       const FunctionProtoType *FPT =
7946           NewFD->getType()->castAs<FunctionProtoType>();
7947       QualType Result =
7948           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7949       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7950                                              FPT->getExtProtoInfo()));
7951     }
7952 
7953     // C++ [dcl.fct.spec]p3:
7954     //  The inline specifier shall not appear on a block scope function
7955     //  declaration.
7956     if (isInline && !NewFD->isInvalidDecl()) {
7957       if (CurContext->isFunctionOrMethod()) {
7958         // 'inline' is not allowed on block scope function declaration.
7959         Diag(D.getDeclSpec().getInlineSpecLoc(),
7960              diag::err_inline_declaration_block_scope) << Name
7961           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7962       }
7963     }
7964 
7965     // C++ [dcl.fct.spec]p6:
7966     //  The explicit specifier shall be used only in the declaration of a
7967     //  constructor or conversion function within its class definition;
7968     //  see 12.3.1 and 12.3.2.
7969     if (isExplicit && !NewFD->isInvalidDecl()) {
7970       if (!CurContext->isRecord()) {
7971         // 'explicit' was specified outside of the class.
7972         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7973              diag::err_explicit_out_of_class)
7974           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7975       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7976                  !isa<CXXConversionDecl>(NewFD)) {
7977         // 'explicit' was specified on a function that wasn't a constructor
7978         // or conversion function.
7979         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7980              diag::err_explicit_non_ctor_or_conv_function)
7981           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7982       }
7983     }
7984 
7985     if (isConstexpr) {
7986       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7987       // are implicitly inline.
7988       NewFD->setImplicitlyInline();
7989 
7990       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7991       // be either constructors or to return a literal type. Therefore,
7992       // destructors cannot be declared constexpr.
7993       if (isa<CXXDestructorDecl>(NewFD))
7994         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7995     }
7996 
7997     if (isConcept) {
7998       // This is a function concept.
7999       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8000         FTD->setConcept();
8001 
8002       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8003       // applied only to the definition of a function template [...]
8004       if (!D.isFunctionDefinition()) {
8005         Diag(D.getDeclSpec().getConceptSpecLoc(),
8006              diag::err_function_concept_not_defined);
8007         NewFD->setInvalidDecl();
8008       }
8009 
8010       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8011       // have no exception-specification and is treated as if it were specified
8012       // with noexcept(true) (15.4). [...]
8013       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8014         if (FPT->hasExceptionSpec()) {
8015           SourceRange Range;
8016           if (D.isFunctionDeclarator())
8017             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8018           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8019               << FixItHint::CreateRemoval(Range);
8020           NewFD->setInvalidDecl();
8021         } else {
8022           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8023         }
8024 
8025         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8026         // following restrictions:
8027         // - The declared return type shall have the type bool.
8028         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8029           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8030           NewFD->setInvalidDecl();
8031         }
8032 
8033         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8034         // following restrictions:
8035         // - The declaration's parameter list shall be equivalent to an empty
8036         //   parameter list.
8037         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8038           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8039       }
8040 
8041       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8042       // implicity defined to be a constexpr declaration (implicitly inline)
8043       NewFD->setImplicitlyInline();
8044 
8045       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8046       // be declared with the thread_local, inline, friend, or constexpr
8047       // specifiers, [...]
8048       if (isInline) {
8049         Diag(D.getDeclSpec().getInlineSpecLoc(),
8050              diag::err_concept_decl_invalid_specifiers)
8051             << 1 << 1;
8052         NewFD->setInvalidDecl(true);
8053       }
8054 
8055       if (isFriend) {
8056         Diag(D.getDeclSpec().getFriendSpecLoc(),
8057              diag::err_concept_decl_invalid_specifiers)
8058             << 1 << 2;
8059         NewFD->setInvalidDecl(true);
8060       }
8061 
8062       if (isConstexpr) {
8063         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8064              diag::err_concept_decl_invalid_specifiers)
8065             << 1 << 3;
8066         NewFD->setInvalidDecl(true);
8067       }
8068 
8069       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8070       // applied only to the definition of a function template or variable
8071       // template, declared in namespace scope.
8072       if (isFunctionTemplateSpecialization) {
8073         Diag(D.getDeclSpec().getConceptSpecLoc(),
8074              diag::err_concept_specified_specialization) << 1;
8075         NewFD->setInvalidDecl(true);
8076         return NewFD;
8077       }
8078     }
8079 
8080     // If __module_private__ was specified, mark the function accordingly.
8081     if (D.getDeclSpec().isModulePrivateSpecified()) {
8082       if (isFunctionTemplateSpecialization) {
8083         SourceLocation ModulePrivateLoc
8084           = D.getDeclSpec().getModulePrivateSpecLoc();
8085         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8086           << 0
8087           << FixItHint::CreateRemoval(ModulePrivateLoc);
8088       } else {
8089         NewFD->setModulePrivate();
8090         if (FunctionTemplate)
8091           FunctionTemplate->setModulePrivate();
8092       }
8093     }
8094 
8095     if (isFriend) {
8096       if (FunctionTemplate) {
8097         FunctionTemplate->setObjectOfFriendDecl();
8098         FunctionTemplate->setAccess(AS_public);
8099       }
8100       NewFD->setObjectOfFriendDecl();
8101       NewFD->setAccess(AS_public);
8102     }
8103 
8104     // If a function is defined as defaulted or deleted, mark it as such now.
8105     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8106     // definition kind to FDK_Definition.
8107     switch (D.getFunctionDefinitionKind()) {
8108       case FDK_Declaration:
8109       case FDK_Definition:
8110         break;
8111 
8112       case FDK_Defaulted:
8113         NewFD->setDefaulted();
8114         break;
8115 
8116       case FDK_Deleted:
8117         NewFD->setDeletedAsWritten();
8118         break;
8119     }
8120 
8121     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8122         D.isFunctionDefinition()) {
8123       // C++ [class.mfct]p2:
8124       //   A member function may be defined (8.4) in its class definition, in
8125       //   which case it is an inline member function (7.1.2)
8126       NewFD->setImplicitlyInline();
8127     }
8128 
8129     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8130         !CurContext->isRecord()) {
8131       // C++ [class.static]p1:
8132       //   A data or function member of a class may be declared static
8133       //   in a class definition, in which case it is a static member of
8134       //   the class.
8135 
8136       // Complain about the 'static' specifier if it's on an out-of-line
8137       // member function definition.
8138       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8139            diag::err_static_out_of_line)
8140         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8141     }
8142 
8143     // C++11 [except.spec]p15:
8144     //   A deallocation function with no exception-specification is treated
8145     //   as if it were specified with noexcept(true).
8146     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8147     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8148          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8149         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8150       NewFD->setType(Context.getFunctionType(
8151           FPT->getReturnType(), FPT->getParamTypes(),
8152           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8153   }
8154 
8155   // Filter out previous declarations that don't match the scope.
8156   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8157                        D.getCXXScopeSpec().isNotEmpty() ||
8158                        isExplicitSpecialization ||
8159                        isFunctionTemplateSpecialization);
8160 
8161   // Handle GNU asm-label extension (encoded as an attribute).
8162   if (Expr *E = (Expr*) D.getAsmLabel()) {
8163     // The parser guarantees this is a string.
8164     StringLiteral *SE = cast<StringLiteral>(E);
8165     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8166                                                 SE->getString(), 0));
8167   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8168     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8169       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8170     if (I != ExtnameUndeclaredIdentifiers.end()) {
8171       if (isDeclExternC(NewFD)) {
8172         NewFD->addAttr(I->second);
8173         ExtnameUndeclaredIdentifiers.erase(I);
8174       } else
8175         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8176             << /*Variable*/0 << NewFD;
8177     }
8178   }
8179 
8180   // Copy the parameter declarations from the declarator D to the function
8181   // declaration NewFD, if they are available.  First scavenge them into Params.
8182   SmallVector<ParmVarDecl*, 16> Params;
8183   if (D.isFunctionDeclarator()) {
8184     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8185 
8186     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8187     // function that takes no arguments, not a function that takes a
8188     // single void argument.
8189     // We let through "const void" here because Sema::GetTypeForDeclarator
8190     // already checks for that case.
8191     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8192       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8193         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8194         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8195         Param->setDeclContext(NewFD);
8196         Params.push_back(Param);
8197 
8198         if (Param->isInvalidDecl())
8199           NewFD->setInvalidDecl();
8200       }
8201     }
8202   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8203     // When we're declaring a function with a typedef, typeof, etc as in the
8204     // following example, we'll need to synthesize (unnamed)
8205     // parameters for use in the declaration.
8206     //
8207     // @code
8208     // typedef void fn(int);
8209     // fn f;
8210     // @endcode
8211 
8212     // Synthesize a parameter for each argument type.
8213     for (const auto &AI : FT->param_types()) {
8214       ParmVarDecl *Param =
8215           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8216       Param->setScopeInfo(0, Params.size());
8217       Params.push_back(Param);
8218     }
8219   } else {
8220     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8221            "Should not need args for typedef of non-prototype fn");
8222   }
8223 
8224   // Finally, we know we have the right number of parameters, install them.
8225   NewFD->setParams(Params);
8226 
8227   // Find all anonymous symbols defined during the declaration of this function
8228   // and add to NewFD. This lets us track decls such 'enum Y' in:
8229   //
8230   //   void f(enum Y {AA} x) {}
8231   //
8232   // which would otherwise incorrectly end up in the translation unit scope.
8233   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8234   DeclsInPrototypeScope.clear();
8235 
8236   if (D.getDeclSpec().isNoreturnSpecified())
8237     NewFD->addAttr(
8238         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8239                                        Context, 0));
8240 
8241   // Functions returning a variably modified type violate C99 6.7.5.2p2
8242   // because all functions have linkage.
8243   if (!NewFD->isInvalidDecl() &&
8244       NewFD->getReturnType()->isVariablyModifiedType()) {
8245     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8246     NewFD->setInvalidDecl();
8247   }
8248 
8249   // Apply an implicit SectionAttr if #pragma code_seg is active.
8250   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8251       !NewFD->hasAttr<SectionAttr>()) {
8252     NewFD->addAttr(
8253         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8254                                     CodeSegStack.CurrentValue->getString(),
8255                                     CodeSegStack.CurrentPragmaLocation));
8256     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8257                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8258                          ASTContext::PSF_Read,
8259                      NewFD))
8260       NewFD->dropAttr<SectionAttr>();
8261   }
8262 
8263   // Handle attributes.
8264   ProcessDeclAttributes(S, NewFD, D);
8265 
8266   if (getLangOpts().CUDA)
8267     maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8268 
8269   if (getLangOpts().OpenCL) {
8270     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8271     // type declaration will generate a compilation error.
8272     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8273     if (AddressSpace == LangAS::opencl_local ||
8274         AddressSpace == LangAS::opencl_global ||
8275         AddressSpace == LangAS::opencl_constant) {
8276       Diag(NewFD->getLocation(),
8277            diag::err_opencl_return_value_with_address_space);
8278       NewFD->setInvalidDecl();
8279     }
8280   }
8281 
8282   if (!getLangOpts().CPlusPlus) {
8283     // Perform semantic checking on the function declaration.
8284     bool isExplicitSpecialization=false;
8285     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8286       CheckMain(NewFD, D.getDeclSpec());
8287 
8288     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8289       CheckMSVCRTEntryPoint(NewFD);
8290 
8291     if (!NewFD->isInvalidDecl())
8292       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8293                                                   isExplicitSpecialization));
8294     else if (!Previous.empty())
8295       // Recover gracefully from an invalid redeclaration.
8296       D.setRedeclaration(true);
8297     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8298             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8299            "previous declaration set still overloaded");
8300 
8301     // Diagnose no-prototype function declarations with calling conventions that
8302     // don't support variadic calls. Only do this in C and do it after merging
8303     // possibly prototyped redeclarations.
8304     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8305     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8306       CallingConv CC = FT->getExtInfo().getCC();
8307       if (!supportsVariadicCall(CC)) {
8308         // Windows system headers sometimes accidentally use stdcall without
8309         // (void) parameters, so we relax this to a warning.
8310         int DiagID =
8311             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8312         Diag(NewFD->getLocation(), DiagID)
8313             << FunctionType::getNameForCallConv(CC);
8314       }
8315     }
8316   } else {
8317     // C++11 [replacement.functions]p3:
8318     //  The program's definitions shall not be specified as inline.
8319     //
8320     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8321     //
8322     // Suppress the diagnostic if the function is __attribute__((used)), since
8323     // that forces an external definition to be emitted.
8324     if (D.getDeclSpec().isInlineSpecified() &&
8325         NewFD->isReplaceableGlobalAllocationFunction() &&
8326         !NewFD->hasAttr<UsedAttr>())
8327       Diag(D.getDeclSpec().getInlineSpecLoc(),
8328            diag::ext_operator_new_delete_declared_inline)
8329         << NewFD->getDeclName();
8330 
8331     // If the declarator is a template-id, translate the parser's template
8332     // argument list into our AST format.
8333     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8334       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8335       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8336       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8337       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8338                                          TemplateId->NumArgs);
8339       translateTemplateArguments(TemplateArgsPtr,
8340                                  TemplateArgs);
8341 
8342       HasExplicitTemplateArgs = true;
8343 
8344       if (NewFD->isInvalidDecl()) {
8345         HasExplicitTemplateArgs = false;
8346       } else if (FunctionTemplate) {
8347         // Function template with explicit template arguments.
8348         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8349           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8350 
8351         HasExplicitTemplateArgs = false;
8352       } else {
8353         assert((isFunctionTemplateSpecialization ||
8354                 D.getDeclSpec().isFriendSpecified()) &&
8355                "should have a 'template<>' for this decl");
8356         // "friend void foo<>(int);" is an implicit specialization decl.
8357         isFunctionTemplateSpecialization = true;
8358       }
8359     } else if (isFriend && isFunctionTemplateSpecialization) {
8360       // This combination is only possible in a recovery case;  the user
8361       // wrote something like:
8362       //   template <> friend void foo(int);
8363       // which we're recovering from as if the user had written:
8364       //   friend void foo<>(int);
8365       // Go ahead and fake up a template id.
8366       HasExplicitTemplateArgs = true;
8367       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8368       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8369     }
8370 
8371     // If it's a friend (and only if it's a friend), it's possible
8372     // that either the specialized function type or the specialized
8373     // template is dependent, and therefore matching will fail.  In
8374     // this case, don't check the specialization yet.
8375     bool InstantiationDependent = false;
8376     if (isFunctionTemplateSpecialization && isFriend &&
8377         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8378          TemplateSpecializationType::anyDependentTemplateArguments(
8379             TemplateArgs,
8380             InstantiationDependent))) {
8381       assert(HasExplicitTemplateArgs &&
8382              "friend function specialization without template args");
8383       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8384                                                        Previous))
8385         NewFD->setInvalidDecl();
8386     } else if (isFunctionTemplateSpecialization) {
8387       if (CurContext->isDependentContext() && CurContext->isRecord()
8388           && !isFriend) {
8389         isDependentClassScopeExplicitSpecialization = true;
8390         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8391           diag::ext_function_specialization_in_class :
8392           diag::err_function_specialization_in_class)
8393           << NewFD->getDeclName();
8394       } else if (CheckFunctionTemplateSpecialization(NewFD,
8395                                   (HasExplicitTemplateArgs ? &TemplateArgs
8396                                                            : nullptr),
8397                                                      Previous))
8398         NewFD->setInvalidDecl();
8399 
8400       // C++ [dcl.stc]p1:
8401       //   A storage-class-specifier shall not be specified in an explicit
8402       //   specialization (14.7.3)
8403       FunctionTemplateSpecializationInfo *Info =
8404           NewFD->getTemplateSpecializationInfo();
8405       if (Info && SC != SC_None) {
8406         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8407           Diag(NewFD->getLocation(),
8408                diag::err_explicit_specialization_inconsistent_storage_class)
8409             << SC
8410             << FixItHint::CreateRemoval(
8411                                       D.getDeclSpec().getStorageClassSpecLoc());
8412 
8413         else
8414           Diag(NewFD->getLocation(),
8415                diag::ext_explicit_specialization_storage_class)
8416             << FixItHint::CreateRemoval(
8417                                       D.getDeclSpec().getStorageClassSpecLoc());
8418       }
8419     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8420       if (CheckMemberSpecialization(NewFD, Previous))
8421           NewFD->setInvalidDecl();
8422     }
8423 
8424     // Perform semantic checking on the function declaration.
8425     if (!isDependentClassScopeExplicitSpecialization) {
8426       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8427         CheckMain(NewFD, D.getDeclSpec());
8428 
8429       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8430         CheckMSVCRTEntryPoint(NewFD);
8431 
8432       if (!NewFD->isInvalidDecl())
8433         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8434                                                     isExplicitSpecialization));
8435       else if (!Previous.empty())
8436         // Recover gracefully from an invalid redeclaration.
8437         D.setRedeclaration(true);
8438     }
8439 
8440     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8441             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8442            "previous declaration set still overloaded");
8443 
8444     NamedDecl *PrincipalDecl = (FunctionTemplate
8445                                 ? cast<NamedDecl>(FunctionTemplate)
8446                                 : NewFD);
8447 
8448     if (isFriend && NewFD->getPreviousDecl()) {
8449       AccessSpecifier Access = AS_public;
8450       if (!NewFD->isInvalidDecl())
8451         Access = NewFD->getPreviousDecl()->getAccess();
8452 
8453       NewFD->setAccess(Access);
8454       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8455     }
8456 
8457     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8458         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8459       PrincipalDecl->setNonMemberOperator();
8460 
8461     // If we have a function template, check the template parameter
8462     // list. This will check and merge default template arguments.
8463     if (FunctionTemplate) {
8464       FunctionTemplateDecl *PrevTemplate =
8465                                      FunctionTemplate->getPreviousDecl();
8466       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8467                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8468                                     : nullptr,
8469                             D.getDeclSpec().isFriendSpecified()
8470                               ? (D.isFunctionDefinition()
8471                                    ? TPC_FriendFunctionTemplateDefinition
8472                                    : TPC_FriendFunctionTemplate)
8473                               : (D.getCXXScopeSpec().isSet() &&
8474                                  DC && DC->isRecord() &&
8475                                  DC->isDependentContext())
8476                                   ? TPC_ClassTemplateMember
8477                                   : TPC_FunctionTemplate);
8478     }
8479 
8480     if (NewFD->isInvalidDecl()) {
8481       // Ignore all the rest of this.
8482     } else if (!D.isRedeclaration()) {
8483       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8484                                        AddToScope };
8485       // Fake up an access specifier if it's supposed to be a class member.
8486       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8487         NewFD->setAccess(AS_public);
8488 
8489       // Qualified decls generally require a previous declaration.
8490       if (D.getCXXScopeSpec().isSet()) {
8491         // ...with the major exception of templated-scope or
8492         // dependent-scope friend declarations.
8493 
8494         // TODO: we currently also suppress this check in dependent
8495         // contexts because (1) the parameter depth will be off when
8496         // matching friend templates and (2) we might actually be
8497         // selecting a friend based on a dependent factor.  But there
8498         // are situations where these conditions don't apply and we
8499         // can actually do this check immediately.
8500         if (isFriend &&
8501             (TemplateParamLists.size() ||
8502              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8503              CurContext->isDependentContext())) {
8504           // ignore these
8505         } else {
8506           // The user tried to provide an out-of-line definition for a
8507           // function that is a member of a class or namespace, but there
8508           // was no such member function declared (C++ [class.mfct]p2,
8509           // C++ [namespace.memdef]p2). For example:
8510           //
8511           // class X {
8512           //   void f() const;
8513           // };
8514           //
8515           // void X::f() { } // ill-formed
8516           //
8517           // Complain about this problem, and attempt to suggest close
8518           // matches (e.g., those that differ only in cv-qualifiers and
8519           // whether the parameter types are references).
8520 
8521           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8522                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8523             AddToScope = ExtraArgs.AddToScope;
8524             return Result;
8525           }
8526         }
8527 
8528         // Unqualified local friend declarations are required to resolve
8529         // to something.
8530       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8531         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8532                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8533           AddToScope = ExtraArgs.AddToScope;
8534           return Result;
8535         }
8536       }
8537     } else if (!D.isFunctionDefinition() &&
8538                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8539                !isFriend && !isFunctionTemplateSpecialization &&
8540                !isExplicitSpecialization) {
8541       // An out-of-line member function declaration must also be a
8542       // definition (C++ [class.mfct]p2).
8543       // Note that this is not the case for explicit specializations of
8544       // function templates or member functions of class templates, per
8545       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8546       // extension for compatibility with old SWIG code which likes to
8547       // generate them.
8548       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8549         << D.getCXXScopeSpec().getRange();
8550     }
8551   }
8552 
8553   ProcessPragmaWeak(S, NewFD);
8554   checkAttributesAfterMerging(*this, *NewFD);
8555 
8556   AddKnownFunctionAttributes(NewFD);
8557 
8558   if (NewFD->hasAttr<OverloadableAttr>() &&
8559       !NewFD->getType()->getAs<FunctionProtoType>()) {
8560     Diag(NewFD->getLocation(),
8561          diag::err_attribute_overloadable_no_prototype)
8562       << NewFD;
8563 
8564     // Turn this into a variadic function with no parameters.
8565     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8566     FunctionProtoType::ExtProtoInfo EPI(
8567         Context.getDefaultCallingConvention(true, false));
8568     EPI.Variadic = true;
8569     EPI.ExtInfo = FT->getExtInfo();
8570 
8571     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8572     NewFD->setType(R);
8573   }
8574 
8575   // If there's a #pragma GCC visibility in scope, and this isn't a class
8576   // member, set the visibility of this function.
8577   if (!DC->isRecord() && NewFD->isExternallyVisible())
8578     AddPushedVisibilityAttribute(NewFD);
8579 
8580   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8581   // marking the function.
8582   AddCFAuditedAttribute(NewFD);
8583 
8584   // If this is a function definition, check if we have to apply optnone due to
8585   // a pragma.
8586   if(D.isFunctionDefinition())
8587     AddRangeBasedOptnone(NewFD);
8588 
8589   // If this is the first declaration of an extern C variable, update
8590   // the map of such variables.
8591   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8592       isIncompleteDeclExternC(*this, NewFD))
8593     RegisterLocallyScopedExternCDecl(NewFD, S);
8594 
8595   // Set this FunctionDecl's range up to the right paren.
8596   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8597 
8598   if (D.isRedeclaration() && !Previous.empty()) {
8599     checkDLLAttributeRedeclaration(
8600         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8601         isExplicitSpecialization || isFunctionTemplateSpecialization,
8602         D.isFunctionDefinition());
8603   }
8604 
8605   if (getLangOpts().CUDA) {
8606     IdentifierInfo *II = NewFD->getIdentifier();
8607     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8608         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8609       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8610         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8611 
8612       Context.setcudaConfigureCallDecl(NewFD);
8613     }
8614 
8615     // Variadic functions, other than a *declaration* of printf, are not allowed
8616     // in device-side CUDA code, unless someone passed
8617     // -fcuda-allow-variadic-functions.
8618     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8619         (NewFD->hasAttr<CUDADeviceAttr>() ||
8620          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8621         !(II && II->isStr("printf") && NewFD->isExternC() &&
8622           !D.isFunctionDefinition())) {
8623       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8624     }
8625   }
8626 
8627   if (getLangOpts().CPlusPlus) {
8628     if (FunctionTemplate) {
8629       if (NewFD->isInvalidDecl())
8630         FunctionTemplate->setInvalidDecl();
8631       return FunctionTemplate;
8632     }
8633   }
8634 
8635   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8636     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8637     if ((getLangOpts().OpenCLVersion >= 120)
8638         && (SC == SC_Static)) {
8639       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8640       D.setInvalidType();
8641     }
8642 
8643     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8644     if (!NewFD->getReturnType()->isVoidType()) {
8645       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8646       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8647           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8648                                 : FixItHint());
8649       D.setInvalidType();
8650     }
8651 
8652     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8653     for (auto Param : NewFD->parameters())
8654       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8655   }
8656   for (const ParmVarDecl *Param : NewFD->parameters()) {
8657     QualType PT = Param->getType();
8658 
8659     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8660     // types.
8661     if (getLangOpts().OpenCLVersion >= 200) {
8662       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8663         QualType ElemTy = PipeTy->getElementType();
8664           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8665             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8666             D.setInvalidType();
8667           }
8668       }
8669     }
8670   }
8671 
8672   MarkUnusedFileScopedDecl(NewFD);
8673 
8674   // Here we have an function template explicit specialization at class scope.
8675   // The actually specialization will be postponed to template instatiation
8676   // time via the ClassScopeFunctionSpecializationDecl node.
8677   if (isDependentClassScopeExplicitSpecialization) {
8678     ClassScopeFunctionSpecializationDecl *NewSpec =
8679                          ClassScopeFunctionSpecializationDecl::Create(
8680                                 Context, CurContext, SourceLocation(),
8681                                 cast<CXXMethodDecl>(NewFD),
8682                                 HasExplicitTemplateArgs, TemplateArgs);
8683     CurContext->addDecl(NewSpec);
8684     AddToScope = false;
8685   }
8686 
8687   return NewFD;
8688 }
8689 
8690 /// \brief Checks if the new declaration declared in dependent context must be
8691 /// put in the same redeclaration chain as the specified declaration.
8692 ///
8693 /// \param D Declaration that is checked.
8694 /// \param PrevDecl Previous declaration found with proper lookup method for the
8695 ///                 same declaration name.
8696 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8697 ///          belongs to.
8698 ///
8699 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8700   // Any declarations should be put into redeclaration chains except for
8701   // friend declaration in a dependent context that names a function in
8702   // namespace scope.
8703   //
8704   // This allows to compile code like:
8705   //
8706   //       void func();
8707   //       template<typename T> class C1 { friend void func() { } };
8708   //       template<typename T> class C2 { friend void func() { } };
8709   //
8710   // This code snippet is a valid code unless both templates are instantiated.
8711   return !(D->getLexicalDeclContext()->isDependentContext() &&
8712            D->getDeclContext()->isFileContext() &&
8713            D->getFriendObjectKind() != Decl::FOK_None);
8714 }
8715 
8716 /// \brief Perform semantic checking of a new function declaration.
8717 ///
8718 /// Performs semantic analysis of the new function declaration
8719 /// NewFD. This routine performs all semantic checking that does not
8720 /// require the actual declarator involved in the declaration, and is
8721 /// used both for the declaration of functions as they are parsed
8722 /// (called via ActOnDeclarator) and for the declaration of functions
8723 /// that have been instantiated via C++ template instantiation (called
8724 /// via InstantiateDecl).
8725 ///
8726 /// \param IsExplicitSpecialization whether this new function declaration is
8727 /// an explicit specialization of the previous declaration.
8728 ///
8729 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8730 ///
8731 /// \returns true if the function declaration is a redeclaration.
8732 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8733                                     LookupResult &Previous,
8734                                     bool IsExplicitSpecialization) {
8735   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8736          "Variably modified return types are not handled here");
8737 
8738   // Determine whether the type of this function should be merged with
8739   // a previous visible declaration. This never happens for functions in C++,
8740   // and always happens in C if the previous declaration was visible.
8741   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8742                                !Previous.isShadowed();
8743 
8744   bool Redeclaration = false;
8745   NamedDecl *OldDecl = nullptr;
8746 
8747   // Merge or overload the declaration with an existing declaration of
8748   // the same name, if appropriate.
8749   if (!Previous.empty()) {
8750     // Determine whether NewFD is an overload of PrevDecl or
8751     // a declaration that requires merging. If it's an overload,
8752     // there's no more work to do here; we'll just add the new
8753     // function to the scope.
8754     if (!AllowOverloadingOfFunction(Previous, Context)) {
8755       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8756       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8757         Redeclaration = true;
8758         OldDecl = Candidate;
8759       }
8760     } else {
8761       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8762                             /*NewIsUsingDecl*/ false)) {
8763       case Ovl_Match:
8764         Redeclaration = true;
8765         break;
8766 
8767       case Ovl_NonFunction:
8768         Redeclaration = true;
8769         break;
8770 
8771       case Ovl_Overload:
8772         Redeclaration = false;
8773         break;
8774       }
8775 
8776       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8777         // If a function name is overloadable in C, then every function
8778         // with that name must be marked "overloadable".
8779         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8780           << Redeclaration << NewFD;
8781         NamedDecl *OverloadedDecl = nullptr;
8782         if (Redeclaration)
8783           OverloadedDecl = OldDecl;
8784         else if (!Previous.empty())
8785           OverloadedDecl = Previous.getRepresentativeDecl();
8786         if (OverloadedDecl)
8787           Diag(OverloadedDecl->getLocation(),
8788                diag::note_attribute_overloadable_prev_overload);
8789         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8790       }
8791     }
8792   }
8793 
8794   // Check for a previous extern "C" declaration with this name.
8795   if (!Redeclaration &&
8796       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8797     if (!Previous.empty()) {
8798       // This is an extern "C" declaration with the same name as a previous
8799       // declaration, and thus redeclares that entity...
8800       Redeclaration = true;
8801       OldDecl = Previous.getFoundDecl();
8802       MergeTypeWithPrevious = false;
8803 
8804       // ... except in the presence of __attribute__((overloadable)).
8805       if (OldDecl->hasAttr<OverloadableAttr>()) {
8806         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8807           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8808             << Redeclaration << NewFD;
8809           Diag(Previous.getFoundDecl()->getLocation(),
8810                diag::note_attribute_overloadable_prev_overload);
8811           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8812         }
8813         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8814           Redeclaration = false;
8815           OldDecl = nullptr;
8816         }
8817       }
8818     }
8819   }
8820 
8821   // C++11 [dcl.constexpr]p8:
8822   //   A constexpr specifier for a non-static member function that is not
8823   //   a constructor declares that member function to be const.
8824   //
8825   // This needs to be delayed until we know whether this is an out-of-line
8826   // definition of a static member function.
8827   //
8828   // This rule is not present in C++1y, so we produce a backwards
8829   // compatibility warning whenever it happens in C++11.
8830   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8831   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8832       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8833       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8834     CXXMethodDecl *OldMD = nullptr;
8835     if (OldDecl)
8836       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8837     if (!OldMD || !OldMD->isStatic()) {
8838       const FunctionProtoType *FPT =
8839         MD->getType()->castAs<FunctionProtoType>();
8840       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8841       EPI.TypeQuals |= Qualifiers::Const;
8842       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8843                                           FPT->getParamTypes(), EPI));
8844 
8845       // Warn that we did this, if we're not performing template instantiation.
8846       // In that case, we'll have warned already when the template was defined.
8847       if (ActiveTemplateInstantiations.empty()) {
8848         SourceLocation AddConstLoc;
8849         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8850                 .IgnoreParens().getAs<FunctionTypeLoc>())
8851           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8852 
8853         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8854           << FixItHint::CreateInsertion(AddConstLoc, " const");
8855       }
8856     }
8857   }
8858 
8859   if (Redeclaration) {
8860     // NewFD and OldDecl represent declarations that need to be
8861     // merged.
8862     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8863       NewFD->setInvalidDecl();
8864       return Redeclaration;
8865     }
8866 
8867     Previous.clear();
8868     Previous.addDecl(OldDecl);
8869 
8870     if (FunctionTemplateDecl *OldTemplateDecl
8871                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8872       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8873       FunctionTemplateDecl *NewTemplateDecl
8874         = NewFD->getDescribedFunctionTemplate();
8875       assert(NewTemplateDecl && "Template/non-template mismatch");
8876       if (CXXMethodDecl *Method
8877             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8878         Method->setAccess(OldTemplateDecl->getAccess());
8879         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8880       }
8881 
8882       // If this is an explicit specialization of a member that is a function
8883       // template, mark it as a member specialization.
8884       if (IsExplicitSpecialization &&
8885           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8886         NewTemplateDecl->setMemberSpecialization();
8887         assert(OldTemplateDecl->isMemberSpecialization());
8888         // Explicit specializations of a member template do not inherit deleted
8889         // status from the parent member template that they are specializing.
8890         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8891           FunctionDecl *const OldTemplatedDecl =
8892               OldTemplateDecl->getTemplatedDecl();
8893           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8894           OldTemplatedDecl->setDeletedAsWritten(false);
8895         }
8896       }
8897 
8898     } else {
8899       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
8900         // This needs to happen first so that 'inline' propagates.
8901         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8902         if (isa<CXXMethodDecl>(NewFD))
8903           NewFD->setAccess(OldDecl->getAccess());
8904       }
8905     }
8906   }
8907 
8908   // Semantic checking for this function declaration (in isolation).
8909 
8910   if (getLangOpts().CPlusPlus) {
8911     // C++-specific checks.
8912     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8913       CheckConstructor(Constructor);
8914     } else if (CXXDestructorDecl *Destructor =
8915                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8916       CXXRecordDecl *Record = Destructor->getParent();
8917       QualType ClassType = Context.getTypeDeclType(Record);
8918 
8919       // FIXME: Shouldn't we be able to perform this check even when the class
8920       // type is dependent? Both gcc and edg can handle that.
8921       if (!ClassType->isDependentType()) {
8922         DeclarationName Name
8923           = Context.DeclarationNames.getCXXDestructorName(
8924                                         Context.getCanonicalType(ClassType));
8925         if (NewFD->getDeclName() != Name) {
8926           Diag(NewFD->getLocation(), diag::err_destructor_name);
8927           NewFD->setInvalidDecl();
8928           return Redeclaration;
8929         }
8930       }
8931     } else if (CXXConversionDecl *Conversion
8932                = dyn_cast<CXXConversionDecl>(NewFD)) {
8933       ActOnConversionDeclarator(Conversion);
8934     }
8935 
8936     // Find any virtual functions that this function overrides.
8937     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8938       if (!Method->isFunctionTemplateSpecialization() &&
8939           !Method->getDescribedFunctionTemplate() &&
8940           Method->isCanonicalDecl()) {
8941         if (AddOverriddenMethods(Method->getParent(), Method)) {
8942           // If the function was marked as "static", we have a problem.
8943           if (NewFD->getStorageClass() == SC_Static) {
8944             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8945           }
8946         }
8947       }
8948 
8949       if (Method->isStatic())
8950         checkThisInStaticMemberFunctionType(Method);
8951     }
8952 
8953     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8954     if (NewFD->isOverloadedOperator() &&
8955         CheckOverloadedOperatorDeclaration(NewFD)) {
8956       NewFD->setInvalidDecl();
8957       return Redeclaration;
8958     }
8959 
8960     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8961     if (NewFD->getLiteralIdentifier() &&
8962         CheckLiteralOperatorDeclaration(NewFD)) {
8963       NewFD->setInvalidDecl();
8964       return Redeclaration;
8965     }
8966 
8967     // In C++, check default arguments now that we have merged decls. Unless
8968     // the lexical context is the class, because in this case this is done
8969     // during delayed parsing anyway.
8970     if (!CurContext->isRecord())
8971       CheckCXXDefaultArguments(NewFD);
8972 
8973     // If this function declares a builtin function, check the type of this
8974     // declaration against the expected type for the builtin.
8975     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8976       ASTContext::GetBuiltinTypeError Error;
8977       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8978       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8979       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8980         // The type of this function differs from the type of the builtin,
8981         // so forget about the builtin entirely.
8982         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8983       }
8984     }
8985 
8986     // If this function is declared as being extern "C", then check to see if
8987     // the function returns a UDT (class, struct, or union type) that is not C
8988     // compatible, and if it does, warn the user.
8989     // But, issue any diagnostic on the first declaration only.
8990     if (Previous.empty() && NewFD->isExternC()) {
8991       QualType R = NewFD->getReturnType();
8992       if (R->isIncompleteType() && !R->isVoidType())
8993         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8994             << NewFD << R;
8995       else if (!R.isPODType(Context) && !R->isVoidType() &&
8996                !R->isObjCObjectPointerType())
8997         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8998     }
8999 
9000     // C++1z [dcl.fct]p6:
9001     //   [...] whether the function has a non-throwing exception-specification
9002     //   [is] part of the function type
9003     //
9004     // This results in an ABI break between C++14 and C++17 for functions whose
9005     // declared type includes an exception-specification in a parameter or
9006     // return type. (Exception specifications on the function itself are OK in
9007     // most cases, and exception specifications are not permitted in most other
9008     // contexts where they could make it into a mangling.)
9009     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9010       auto HasNoexcept = [&](QualType T) -> bool {
9011         // Strip off declarator chunks that could be between us and a function
9012         // type. We don't need to look far, exception specifications are very
9013         // restricted prior to C++17.
9014         if (auto *RT = T->getAs<ReferenceType>())
9015           T = RT->getPointeeType();
9016         else if (T->isAnyPointerType())
9017           T = T->getPointeeType();
9018         else if (auto *MPT = T->getAs<MemberPointerType>())
9019           T = MPT->getPointeeType();
9020         if (auto *FPT = T->getAs<FunctionProtoType>())
9021           if (FPT->isNothrow(Context))
9022             return true;
9023         return false;
9024       };
9025 
9026       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9027       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9028       for (QualType T : FPT->param_types())
9029         AnyNoexcept |= HasNoexcept(T);
9030       if (AnyNoexcept)
9031         Diag(NewFD->getLocation(),
9032              diag::warn_cxx1z_compat_exception_spec_in_signature)
9033             << NewFD;
9034     }
9035   }
9036   return Redeclaration;
9037 }
9038 
9039 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9040   // C++11 [basic.start.main]p3:
9041   //   A program that [...] declares main to be inline, static or
9042   //   constexpr is ill-formed.
9043   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9044   //   appear in a declaration of main.
9045   // static main is not an error under C99, but we should warn about it.
9046   // We accept _Noreturn main as an extension.
9047   if (FD->getStorageClass() == SC_Static)
9048     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9049          ? diag::err_static_main : diag::warn_static_main)
9050       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9051   if (FD->isInlineSpecified())
9052     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9053       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9054   if (DS.isNoreturnSpecified()) {
9055     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9056     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9057     Diag(NoreturnLoc, diag::ext_noreturn_main);
9058     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9059       << FixItHint::CreateRemoval(NoreturnRange);
9060   }
9061   if (FD->isConstexpr()) {
9062     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9063       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9064     FD->setConstexpr(false);
9065   }
9066 
9067   if (getLangOpts().OpenCL) {
9068     Diag(FD->getLocation(), diag::err_opencl_no_main)
9069         << FD->hasAttr<OpenCLKernelAttr>();
9070     FD->setInvalidDecl();
9071     return;
9072   }
9073 
9074   QualType T = FD->getType();
9075   assert(T->isFunctionType() && "function decl is not of function type");
9076   const FunctionType* FT = T->castAs<FunctionType>();
9077 
9078   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9079     // In C with GNU extensions we allow main() to have non-integer return
9080     // type, but we should warn about the extension, and we disable the
9081     // implicit-return-zero rule.
9082 
9083     // GCC in C mode accepts qualified 'int'.
9084     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9085       FD->setHasImplicitReturnZero(true);
9086     else {
9087       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9088       SourceRange RTRange = FD->getReturnTypeSourceRange();
9089       if (RTRange.isValid())
9090         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9091             << FixItHint::CreateReplacement(RTRange, "int");
9092     }
9093   } else {
9094     // In C and C++, main magically returns 0 if you fall off the end;
9095     // set the flag which tells us that.
9096     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9097 
9098     // All the standards say that main() should return 'int'.
9099     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9100       FD->setHasImplicitReturnZero(true);
9101     else {
9102       // Otherwise, this is just a flat-out error.
9103       SourceRange RTRange = FD->getReturnTypeSourceRange();
9104       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9105           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9106                                 : FixItHint());
9107       FD->setInvalidDecl(true);
9108     }
9109   }
9110 
9111   // Treat protoless main() as nullary.
9112   if (isa<FunctionNoProtoType>(FT)) return;
9113 
9114   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9115   unsigned nparams = FTP->getNumParams();
9116   assert(FD->getNumParams() == nparams);
9117 
9118   bool HasExtraParameters = (nparams > 3);
9119 
9120   if (FTP->isVariadic()) {
9121     Diag(FD->getLocation(), diag::ext_variadic_main);
9122     // FIXME: if we had information about the location of the ellipsis, we
9123     // could add a FixIt hint to remove it as a parameter.
9124   }
9125 
9126   // Darwin passes an undocumented fourth argument of type char**.  If
9127   // other platforms start sprouting these, the logic below will start
9128   // getting shifty.
9129   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9130     HasExtraParameters = false;
9131 
9132   if (HasExtraParameters) {
9133     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9134     FD->setInvalidDecl(true);
9135     nparams = 3;
9136   }
9137 
9138   // FIXME: a lot of the following diagnostics would be improved
9139   // if we had some location information about types.
9140 
9141   QualType CharPP =
9142     Context.getPointerType(Context.getPointerType(Context.CharTy));
9143   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9144 
9145   for (unsigned i = 0; i < nparams; ++i) {
9146     QualType AT = FTP->getParamType(i);
9147 
9148     bool mismatch = true;
9149 
9150     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9151       mismatch = false;
9152     else if (Expected[i] == CharPP) {
9153       // As an extension, the following forms are okay:
9154       //   char const **
9155       //   char const * const *
9156       //   char * const *
9157 
9158       QualifierCollector qs;
9159       const PointerType* PT;
9160       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9161           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9162           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9163                               Context.CharTy)) {
9164         qs.removeConst();
9165         mismatch = !qs.empty();
9166       }
9167     }
9168 
9169     if (mismatch) {
9170       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9171       // TODO: suggest replacing given type with expected type
9172       FD->setInvalidDecl(true);
9173     }
9174   }
9175 
9176   if (nparams == 1 && !FD->isInvalidDecl()) {
9177     Diag(FD->getLocation(), diag::warn_main_one_arg);
9178   }
9179 
9180   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9181     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9182     FD->setInvalidDecl();
9183   }
9184 }
9185 
9186 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9187   QualType T = FD->getType();
9188   assert(T->isFunctionType() && "function decl is not of function type");
9189   const FunctionType *FT = T->castAs<FunctionType>();
9190 
9191   // Set an implicit return of 'zero' if the function can return some integral,
9192   // enumeration, pointer or nullptr type.
9193   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9194       FT->getReturnType()->isAnyPointerType() ||
9195       FT->getReturnType()->isNullPtrType())
9196     // DllMain is exempt because a return value of zero means it failed.
9197     if (FD->getName() != "DllMain")
9198       FD->setHasImplicitReturnZero(true);
9199 
9200   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9201     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9202     FD->setInvalidDecl();
9203   }
9204 }
9205 
9206 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9207   // FIXME: Need strict checking.  In C89, we need to check for
9208   // any assignment, increment, decrement, function-calls, or
9209   // commas outside of a sizeof.  In C99, it's the same list,
9210   // except that the aforementioned are allowed in unevaluated
9211   // expressions.  Everything else falls under the
9212   // "may accept other forms of constant expressions" exception.
9213   // (We never end up here for C++, so the constant expression
9214   // rules there don't matter.)
9215   const Expr *Culprit;
9216   if (Init->isConstantInitializer(Context, false, &Culprit))
9217     return false;
9218   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9219     << Culprit->getSourceRange();
9220   return true;
9221 }
9222 
9223 namespace {
9224   // Visits an initialization expression to see if OrigDecl is evaluated in
9225   // its own initialization and throws a warning if it does.
9226   class SelfReferenceChecker
9227       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9228     Sema &S;
9229     Decl *OrigDecl;
9230     bool isRecordType;
9231     bool isPODType;
9232     bool isReferenceType;
9233 
9234     bool isInitList;
9235     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9236 
9237   public:
9238     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9239 
9240     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9241                                                     S(S), OrigDecl(OrigDecl) {
9242       isPODType = false;
9243       isRecordType = false;
9244       isReferenceType = false;
9245       isInitList = false;
9246       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9247         isPODType = VD->getType().isPODType(S.Context);
9248         isRecordType = VD->getType()->isRecordType();
9249         isReferenceType = VD->getType()->isReferenceType();
9250       }
9251     }
9252 
9253     // For most expressions, just call the visitor.  For initializer lists,
9254     // track the index of the field being initialized since fields are
9255     // initialized in order allowing use of previously initialized fields.
9256     void CheckExpr(Expr *E) {
9257       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9258       if (!InitList) {
9259         Visit(E);
9260         return;
9261       }
9262 
9263       // Track and increment the index here.
9264       isInitList = true;
9265       InitFieldIndex.push_back(0);
9266       for (auto Child : InitList->children()) {
9267         CheckExpr(cast<Expr>(Child));
9268         ++InitFieldIndex.back();
9269       }
9270       InitFieldIndex.pop_back();
9271     }
9272 
9273     // Returns true if MemberExpr is checked and no futher checking is needed.
9274     // Returns false if additional checking is required.
9275     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9276       llvm::SmallVector<FieldDecl*, 4> Fields;
9277       Expr *Base = E;
9278       bool ReferenceField = false;
9279 
9280       // Get the field memebers used.
9281       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9282         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9283         if (!FD)
9284           return false;
9285         Fields.push_back(FD);
9286         if (FD->getType()->isReferenceType())
9287           ReferenceField = true;
9288         Base = ME->getBase()->IgnoreParenImpCasts();
9289       }
9290 
9291       // Keep checking only if the base Decl is the same.
9292       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9293       if (!DRE || DRE->getDecl() != OrigDecl)
9294         return false;
9295 
9296       // A reference field can be bound to an unininitialized field.
9297       if (CheckReference && !ReferenceField)
9298         return true;
9299 
9300       // Convert FieldDecls to their index number.
9301       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9302       for (const FieldDecl *I : llvm::reverse(Fields))
9303         UsedFieldIndex.push_back(I->getFieldIndex());
9304 
9305       // See if a warning is needed by checking the first difference in index
9306       // numbers.  If field being used has index less than the field being
9307       // initialized, then the use is safe.
9308       for (auto UsedIter = UsedFieldIndex.begin(),
9309                 UsedEnd = UsedFieldIndex.end(),
9310                 OrigIter = InitFieldIndex.begin(),
9311                 OrigEnd = InitFieldIndex.end();
9312            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9313         if (*UsedIter < *OrigIter)
9314           return true;
9315         if (*UsedIter > *OrigIter)
9316           break;
9317       }
9318 
9319       // TODO: Add a different warning which will print the field names.
9320       HandleDeclRefExpr(DRE);
9321       return true;
9322     }
9323 
9324     // For most expressions, the cast is directly above the DeclRefExpr.
9325     // For conditional operators, the cast can be outside the conditional
9326     // operator if both expressions are DeclRefExpr's.
9327     void HandleValue(Expr *E) {
9328       E = E->IgnoreParens();
9329       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9330         HandleDeclRefExpr(DRE);
9331         return;
9332       }
9333 
9334       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9335         Visit(CO->getCond());
9336         HandleValue(CO->getTrueExpr());
9337         HandleValue(CO->getFalseExpr());
9338         return;
9339       }
9340 
9341       if (BinaryConditionalOperator *BCO =
9342               dyn_cast<BinaryConditionalOperator>(E)) {
9343         Visit(BCO->getCond());
9344         HandleValue(BCO->getFalseExpr());
9345         return;
9346       }
9347 
9348       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9349         HandleValue(OVE->getSourceExpr());
9350         return;
9351       }
9352 
9353       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9354         if (BO->getOpcode() == BO_Comma) {
9355           Visit(BO->getLHS());
9356           HandleValue(BO->getRHS());
9357           return;
9358         }
9359       }
9360 
9361       if (isa<MemberExpr>(E)) {
9362         if (isInitList) {
9363           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9364                                       false /*CheckReference*/))
9365             return;
9366         }
9367 
9368         Expr *Base = E->IgnoreParenImpCasts();
9369         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9370           // Check for static member variables and don't warn on them.
9371           if (!isa<FieldDecl>(ME->getMemberDecl()))
9372             return;
9373           Base = ME->getBase()->IgnoreParenImpCasts();
9374         }
9375         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9376           HandleDeclRefExpr(DRE);
9377         return;
9378       }
9379 
9380       Visit(E);
9381     }
9382 
9383     // Reference types not handled in HandleValue are handled here since all
9384     // uses of references are bad, not just r-value uses.
9385     void VisitDeclRefExpr(DeclRefExpr *E) {
9386       if (isReferenceType)
9387         HandleDeclRefExpr(E);
9388     }
9389 
9390     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9391       if (E->getCastKind() == CK_LValueToRValue) {
9392         HandleValue(E->getSubExpr());
9393         return;
9394       }
9395 
9396       Inherited::VisitImplicitCastExpr(E);
9397     }
9398 
9399     void VisitMemberExpr(MemberExpr *E) {
9400       if (isInitList) {
9401         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9402           return;
9403       }
9404 
9405       // Don't warn on arrays since they can be treated as pointers.
9406       if (E->getType()->canDecayToPointerType()) return;
9407 
9408       // Warn when a non-static method call is followed by non-static member
9409       // field accesses, which is followed by a DeclRefExpr.
9410       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9411       bool Warn = (MD && !MD->isStatic());
9412       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9413       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9414         if (!isa<FieldDecl>(ME->getMemberDecl()))
9415           Warn = false;
9416         Base = ME->getBase()->IgnoreParenImpCasts();
9417       }
9418 
9419       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9420         if (Warn)
9421           HandleDeclRefExpr(DRE);
9422         return;
9423       }
9424 
9425       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9426       // Visit that expression.
9427       Visit(Base);
9428     }
9429 
9430     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9431       Expr *Callee = E->getCallee();
9432 
9433       if (isa<UnresolvedLookupExpr>(Callee))
9434         return Inherited::VisitCXXOperatorCallExpr(E);
9435 
9436       Visit(Callee);
9437       for (auto Arg: E->arguments())
9438         HandleValue(Arg->IgnoreParenImpCasts());
9439     }
9440 
9441     void VisitUnaryOperator(UnaryOperator *E) {
9442       // For POD record types, addresses of its own members are well-defined.
9443       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9444           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9445         if (!isPODType)
9446           HandleValue(E->getSubExpr());
9447         return;
9448       }
9449 
9450       if (E->isIncrementDecrementOp()) {
9451         HandleValue(E->getSubExpr());
9452         return;
9453       }
9454 
9455       Inherited::VisitUnaryOperator(E);
9456     }
9457 
9458     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9459 
9460     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9461       if (E->getConstructor()->isCopyConstructor()) {
9462         Expr *ArgExpr = E->getArg(0);
9463         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9464           if (ILE->getNumInits() == 1)
9465             ArgExpr = ILE->getInit(0);
9466         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9467           if (ICE->getCastKind() == CK_NoOp)
9468             ArgExpr = ICE->getSubExpr();
9469         HandleValue(ArgExpr);
9470         return;
9471       }
9472       Inherited::VisitCXXConstructExpr(E);
9473     }
9474 
9475     void VisitCallExpr(CallExpr *E) {
9476       // Treat std::move as a use.
9477       if (E->getNumArgs() == 1) {
9478         if (FunctionDecl *FD = E->getDirectCallee()) {
9479           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9480               FD->getIdentifier()->isStr("move")) {
9481             HandleValue(E->getArg(0));
9482             return;
9483           }
9484         }
9485       }
9486 
9487       Inherited::VisitCallExpr(E);
9488     }
9489 
9490     void VisitBinaryOperator(BinaryOperator *E) {
9491       if (E->isCompoundAssignmentOp()) {
9492         HandleValue(E->getLHS());
9493         Visit(E->getRHS());
9494         return;
9495       }
9496 
9497       Inherited::VisitBinaryOperator(E);
9498     }
9499 
9500     // A custom visitor for BinaryConditionalOperator is needed because the
9501     // regular visitor would check the condition and true expression separately
9502     // but both point to the same place giving duplicate diagnostics.
9503     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9504       Visit(E->getCond());
9505       Visit(E->getFalseExpr());
9506     }
9507 
9508     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9509       Decl* ReferenceDecl = DRE->getDecl();
9510       if (OrigDecl != ReferenceDecl) return;
9511       unsigned diag;
9512       if (isReferenceType) {
9513         diag = diag::warn_uninit_self_reference_in_reference_init;
9514       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9515         diag = diag::warn_static_self_reference_in_init;
9516       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9517                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9518                  DRE->getDecl()->getType()->isRecordType()) {
9519         diag = diag::warn_uninit_self_reference_in_init;
9520       } else {
9521         // Local variables will be handled by the CFG analysis.
9522         return;
9523       }
9524 
9525       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9526                             S.PDiag(diag)
9527                               << DRE->getNameInfo().getName()
9528                               << OrigDecl->getLocation()
9529                               << DRE->getSourceRange());
9530     }
9531   };
9532 
9533   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9534   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9535                                  bool DirectInit) {
9536     // Parameters arguments are occassionially constructed with itself,
9537     // for instance, in recursive functions.  Skip them.
9538     if (isa<ParmVarDecl>(OrigDecl))
9539       return;
9540 
9541     E = E->IgnoreParens();
9542 
9543     // Skip checking T a = a where T is not a record or reference type.
9544     // Doing so is a way to silence uninitialized warnings.
9545     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9546       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9547         if (ICE->getCastKind() == CK_LValueToRValue)
9548           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9549             if (DRE->getDecl() == OrigDecl)
9550               return;
9551 
9552     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9553   }
9554 } // end anonymous namespace
9555 
9556 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9557                                             DeclarationName Name, QualType Type,
9558                                             TypeSourceInfo *TSI,
9559                                             SourceRange Range, bool DirectInit,
9560                                             Expr *Init) {
9561   bool IsInitCapture = !VDecl;
9562   assert((!VDecl || !VDecl->isInitCapture()) &&
9563          "init captures are expected to be deduced prior to initialization");
9564 
9565   // FIXME: Deduction for a decomposition declaration does weird things if the
9566   // initializer is an array.
9567 
9568   ArrayRef<Expr *> DeduceInits = Init;
9569   if (DirectInit) {
9570     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9571       DeduceInits = PL->exprs();
9572     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9573       DeduceInits = IL->inits();
9574   }
9575 
9576   // Deduction only works if we have exactly one source expression.
9577   if (DeduceInits.empty()) {
9578     // It isn't possible to write this directly, but it is possible to
9579     // end up in this situation with "auto x(some_pack...);"
9580     Diag(Init->getLocStart(), IsInitCapture
9581                                   ? diag::err_init_capture_no_expression
9582                                   : diag::err_auto_var_init_no_expression)
9583         << Name << Type << Range;
9584     return QualType();
9585   }
9586 
9587   if (DeduceInits.size() > 1) {
9588     Diag(DeduceInits[1]->getLocStart(),
9589          IsInitCapture ? diag::err_init_capture_multiple_expressions
9590                        : diag::err_auto_var_init_multiple_expressions)
9591         << Name << Type << Range;
9592     return QualType();
9593   }
9594 
9595   Expr *DeduceInit = DeduceInits[0];
9596   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9597     Diag(Init->getLocStart(), IsInitCapture
9598                                   ? diag::err_init_capture_paren_braces
9599                                   : diag::err_auto_var_init_paren_braces)
9600         << isa<InitListExpr>(Init) << Name << Type << Range;
9601     return QualType();
9602   }
9603 
9604   // Expressions default to 'id' when we're in a debugger.
9605   bool DefaultedAnyToId = false;
9606   if (getLangOpts().DebuggerCastResultToId &&
9607       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9608     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9609     if (Result.isInvalid()) {
9610       return QualType();
9611     }
9612     Init = Result.get();
9613     DefaultedAnyToId = true;
9614   }
9615 
9616   QualType DeducedType;
9617   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9618     if (!IsInitCapture)
9619       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9620     else if (isa<InitListExpr>(Init))
9621       Diag(Range.getBegin(),
9622            diag::err_init_capture_deduction_failure_from_init_list)
9623           << Name
9624           << (DeduceInit->getType().isNull() ? TSI->getType()
9625                                              : DeduceInit->getType())
9626           << DeduceInit->getSourceRange();
9627     else
9628       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9629           << Name << TSI->getType()
9630           << (DeduceInit->getType().isNull() ? TSI->getType()
9631                                              : DeduceInit->getType())
9632           << DeduceInit->getSourceRange();
9633   }
9634 
9635   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9636   // 'id' instead of a specific object type prevents most of our usual
9637   // checks.
9638   // We only want to warn outside of template instantiations, though:
9639   // inside a template, the 'id' could have come from a parameter.
9640   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9641       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9642     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9643     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9644   }
9645 
9646   return DeducedType;
9647 }
9648 
9649 /// AddInitializerToDecl - Adds the initializer Init to the
9650 /// declaration dcl. If DirectInit is true, this is C++ direct
9651 /// initialization rather than copy initialization.
9652 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9653                                 bool DirectInit, bool TypeMayContainAuto) {
9654   // If there is no declaration, there was an error parsing it.  Just ignore
9655   // the initializer.
9656   if (!RealDecl || RealDecl->isInvalidDecl()) {
9657     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9658     return;
9659   }
9660 
9661   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9662     // Pure-specifiers are handled in ActOnPureSpecifier.
9663     Diag(Method->getLocation(), diag::err_member_function_initialization)
9664       << Method->getDeclName() << Init->getSourceRange();
9665     Method->setInvalidDecl();
9666     return;
9667   }
9668 
9669   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9670   if (!VDecl) {
9671     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9672     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9673     RealDecl->setInvalidDecl();
9674     return;
9675   }
9676 
9677   // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not
9678   // permitted.
9679   if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init))
9680     Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl;
9681 
9682   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9683   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9684     // Attempt typo correction early so that the type of the init expression can
9685     // be deduced based on the chosen correction if the original init contains a
9686     // TypoExpr.
9687     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9688     if (!Res.isUsable()) {
9689       RealDecl->setInvalidDecl();
9690       return;
9691     }
9692     Init = Res.get();
9693 
9694     QualType DeducedType = deduceVarTypeFromInitializer(
9695         VDecl, VDecl->getDeclName(), VDecl->getType(),
9696         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9697     if (DeducedType.isNull()) {
9698       RealDecl->setInvalidDecl();
9699       return;
9700     }
9701 
9702     VDecl->setType(DeducedType);
9703     assert(VDecl->isLinkageValid());
9704 
9705     // In ARC, infer lifetime.
9706     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9707       VDecl->setInvalidDecl();
9708 
9709     // If this is a redeclaration, check that the type we just deduced matches
9710     // the previously declared type.
9711     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9712       // We never need to merge the type, because we cannot form an incomplete
9713       // array of auto, nor deduce such a type.
9714       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9715     }
9716 
9717     // Check the deduced type is valid for a variable declaration.
9718     CheckVariableDeclarationType(VDecl);
9719     if (VDecl->isInvalidDecl())
9720       return;
9721   }
9722 
9723   // dllimport cannot be used on variable definitions.
9724   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9725     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9726     VDecl->setInvalidDecl();
9727     return;
9728   }
9729 
9730   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9731     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9732     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9733     VDecl->setInvalidDecl();
9734     return;
9735   }
9736 
9737   if (!VDecl->getType()->isDependentType()) {
9738     // A definition must end up with a complete type, which means it must be
9739     // complete with the restriction that an array type might be completed by
9740     // the initializer; note that later code assumes this restriction.
9741     QualType BaseDeclType = VDecl->getType();
9742     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9743       BaseDeclType = Array->getElementType();
9744     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9745                             diag::err_typecheck_decl_incomplete_type)) {
9746       RealDecl->setInvalidDecl();
9747       return;
9748     }
9749 
9750     // The variable can not have an abstract class type.
9751     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9752                                diag::err_abstract_type_in_decl,
9753                                AbstractVariableType))
9754       VDecl->setInvalidDecl();
9755   }
9756 
9757   // If adding the initializer will turn this declaration into a definition,
9758   // and we already have a definition for this variable, diagnose or otherwise
9759   // handle the situation.
9760   VarDecl *Def;
9761   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9762       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
9763       !VDecl->isThisDeclarationADemotedDefinition() &&
9764       checkVarDeclRedefinition(Def, VDecl))
9765     return;
9766 
9767   if (getLangOpts().CPlusPlus) {
9768     // C++ [class.static.data]p4
9769     //   If a static data member is of const integral or const
9770     //   enumeration type, its declaration in the class definition can
9771     //   specify a constant-initializer which shall be an integral
9772     //   constant expression (5.19). In that case, the member can appear
9773     //   in integral constant expressions. The member shall still be
9774     //   defined in a namespace scope if it is used in the program and the
9775     //   namespace scope definition shall not contain an initializer.
9776     //
9777     // We already performed a redefinition check above, but for static
9778     // data members we also need to check whether there was an in-class
9779     // declaration with an initializer.
9780     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9781       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9782           << VDecl->getDeclName();
9783       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9784            diag::note_previous_initializer)
9785           << 0;
9786       return;
9787     }
9788 
9789     if (VDecl->hasLocalStorage())
9790       getCurFunction()->setHasBranchProtectedScope();
9791 
9792     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9793       VDecl->setInvalidDecl();
9794       return;
9795     }
9796   }
9797 
9798   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9799   // a kernel function cannot be initialized."
9800   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9801     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9802     VDecl->setInvalidDecl();
9803     return;
9804   }
9805 
9806   // Get the decls type and save a reference for later, since
9807   // CheckInitializerTypes may change it.
9808   QualType DclT = VDecl->getType(), SavT = DclT;
9809 
9810   // Expressions default to 'id' when we're in a debugger
9811   // and we are assigning it to a variable of Objective-C pointer type.
9812   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9813       Init->getType() == Context.UnknownAnyTy) {
9814     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9815     if (Result.isInvalid()) {
9816       VDecl->setInvalidDecl();
9817       return;
9818     }
9819     Init = Result.get();
9820   }
9821 
9822   // Perform the initialization.
9823   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9824   if (!VDecl->isInvalidDecl()) {
9825     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9826     InitializationKind Kind =
9827         DirectInit
9828             ? CXXDirectInit
9829                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9830                                                      Init->getLocStart(),
9831                                                      Init->getLocEnd())
9832                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9833             : InitializationKind::CreateCopy(VDecl->getLocation(),
9834                                              Init->getLocStart());
9835 
9836     MultiExprArg Args = Init;
9837     if (CXXDirectInit)
9838       Args = MultiExprArg(CXXDirectInit->getExprs(),
9839                           CXXDirectInit->getNumExprs());
9840 
9841     // Try to correct any TypoExprs in the initialization arguments.
9842     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9843       ExprResult Res = CorrectDelayedTyposInExpr(
9844           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9845             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9846             return Init.Failed() ? ExprError() : E;
9847           });
9848       if (Res.isInvalid()) {
9849         VDecl->setInvalidDecl();
9850       } else if (Res.get() != Args[Idx]) {
9851         Args[Idx] = Res.get();
9852       }
9853     }
9854     if (VDecl->isInvalidDecl())
9855       return;
9856 
9857     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9858                                    /*TopLevelOfInitList=*/false,
9859                                    /*TreatUnavailableAsInvalid=*/false);
9860     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9861     if (Result.isInvalid()) {
9862       VDecl->setInvalidDecl();
9863       return;
9864     }
9865 
9866     Init = Result.getAs<Expr>();
9867   }
9868 
9869   // Check for self-references within variable initializers.
9870   // Variables declared within a function/method body (except for references)
9871   // are handled by a dataflow analysis.
9872   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9873       VDecl->getType()->isReferenceType()) {
9874     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9875   }
9876 
9877   // If the type changed, it means we had an incomplete type that was
9878   // completed by the initializer. For example:
9879   //   int ary[] = { 1, 3, 5 };
9880   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9881   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9882     VDecl->setType(DclT);
9883 
9884   if (!VDecl->isInvalidDecl()) {
9885     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9886 
9887     if (VDecl->hasAttr<BlocksAttr>())
9888       checkRetainCycles(VDecl, Init);
9889 
9890     // It is safe to assign a weak reference into a strong variable.
9891     // Although this code can still have problems:
9892     //   id x = self.weakProp;
9893     //   id y = self.weakProp;
9894     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9895     // paths through the function. This should be revisited if
9896     // -Wrepeated-use-of-weak is made flow-sensitive.
9897     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9898         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9899                          Init->getLocStart()))
9900       getCurFunction()->markSafeWeakUse(Init);
9901   }
9902 
9903   // The initialization is usually a full-expression.
9904   //
9905   // FIXME: If this is a braced initialization of an aggregate, it is not
9906   // an expression, and each individual field initializer is a separate
9907   // full-expression. For instance, in:
9908   //
9909   //   struct Temp { ~Temp(); };
9910   //   struct S { S(Temp); };
9911   //   struct T { S a, b; } t = { Temp(), Temp() }
9912   //
9913   // we should destroy the first Temp before constructing the second.
9914   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9915                                           false,
9916                                           VDecl->isConstexpr());
9917   if (Result.isInvalid()) {
9918     VDecl->setInvalidDecl();
9919     return;
9920   }
9921   Init = Result.get();
9922 
9923   // Attach the initializer to the decl.
9924   VDecl->setInit(Init);
9925 
9926   if (VDecl->isLocalVarDecl()) {
9927     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9928     // static storage duration shall be constant expressions or string literals.
9929     // C++ does not have this restriction.
9930     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9931       const Expr *Culprit;
9932       if (VDecl->getStorageClass() == SC_Static)
9933         CheckForConstantInitializer(Init, DclT);
9934       // C89 is stricter than C99 for non-static aggregate types.
9935       // C89 6.5.7p3: All the expressions [...] in an initializer list
9936       // for an object that has aggregate or union type shall be
9937       // constant expressions.
9938       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9939                isa<InitListExpr>(Init) &&
9940                !Init->isConstantInitializer(Context, false, &Culprit))
9941         Diag(Culprit->getExprLoc(),
9942              diag::ext_aggregate_init_not_constant)
9943           << Culprit->getSourceRange();
9944     }
9945   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
9946              VDecl->getLexicalDeclContext()->isRecord()) {
9947     // This is an in-class initialization for a static data member, e.g.,
9948     //
9949     // struct S {
9950     //   static const int value = 17;
9951     // };
9952 
9953     // C++ [class.mem]p4:
9954     //   A member-declarator can contain a constant-initializer only
9955     //   if it declares a static member (9.4) of const integral or
9956     //   const enumeration type, see 9.4.2.
9957     //
9958     // C++11 [class.static.data]p3:
9959     //   If a non-volatile non-inline const static data member is of integral
9960     //   or enumeration type, its declaration in the class definition can
9961     //   specify a brace-or-equal-initializer in which every initalizer-clause
9962     //   that is an assignment-expression is a constant expression. A static
9963     //   data member of literal type can be declared in the class definition
9964     //   with the constexpr specifier; if so, its declaration shall specify a
9965     //   brace-or-equal-initializer in which every initializer-clause that is
9966     //   an assignment-expression is a constant expression.
9967 
9968     // Do nothing on dependent types.
9969     if (DclT->isDependentType()) {
9970 
9971     // Allow any 'static constexpr' members, whether or not they are of literal
9972     // type. We separately check that every constexpr variable is of literal
9973     // type.
9974     } else if (VDecl->isConstexpr()) {
9975 
9976     // Require constness.
9977     } else if (!DclT.isConstQualified()) {
9978       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9979         << Init->getSourceRange();
9980       VDecl->setInvalidDecl();
9981 
9982     // We allow integer constant expressions in all cases.
9983     } else if (DclT->isIntegralOrEnumerationType()) {
9984       // Check whether the expression is a constant expression.
9985       SourceLocation Loc;
9986       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9987         // In C++11, a non-constexpr const static data member with an
9988         // in-class initializer cannot be volatile.
9989         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9990       else if (Init->isValueDependent())
9991         ; // Nothing to check.
9992       else if (Init->isIntegerConstantExpr(Context, &Loc))
9993         ; // Ok, it's an ICE!
9994       else if (Init->isEvaluatable(Context)) {
9995         // If we can constant fold the initializer through heroics, accept it,
9996         // but report this as a use of an extension for -pedantic.
9997         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9998           << Init->getSourceRange();
9999       } else {
10000         // Otherwise, this is some crazy unknown case.  Report the issue at the
10001         // location provided by the isIntegerConstantExpr failed check.
10002         Diag(Loc, diag::err_in_class_initializer_non_constant)
10003           << Init->getSourceRange();
10004         VDecl->setInvalidDecl();
10005       }
10006 
10007     // We allow foldable floating-point constants as an extension.
10008     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10009       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10010       // it anyway and provide a fixit to add the 'constexpr'.
10011       if (getLangOpts().CPlusPlus11) {
10012         Diag(VDecl->getLocation(),
10013              diag::ext_in_class_initializer_float_type_cxx11)
10014             << DclT << Init->getSourceRange();
10015         Diag(VDecl->getLocStart(),
10016              diag::note_in_class_initializer_float_type_cxx11)
10017             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10018       } else {
10019         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10020           << DclT << Init->getSourceRange();
10021 
10022         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10023           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10024             << Init->getSourceRange();
10025           VDecl->setInvalidDecl();
10026         }
10027       }
10028 
10029     // Suggest adding 'constexpr' in C++11 for literal types.
10030     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10031       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10032         << DclT << Init->getSourceRange()
10033         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10034       VDecl->setConstexpr(true);
10035 
10036     } else {
10037       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10038         << DclT << Init->getSourceRange();
10039       VDecl->setInvalidDecl();
10040     }
10041   } else if (VDecl->isFileVarDecl()) {
10042     // In C, extern is typically used to avoid tentative definitions when
10043     // declaring variables in headers, but adding an intializer makes it a
10044     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10045     // In C++, extern is often used to give implictly static const variables
10046     // external linkage, so don't warn in that case. If selectany is present,
10047     // this might be header code intended for C and C++ inclusion, so apply the
10048     // C++ rules.
10049     if (VDecl->getStorageClass() == SC_Extern &&
10050         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10051          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10052         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10053         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10054       Diag(VDecl->getLocation(), diag::warn_extern_init);
10055 
10056     // C99 6.7.8p4. All file scoped initializers need to be constant.
10057     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10058       CheckForConstantInitializer(Init, DclT);
10059   }
10060 
10061   // We will represent direct-initialization similarly to copy-initialization:
10062   //    int x(1);  -as-> int x = 1;
10063   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10064   //
10065   // Clients that want to distinguish between the two forms, can check for
10066   // direct initializer using VarDecl::getInitStyle().
10067   // A major benefit is that clients that don't particularly care about which
10068   // exactly form was it (like the CodeGen) can handle both cases without
10069   // special case code.
10070 
10071   // C++ 8.5p11:
10072   // The form of initialization (using parentheses or '=') is generally
10073   // insignificant, but does matter when the entity being initialized has a
10074   // class type.
10075   if (CXXDirectInit) {
10076     assert(DirectInit && "Call-style initializer must be direct init.");
10077     VDecl->setInitStyle(VarDecl::CallInit);
10078   } else if (DirectInit) {
10079     // This must be list-initialization. No other way is direct-initialization.
10080     VDecl->setInitStyle(VarDecl::ListInit);
10081   }
10082 
10083   CheckCompleteVariableDeclaration(VDecl);
10084 }
10085 
10086 /// ActOnInitializerError - Given that there was an error parsing an
10087 /// initializer for the given declaration, try to return to some form
10088 /// of sanity.
10089 void Sema::ActOnInitializerError(Decl *D) {
10090   // Our main concern here is re-establishing invariants like "a
10091   // variable's type is either dependent or complete".
10092   if (!D || D->isInvalidDecl()) return;
10093 
10094   VarDecl *VD = dyn_cast<VarDecl>(D);
10095   if (!VD) return;
10096 
10097   // Bindings are not usable if we can't make sense of the initializer.
10098   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10099     for (auto *BD : DD->bindings())
10100       BD->setInvalidDecl();
10101 
10102   // Auto types are meaningless if we can't make sense of the initializer.
10103   if (ParsingInitForAutoVars.count(D)) {
10104     D->setInvalidDecl();
10105     return;
10106   }
10107 
10108   QualType Ty = VD->getType();
10109   if (Ty->isDependentType()) return;
10110 
10111   // Require a complete type.
10112   if (RequireCompleteType(VD->getLocation(),
10113                           Context.getBaseElementType(Ty),
10114                           diag::err_typecheck_decl_incomplete_type)) {
10115     VD->setInvalidDecl();
10116     return;
10117   }
10118 
10119   // Require a non-abstract type.
10120   if (RequireNonAbstractType(VD->getLocation(), Ty,
10121                              diag::err_abstract_type_in_decl,
10122                              AbstractVariableType)) {
10123     VD->setInvalidDecl();
10124     return;
10125   }
10126 
10127   // Don't bother complaining about constructors or destructors,
10128   // though.
10129 }
10130 
10131 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
10132                                   bool TypeMayContainAuto) {
10133   // If there is no declaration, there was an error parsing it. Just ignore it.
10134   if (!RealDecl)
10135     return;
10136 
10137   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10138     QualType Type = Var->getType();
10139 
10140     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10141     if (isa<DecompositionDecl>(RealDecl)) {
10142       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10143       Var->setInvalidDecl();
10144       return;
10145     }
10146 
10147     // C++11 [dcl.spec.auto]p3
10148     if (TypeMayContainAuto && Type->getContainedAutoType()) {
10149       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10150         << Var->getDeclName() << Type;
10151       Var->setInvalidDecl();
10152       return;
10153     }
10154 
10155     // C++11 [class.static.data]p3: A static data member can be declared with
10156     // the constexpr specifier; if so, its declaration shall specify
10157     // a brace-or-equal-initializer.
10158     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10159     // the definition of a variable [...] or the declaration of a static data
10160     // member.
10161     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10162         !Var->isThisDeclarationADemotedDefinition()) {
10163       if (Var->isStaticDataMember()) {
10164         // C++1z removes the relevant rule; the in-class declaration is always
10165         // a definition there.
10166         if (!getLangOpts().CPlusPlus1z) {
10167           Diag(Var->getLocation(),
10168                diag::err_constexpr_static_mem_var_requires_init)
10169             << Var->getDeclName();
10170           Var->setInvalidDecl();
10171           return;
10172         }
10173       } else {
10174         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10175         Var->setInvalidDecl();
10176         return;
10177       }
10178     }
10179 
10180     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10181     // definition having the concept specifier is called a variable concept. A
10182     // concept definition refers to [...] a variable concept and its initializer.
10183     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10184       if (VTD->isConcept()) {
10185         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10186         Var->setInvalidDecl();
10187         return;
10188       }
10189     }
10190 
10191     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10192     // be initialized.
10193     if (!Var->isInvalidDecl() &&
10194         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10195         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10196       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10197       Var->setInvalidDecl();
10198       return;
10199     }
10200 
10201     switch (Var->isThisDeclarationADefinition()) {
10202     case VarDecl::Definition:
10203       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10204         break;
10205 
10206       // We have an out-of-line definition of a static data member
10207       // that has an in-class initializer, so we type-check this like
10208       // a declaration.
10209       //
10210       // Fall through
10211 
10212     case VarDecl::DeclarationOnly:
10213       // It's only a declaration.
10214 
10215       // Block scope. C99 6.7p7: If an identifier for an object is
10216       // declared with no linkage (C99 6.2.2p6), the type for the
10217       // object shall be complete.
10218       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10219           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10220           RequireCompleteType(Var->getLocation(), Type,
10221                               diag::err_typecheck_decl_incomplete_type))
10222         Var->setInvalidDecl();
10223 
10224       // Make sure that the type is not abstract.
10225       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10226           RequireNonAbstractType(Var->getLocation(), Type,
10227                                  diag::err_abstract_type_in_decl,
10228                                  AbstractVariableType))
10229         Var->setInvalidDecl();
10230       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10231           Var->getStorageClass() == SC_PrivateExtern) {
10232         Diag(Var->getLocation(), diag::warn_private_extern);
10233         Diag(Var->getLocation(), diag::note_private_extern);
10234       }
10235 
10236       return;
10237 
10238     case VarDecl::TentativeDefinition:
10239       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10240       // object that has file scope without an initializer, and without a
10241       // storage-class specifier or with the storage-class specifier "static",
10242       // constitutes a tentative definition. Note: A tentative definition with
10243       // external linkage is valid (C99 6.2.2p5).
10244       if (!Var->isInvalidDecl()) {
10245         if (const IncompleteArrayType *ArrayT
10246                                     = Context.getAsIncompleteArrayType(Type)) {
10247           if (RequireCompleteType(Var->getLocation(),
10248                                   ArrayT->getElementType(),
10249                                   diag::err_illegal_decl_array_incomplete_type))
10250             Var->setInvalidDecl();
10251         } else if (Var->getStorageClass() == SC_Static) {
10252           // C99 6.9.2p3: If the declaration of an identifier for an object is
10253           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10254           // declared type shall not be an incomplete type.
10255           // NOTE: code such as the following
10256           //     static struct s;
10257           //     struct s { int a; };
10258           // is accepted by gcc. Hence here we issue a warning instead of
10259           // an error and we do not invalidate the static declaration.
10260           // NOTE: to avoid multiple warnings, only check the first declaration.
10261           if (Var->isFirstDecl())
10262             RequireCompleteType(Var->getLocation(), Type,
10263                                 diag::ext_typecheck_decl_incomplete_type);
10264         }
10265       }
10266 
10267       // Record the tentative definition; we're done.
10268       if (!Var->isInvalidDecl())
10269         TentativeDefinitions.push_back(Var);
10270       return;
10271     }
10272 
10273     // Provide a specific diagnostic for uninitialized variable
10274     // definitions with incomplete array type.
10275     if (Type->isIncompleteArrayType()) {
10276       Diag(Var->getLocation(),
10277            diag::err_typecheck_incomplete_array_needs_initializer);
10278       Var->setInvalidDecl();
10279       return;
10280     }
10281 
10282     // Provide a specific diagnostic for uninitialized variable
10283     // definitions with reference type.
10284     if (Type->isReferenceType()) {
10285       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10286         << Var->getDeclName()
10287         << SourceRange(Var->getLocation(), Var->getLocation());
10288       Var->setInvalidDecl();
10289       return;
10290     }
10291 
10292     // Do not attempt to type-check the default initializer for a
10293     // variable with dependent type.
10294     if (Type->isDependentType())
10295       return;
10296 
10297     if (Var->isInvalidDecl())
10298       return;
10299 
10300     if (!Var->hasAttr<AliasAttr>()) {
10301       if (RequireCompleteType(Var->getLocation(),
10302                               Context.getBaseElementType(Type),
10303                               diag::err_typecheck_decl_incomplete_type)) {
10304         Var->setInvalidDecl();
10305         return;
10306       }
10307     } else {
10308       return;
10309     }
10310 
10311     // The variable can not have an abstract class type.
10312     if (RequireNonAbstractType(Var->getLocation(), Type,
10313                                diag::err_abstract_type_in_decl,
10314                                AbstractVariableType)) {
10315       Var->setInvalidDecl();
10316       return;
10317     }
10318 
10319     // Check for jumps past the implicit initializer.  C++0x
10320     // clarifies that this applies to a "variable with automatic
10321     // storage duration", not a "local variable".
10322     // C++11 [stmt.dcl]p3
10323     //   A program that jumps from a point where a variable with automatic
10324     //   storage duration is not in scope to a point where it is in scope is
10325     //   ill-formed unless the variable has scalar type, class type with a
10326     //   trivial default constructor and a trivial destructor, a cv-qualified
10327     //   version of one of these types, or an array of one of the preceding
10328     //   types and is declared without an initializer.
10329     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10330       if (const RecordType *Record
10331             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10332         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10333         // Mark the function for further checking even if the looser rules of
10334         // C++11 do not require such checks, so that we can diagnose
10335         // incompatibilities with C++98.
10336         if (!CXXRecord->isPOD())
10337           getCurFunction()->setHasBranchProtectedScope();
10338       }
10339     }
10340 
10341     // C++03 [dcl.init]p9:
10342     //   If no initializer is specified for an object, and the
10343     //   object is of (possibly cv-qualified) non-POD class type (or
10344     //   array thereof), the object shall be default-initialized; if
10345     //   the object is of const-qualified type, the underlying class
10346     //   type shall have a user-declared default
10347     //   constructor. Otherwise, if no initializer is specified for
10348     //   a non- static object, the object and its subobjects, if
10349     //   any, have an indeterminate initial value); if the object
10350     //   or any of its subobjects are of const-qualified type, the
10351     //   program is ill-formed.
10352     // C++0x [dcl.init]p11:
10353     //   If no initializer is specified for an object, the object is
10354     //   default-initialized; [...].
10355     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10356     InitializationKind Kind
10357       = InitializationKind::CreateDefault(Var->getLocation());
10358 
10359     InitializationSequence InitSeq(*this, Entity, Kind, None);
10360     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10361     if (Init.isInvalid())
10362       Var->setInvalidDecl();
10363     else if (Init.get()) {
10364       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10365       // This is important for template substitution.
10366       Var->setInitStyle(VarDecl::CallInit);
10367     }
10368 
10369     CheckCompleteVariableDeclaration(Var);
10370   }
10371 }
10372 
10373 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10374   // If there is no declaration, there was an error parsing it. Ignore it.
10375   if (!D)
10376     return;
10377 
10378   VarDecl *VD = dyn_cast<VarDecl>(D);
10379   if (!VD) {
10380     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10381     D->setInvalidDecl();
10382     return;
10383   }
10384 
10385   VD->setCXXForRangeDecl(true);
10386 
10387   // for-range-declaration cannot be given a storage class specifier.
10388   int Error = -1;
10389   switch (VD->getStorageClass()) {
10390   case SC_None:
10391     break;
10392   case SC_Extern:
10393     Error = 0;
10394     break;
10395   case SC_Static:
10396     Error = 1;
10397     break;
10398   case SC_PrivateExtern:
10399     Error = 2;
10400     break;
10401   case SC_Auto:
10402     Error = 3;
10403     break;
10404   case SC_Register:
10405     Error = 4;
10406     break;
10407   }
10408   if (Error != -1) {
10409     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10410       << VD->getDeclName() << Error;
10411     D->setInvalidDecl();
10412   }
10413 }
10414 
10415 StmtResult
10416 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10417                                  IdentifierInfo *Ident,
10418                                  ParsedAttributes &Attrs,
10419                                  SourceLocation AttrEnd) {
10420   // C++1y [stmt.iter]p1:
10421   //   A range-based for statement of the form
10422   //      for ( for-range-identifier : for-range-initializer ) statement
10423   //   is equivalent to
10424   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10425   DeclSpec DS(Attrs.getPool().getFactory());
10426 
10427   const char *PrevSpec;
10428   unsigned DiagID;
10429   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10430                      getPrintingPolicy());
10431 
10432   Declarator D(DS, Declarator::ForContext);
10433   D.SetIdentifier(Ident, IdentLoc);
10434   D.takeAttributes(Attrs, AttrEnd);
10435 
10436   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10437   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10438                 EmptyAttrs, IdentLoc);
10439   Decl *Var = ActOnDeclarator(S, D);
10440   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10441   FinalizeDeclaration(Var);
10442   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10443                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10444 }
10445 
10446 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10447   if (var->isInvalidDecl()) return;
10448 
10449   if (getLangOpts().OpenCL) {
10450     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10451     // initialiser
10452     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10453         !var->hasInit()) {
10454       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10455           << 1 /*Init*/;
10456       var->setInvalidDecl();
10457       return;
10458     }
10459   }
10460 
10461   // In Objective-C, don't allow jumps past the implicit initialization of a
10462   // local retaining variable.
10463   if (getLangOpts().ObjC1 &&
10464       var->hasLocalStorage()) {
10465     switch (var->getType().getObjCLifetime()) {
10466     case Qualifiers::OCL_None:
10467     case Qualifiers::OCL_ExplicitNone:
10468     case Qualifiers::OCL_Autoreleasing:
10469       break;
10470 
10471     case Qualifiers::OCL_Weak:
10472     case Qualifiers::OCL_Strong:
10473       getCurFunction()->setHasBranchProtectedScope();
10474       break;
10475     }
10476   }
10477 
10478   // Warn about externally-visible variables being defined without a
10479   // prior declaration.  We only want to do this for global
10480   // declarations, but we also specifically need to avoid doing it for
10481   // class members because the linkage of an anonymous class can
10482   // change if it's later given a typedef name.
10483   if (var->isThisDeclarationADefinition() &&
10484       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10485       var->isExternallyVisible() && var->hasLinkage() &&
10486       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10487                                   var->getLocation())) {
10488     // Find a previous declaration that's not a definition.
10489     VarDecl *prev = var->getPreviousDecl();
10490     while (prev && prev->isThisDeclarationADefinition())
10491       prev = prev->getPreviousDecl();
10492 
10493     if (!prev)
10494       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10495   }
10496 
10497   // Cache the result of checking for constant initialization.
10498   Optional<bool> CacheHasConstInit;
10499   const Expr *CacheCulprit;
10500   auto checkConstInit = [&]() mutable {
10501     if (!CacheHasConstInit)
10502       CacheHasConstInit = var->getInit()->isConstantInitializer(
10503             Context, var->getType()->isReferenceType(), &CacheCulprit);
10504     return *CacheHasConstInit;
10505   };
10506 
10507   if (var->getTLSKind() == VarDecl::TLS_Static) {
10508     if (var->getType().isDestructedType()) {
10509       // GNU C++98 edits for __thread, [basic.start.term]p3:
10510       //   The type of an object with thread storage duration shall not
10511       //   have a non-trivial destructor.
10512       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10513       if (getLangOpts().CPlusPlus11)
10514         Diag(var->getLocation(), diag::note_use_thread_local);
10515     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10516       if (!checkConstInit()) {
10517         // GNU C++98 edits for __thread, [basic.start.init]p4:
10518         //   An object of thread storage duration shall not require dynamic
10519         //   initialization.
10520         // FIXME: Need strict checking here.
10521         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10522           << CacheCulprit->getSourceRange();
10523         if (getLangOpts().CPlusPlus11)
10524           Diag(var->getLocation(), diag::note_use_thread_local);
10525       }
10526     }
10527   }
10528 
10529   // Apply section attributes and pragmas to global variables.
10530   bool GlobalStorage = var->hasGlobalStorage();
10531   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10532       ActiveTemplateInstantiations.empty()) {
10533     PragmaStack<StringLiteral *> *Stack = nullptr;
10534     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10535     if (var->getType().isConstQualified())
10536       Stack = &ConstSegStack;
10537     else if (!var->getInit()) {
10538       Stack = &BSSSegStack;
10539       SectionFlags |= ASTContext::PSF_Write;
10540     } else {
10541       Stack = &DataSegStack;
10542       SectionFlags |= ASTContext::PSF_Write;
10543     }
10544     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10545       var->addAttr(SectionAttr::CreateImplicit(
10546           Context, SectionAttr::Declspec_allocate,
10547           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10548     }
10549     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10550       if (UnifySection(SA->getName(), SectionFlags, var))
10551         var->dropAttr<SectionAttr>();
10552 
10553     // Apply the init_seg attribute if this has an initializer.  If the
10554     // initializer turns out to not be dynamic, we'll end up ignoring this
10555     // attribute.
10556     if (CurInitSeg && var->getInit())
10557       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10558                                                CurInitSegLoc));
10559   }
10560 
10561   // All the following checks are C++ only.
10562   if (!getLangOpts().CPlusPlus) {
10563       // If this variable must be emitted, add it as an initializer for the
10564       // current module.
10565      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10566        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10567      return;
10568   }
10569 
10570   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10571     CheckCompleteDecompositionDeclaration(DD);
10572 
10573   QualType type = var->getType();
10574   if (type->isDependentType()) return;
10575 
10576   // __block variables might require us to capture a copy-initializer.
10577   if (var->hasAttr<BlocksAttr>()) {
10578     // It's currently invalid to ever have a __block variable with an
10579     // array type; should we diagnose that here?
10580 
10581     // Regardless, we don't want to ignore array nesting when
10582     // constructing this copy.
10583     if (type->isStructureOrClassType()) {
10584       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10585       SourceLocation poi = var->getLocation();
10586       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10587       ExprResult result
10588         = PerformMoveOrCopyInitialization(
10589             InitializedEntity::InitializeBlock(poi, type, false),
10590             var, var->getType(), varRef, /*AllowNRVO=*/true);
10591       if (!result.isInvalid()) {
10592         result = MaybeCreateExprWithCleanups(result);
10593         Expr *init = result.getAs<Expr>();
10594         Context.setBlockVarCopyInits(var, init);
10595       }
10596     }
10597   }
10598 
10599   Expr *Init = var->getInit();
10600   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10601   QualType baseType = Context.getBaseElementType(type);
10602 
10603   if (!var->getDeclContext()->isDependentContext() &&
10604       Init && !Init->isValueDependent()) {
10605 
10606     if (var->isConstexpr()) {
10607       SmallVector<PartialDiagnosticAt, 8> Notes;
10608       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10609         SourceLocation DiagLoc = var->getLocation();
10610         // If the note doesn't add any useful information other than a source
10611         // location, fold it into the primary diagnostic.
10612         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10613               diag::note_invalid_subexpr_in_const_expr) {
10614           DiagLoc = Notes[0].first;
10615           Notes.clear();
10616         }
10617         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10618           << var << Init->getSourceRange();
10619         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10620           Diag(Notes[I].first, Notes[I].second);
10621       }
10622     } else if (var->isUsableInConstantExpressions(Context)) {
10623       // Check whether the initializer of a const variable of integral or
10624       // enumeration type is an ICE now, since we can't tell whether it was
10625       // initialized by a constant expression if we check later.
10626       var->checkInitIsICE();
10627     }
10628 
10629     // Don't emit further diagnostics about constexpr globals since they
10630     // were just diagnosed.
10631     if (!var->isConstexpr() && GlobalStorage &&
10632             var->hasAttr<RequireConstantInitAttr>()) {
10633       // FIXME: Need strict checking in C++03 here.
10634       bool DiagErr = getLangOpts().CPlusPlus11
10635           ? !var->checkInitIsICE() : !checkConstInit();
10636       if (DiagErr) {
10637         auto attr = var->getAttr<RequireConstantInitAttr>();
10638         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10639           << Init->getSourceRange();
10640         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10641           << attr->getRange();
10642       }
10643     }
10644     else if (!var->isConstexpr() && IsGlobal &&
10645              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10646                                     var->getLocation())) {
10647       // Warn about globals which don't have a constant initializer.  Don't
10648       // warn about globals with a non-trivial destructor because we already
10649       // warned about them.
10650       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10651       if (!(RD && !RD->hasTrivialDestructor())) {
10652         if (!checkConstInit())
10653           Diag(var->getLocation(), diag::warn_global_constructor)
10654             << Init->getSourceRange();
10655       }
10656     }
10657   }
10658 
10659   // Require the destructor.
10660   if (const RecordType *recordType = baseType->getAs<RecordType>())
10661     FinalizeVarWithDestructor(var, recordType);
10662 
10663   // If this variable must be emitted, add it as an initializer for the current
10664   // module.
10665   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10666     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10667 }
10668 
10669 /// \brief Determines if a variable's alignment is dependent.
10670 static bool hasDependentAlignment(VarDecl *VD) {
10671   if (VD->getType()->isDependentType())
10672     return true;
10673   for (auto *I : VD->specific_attrs<AlignedAttr>())
10674     if (I->isAlignmentDependent())
10675       return true;
10676   return false;
10677 }
10678 
10679 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10680 /// any semantic actions necessary after any initializer has been attached.
10681 void
10682 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10683   // Note that we are no longer parsing the initializer for this declaration.
10684   ParsingInitForAutoVars.erase(ThisDecl);
10685 
10686   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10687   if (!VD)
10688     return;
10689 
10690   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10691     for (auto *BD : DD->bindings()) {
10692       if (ThisDecl->isInvalidDecl())
10693         BD->setInvalidDecl();
10694       FinalizeDeclaration(BD);
10695     }
10696   }
10697 
10698   checkAttributesAfterMerging(*this, *VD);
10699 
10700   // Perform TLS alignment check here after attributes attached to the variable
10701   // which may affect the alignment have been processed. Only perform the check
10702   // if the target has a maximum TLS alignment (zero means no constraints).
10703   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10704     // Protect the check so that it's not performed on dependent types and
10705     // dependent alignments (we can't determine the alignment in that case).
10706     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10707       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10708       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10709         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10710           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10711           << (unsigned)MaxAlignChars.getQuantity();
10712       }
10713     }
10714   }
10715 
10716   if (VD->isStaticLocal()) {
10717     if (FunctionDecl *FD =
10718             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10719       // Static locals inherit dll attributes from their function.
10720       if (Attr *A = getDLLAttr(FD)) {
10721         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10722         NewAttr->setInherited(true);
10723         VD->addAttr(NewAttr);
10724       }
10725       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10726       // function, only __shared__ variables may be declared with
10727       // static storage class.
10728       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
10729           CUDADiagIfDeviceCode(VD->getLocation(),
10730                                diag::err_device_static_local_var)
10731               << CurrentCUDATarget())
10732         VD->setInvalidDecl();
10733     }
10734   }
10735 
10736   // Perform check for initializers of device-side global variables.
10737   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10738   // 7.5). We must also apply the same checks to all __shared__
10739   // variables whether they are local or not. CUDA also allows
10740   // constant initializers for __constant__ and __device__ variables.
10741   if (getLangOpts().CUDA) {
10742     const Expr *Init = VD->getInit();
10743     if (Init && VD->hasGlobalStorage()) {
10744       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10745           VD->hasAttr<CUDASharedAttr>()) {
10746         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
10747         bool AllowedInit = false;
10748         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10749           AllowedInit =
10750               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10751         // We'll allow constant initializers even if it's a non-empty
10752         // constructor according to CUDA rules. This deviates from NVCC,
10753         // but allows us to handle things like constexpr constructors.
10754         if (!AllowedInit &&
10755             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10756           AllowedInit = VD->getInit()->isConstantInitializer(
10757               Context, VD->getType()->isReferenceType());
10758 
10759         // Also make sure that destructor, if there is one, is empty.
10760         if (AllowedInit)
10761           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10762             AllowedInit =
10763                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10764 
10765         if (!AllowedInit) {
10766           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10767                                       ? diag::err_shared_var_init
10768                                       : diag::err_dynamic_var_init)
10769               << Init->getSourceRange();
10770           VD->setInvalidDecl();
10771         }
10772       } else {
10773         // This is a host-side global variable.  Check that the initializer is
10774         // callable from the host side.
10775         const FunctionDecl *InitFn = nullptr;
10776         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10777           InitFn = CE->getConstructor();
10778         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10779           InitFn = CE->getDirectCallee();
10780         }
10781         if (InitFn) {
10782           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10783           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10784             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10785                 << InitFnTarget << InitFn;
10786             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10787             VD->setInvalidDecl();
10788           }
10789         }
10790       }
10791     }
10792   }
10793 
10794   // Grab the dllimport or dllexport attribute off of the VarDecl.
10795   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10796 
10797   // Imported static data members cannot be defined out-of-line.
10798   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10799     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10800         VD->isThisDeclarationADefinition()) {
10801       // We allow definitions of dllimport class template static data members
10802       // with a warning.
10803       CXXRecordDecl *Context =
10804         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10805       bool IsClassTemplateMember =
10806           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10807           Context->getDescribedClassTemplate();
10808 
10809       Diag(VD->getLocation(),
10810            IsClassTemplateMember
10811                ? diag::warn_attribute_dllimport_static_field_definition
10812                : diag::err_attribute_dllimport_static_field_definition);
10813       Diag(IA->getLocation(), diag::note_attribute);
10814       if (!IsClassTemplateMember)
10815         VD->setInvalidDecl();
10816     }
10817   }
10818 
10819   // dllimport/dllexport variables cannot be thread local, their TLS index
10820   // isn't exported with the variable.
10821   if (DLLAttr && VD->getTLSKind()) {
10822     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10823     if (F && getDLLAttr(F)) {
10824       assert(VD->isStaticLocal());
10825       // But if this is a static local in a dlimport/dllexport function, the
10826       // function will never be inlined, which means the var would never be
10827       // imported, so having it marked import/export is safe.
10828     } else {
10829       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10830                                                                     << DLLAttr;
10831       VD->setInvalidDecl();
10832     }
10833   }
10834 
10835   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10836     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10837       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10838       VD->dropAttr<UsedAttr>();
10839     }
10840   }
10841 
10842   const DeclContext *DC = VD->getDeclContext();
10843   // If there's a #pragma GCC visibility in scope, and this isn't a class
10844   // member, set the visibility of this variable.
10845   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10846     AddPushedVisibilityAttribute(VD);
10847 
10848   // FIXME: Warn on unused templates.
10849   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10850       !isa<VarTemplatePartialSpecializationDecl>(VD))
10851     MarkUnusedFileScopedDecl(VD);
10852 
10853   // Now we have parsed the initializer and can update the table of magic
10854   // tag values.
10855   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10856       !VD->getType()->isIntegralOrEnumerationType())
10857     return;
10858 
10859   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10860     const Expr *MagicValueExpr = VD->getInit();
10861     if (!MagicValueExpr) {
10862       continue;
10863     }
10864     llvm::APSInt MagicValueInt;
10865     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10866       Diag(I->getRange().getBegin(),
10867            diag::err_type_tag_for_datatype_not_ice)
10868         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10869       continue;
10870     }
10871     if (MagicValueInt.getActiveBits() > 64) {
10872       Diag(I->getRange().getBegin(),
10873            diag::err_type_tag_for_datatype_too_large)
10874         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10875       continue;
10876     }
10877     uint64_t MagicValue = MagicValueInt.getZExtValue();
10878     RegisterTypeTagForDatatype(I->getArgumentKind(),
10879                                MagicValue,
10880                                I->getMatchingCType(),
10881                                I->getLayoutCompatible(),
10882                                I->getMustBeNull());
10883   }
10884 }
10885 
10886 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10887                                                    ArrayRef<Decl *> Group) {
10888   SmallVector<Decl*, 8> Decls;
10889 
10890   if (DS.isTypeSpecOwned())
10891     Decls.push_back(DS.getRepAsDecl());
10892 
10893   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10894   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
10895   bool DiagnosedMultipleDecomps = false;
10896 
10897   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10898     if (Decl *D = Group[i]) {
10899       auto *DD = dyn_cast<DeclaratorDecl>(D);
10900       if (DD && !FirstDeclaratorInGroup)
10901         FirstDeclaratorInGroup = DD;
10902 
10903       auto *Decomp = dyn_cast<DecompositionDecl>(D);
10904       if (Decomp && !FirstDecompDeclaratorInGroup)
10905         FirstDecompDeclaratorInGroup = Decomp;
10906 
10907       // A decomposition declaration cannot be combined with any other
10908       // declaration in the same group.
10909       auto *OtherDD = FirstDeclaratorInGroup;
10910       if (OtherDD == FirstDecompDeclaratorInGroup)
10911         OtherDD = DD;
10912       if (OtherDD && FirstDecompDeclaratorInGroup &&
10913           OtherDD != FirstDecompDeclaratorInGroup &&
10914           !DiagnosedMultipleDecomps) {
10915         Diag(FirstDecompDeclaratorInGroup->getLocation(),
10916              diag::err_decomp_decl_not_alone)
10917           << OtherDD->getSourceRange();
10918         DiagnosedMultipleDecomps = true;
10919       }
10920 
10921       Decls.push_back(D);
10922     }
10923   }
10924 
10925   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10926     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10927       handleTagNumbering(Tag, S);
10928       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10929           getLangOpts().CPlusPlus)
10930         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10931     }
10932   }
10933 
10934   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10935 }
10936 
10937 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10938 /// group, performing any necessary semantic checking.
10939 Sema::DeclGroupPtrTy
10940 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10941                            bool TypeMayContainAuto) {
10942   // C++0x [dcl.spec.auto]p7:
10943   //   If the type deduced for the template parameter U is not the same in each
10944   //   deduction, the program is ill-formed.
10945   // FIXME: When initializer-list support is added, a distinction is needed
10946   // between the deduced type U and the deduced type which 'auto' stands for.
10947   //   auto a = 0, b = { 1, 2, 3 };
10948   // is legal because the deduced type U is 'int' in both cases.
10949   if (TypeMayContainAuto && Group.size() > 1) {
10950     QualType Deduced;
10951     CanQualType DeducedCanon;
10952     VarDecl *DeducedDecl = nullptr;
10953     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10954       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10955         AutoType *AT = D->getType()->getContainedAutoType();
10956         // Don't reissue diagnostics when instantiating a template.
10957         if (AT && D->isInvalidDecl())
10958           break;
10959         QualType U = AT ? AT->getDeducedType() : QualType();
10960         if (!U.isNull()) {
10961           CanQualType UCanon = Context.getCanonicalType(U);
10962           if (Deduced.isNull()) {
10963             Deduced = U;
10964             DeducedCanon = UCanon;
10965             DeducedDecl = D;
10966           } else if (DeducedCanon != UCanon) {
10967             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10968                  diag::err_auto_different_deductions)
10969               << (unsigned)AT->getKeyword()
10970               << Deduced << DeducedDecl->getDeclName()
10971               << U << D->getDeclName()
10972               << DeducedDecl->getInit()->getSourceRange()
10973               << D->getInit()->getSourceRange();
10974             D->setInvalidDecl();
10975             break;
10976           }
10977         }
10978       }
10979     }
10980   }
10981 
10982   ActOnDocumentableDecls(Group);
10983 
10984   return DeclGroupPtrTy::make(
10985       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10986 }
10987 
10988 void Sema::ActOnDocumentableDecl(Decl *D) {
10989   ActOnDocumentableDecls(D);
10990 }
10991 
10992 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10993   // Don't parse the comment if Doxygen diagnostics are ignored.
10994   if (Group.empty() || !Group[0])
10995     return;
10996 
10997   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10998                       Group[0]->getLocation()) &&
10999       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11000                       Group[0]->getLocation()))
11001     return;
11002 
11003   if (Group.size() >= 2) {
11004     // This is a decl group.  Normally it will contain only declarations
11005     // produced from declarator list.  But in case we have any definitions or
11006     // additional declaration references:
11007     //   'typedef struct S {} S;'
11008     //   'typedef struct S *S;'
11009     //   'struct S *pS;'
11010     // FinalizeDeclaratorGroup adds these as separate declarations.
11011     Decl *MaybeTagDecl = Group[0];
11012     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11013       Group = Group.slice(1);
11014     }
11015   }
11016 
11017   // See if there are any new comments that are not attached to a decl.
11018   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11019   if (!Comments.empty() &&
11020       !Comments.back()->isAttached()) {
11021     // There is at least one comment that not attached to a decl.
11022     // Maybe it should be attached to one of these decls?
11023     //
11024     // Note that this way we pick up not only comments that precede the
11025     // declaration, but also comments that *follow* the declaration -- thanks to
11026     // the lookahead in the lexer: we've consumed the semicolon and looked
11027     // ahead through comments.
11028     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11029       Context.getCommentForDecl(Group[i], &PP);
11030   }
11031 }
11032 
11033 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11034 /// to introduce parameters into function prototype scope.
11035 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11036   const DeclSpec &DS = D.getDeclSpec();
11037 
11038   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11039 
11040   // C++03 [dcl.stc]p2 also permits 'auto'.
11041   StorageClass SC = SC_None;
11042   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11043     SC = SC_Register;
11044   } else if (getLangOpts().CPlusPlus &&
11045              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11046     SC = SC_Auto;
11047   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11048     Diag(DS.getStorageClassSpecLoc(),
11049          diag::err_invalid_storage_class_in_func_decl);
11050     D.getMutableDeclSpec().ClearStorageClassSpecs();
11051   }
11052 
11053   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11054     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11055       << DeclSpec::getSpecifierName(TSCS);
11056   if (DS.isInlineSpecified())
11057     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11058         << getLangOpts().CPlusPlus1z;
11059   if (DS.isConstexprSpecified())
11060     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11061       << 0;
11062   if (DS.isConceptSpecified())
11063     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11064 
11065   DiagnoseFunctionSpecifiers(DS);
11066 
11067   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11068   QualType parmDeclType = TInfo->getType();
11069 
11070   if (getLangOpts().CPlusPlus) {
11071     // Check that there are no default arguments inside the type of this
11072     // parameter.
11073     CheckExtraCXXDefaultArguments(D);
11074 
11075     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11076     if (D.getCXXScopeSpec().isSet()) {
11077       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11078         << D.getCXXScopeSpec().getRange();
11079       D.getCXXScopeSpec().clear();
11080     }
11081   }
11082 
11083   // Ensure we have a valid name
11084   IdentifierInfo *II = nullptr;
11085   if (D.hasName()) {
11086     II = D.getIdentifier();
11087     if (!II) {
11088       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11089         << GetNameForDeclarator(D).getName();
11090       D.setInvalidType(true);
11091     }
11092   }
11093 
11094   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11095   if (II) {
11096     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11097                    ForRedeclaration);
11098     LookupName(R, S);
11099     if (R.isSingleResult()) {
11100       NamedDecl *PrevDecl = R.getFoundDecl();
11101       if (PrevDecl->isTemplateParameter()) {
11102         // Maybe we will complain about the shadowed template parameter.
11103         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11104         // Just pretend that we didn't see the previous declaration.
11105         PrevDecl = nullptr;
11106       } else if (S->isDeclScope(PrevDecl)) {
11107         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11108         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11109 
11110         // Recover by removing the name
11111         II = nullptr;
11112         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11113         D.setInvalidType(true);
11114       }
11115     }
11116   }
11117 
11118   // Temporarily put parameter variables in the translation unit, not
11119   // the enclosing context.  This prevents them from accidentally
11120   // looking like class members in C++.
11121   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11122                                     D.getLocStart(),
11123                                     D.getIdentifierLoc(), II,
11124                                     parmDeclType, TInfo,
11125                                     SC);
11126 
11127   if (D.isInvalidType())
11128     New->setInvalidDecl();
11129 
11130   assert(S->isFunctionPrototypeScope());
11131   assert(S->getFunctionPrototypeDepth() >= 1);
11132   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11133                     S->getNextFunctionPrototypeIndex());
11134 
11135   // Add the parameter declaration into this scope.
11136   S->AddDecl(New);
11137   if (II)
11138     IdResolver.AddDecl(New);
11139 
11140   ProcessDeclAttributes(S, New, D);
11141 
11142   if (D.getDeclSpec().isModulePrivateSpecified())
11143     Diag(New->getLocation(), diag::err_module_private_local)
11144       << 1 << New->getDeclName()
11145       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11146       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11147 
11148   if (New->hasAttr<BlocksAttr>()) {
11149     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11150   }
11151   return New;
11152 }
11153 
11154 /// \brief Synthesizes a variable for a parameter arising from a
11155 /// typedef.
11156 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11157                                               SourceLocation Loc,
11158                                               QualType T) {
11159   /* FIXME: setting StartLoc == Loc.
11160      Would it be worth to modify callers so as to provide proper source
11161      location for the unnamed parameters, embedding the parameter's type? */
11162   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11163                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11164                                            SC_None, nullptr);
11165   Param->setImplicit();
11166   return Param;
11167 }
11168 
11169 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11170   // Don't diagnose unused-parameter errors in template instantiations; we
11171   // will already have done so in the template itself.
11172   if (!ActiveTemplateInstantiations.empty())
11173     return;
11174 
11175   for (const ParmVarDecl *Parameter : Parameters) {
11176     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11177         !Parameter->hasAttr<UnusedAttr>()) {
11178       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11179         << Parameter->getDeclName();
11180     }
11181   }
11182 }
11183 
11184 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11185     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11186   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11187     return;
11188 
11189   // Warn if the return value is pass-by-value and larger than the specified
11190   // threshold.
11191   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11192     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11193     if (Size > LangOpts.NumLargeByValueCopy)
11194       Diag(D->getLocation(), diag::warn_return_value_size)
11195           << D->getDeclName() << Size;
11196   }
11197 
11198   // Warn if any parameter is pass-by-value and larger than the specified
11199   // threshold.
11200   for (const ParmVarDecl *Parameter : Parameters) {
11201     QualType T = Parameter->getType();
11202     if (T->isDependentType() || !T.isPODType(Context))
11203       continue;
11204     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11205     if (Size > LangOpts.NumLargeByValueCopy)
11206       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11207           << Parameter->getDeclName() << Size;
11208   }
11209 }
11210 
11211 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11212                                   SourceLocation NameLoc, IdentifierInfo *Name,
11213                                   QualType T, TypeSourceInfo *TSInfo,
11214                                   StorageClass SC) {
11215   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11216   if (getLangOpts().ObjCAutoRefCount &&
11217       T.getObjCLifetime() == Qualifiers::OCL_None &&
11218       T->isObjCLifetimeType()) {
11219 
11220     Qualifiers::ObjCLifetime lifetime;
11221 
11222     // Special cases for arrays:
11223     //   - if it's const, use __unsafe_unretained
11224     //   - otherwise, it's an error
11225     if (T->isArrayType()) {
11226       if (!T.isConstQualified()) {
11227         DelayedDiagnostics.add(
11228             sema::DelayedDiagnostic::makeForbiddenType(
11229             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11230       }
11231       lifetime = Qualifiers::OCL_ExplicitNone;
11232     } else {
11233       lifetime = T->getObjCARCImplicitLifetime();
11234     }
11235     T = Context.getLifetimeQualifiedType(T, lifetime);
11236   }
11237 
11238   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11239                                          Context.getAdjustedParameterType(T),
11240                                          TSInfo, SC, nullptr);
11241 
11242   // Parameters can not be abstract class types.
11243   // For record types, this is done by the AbstractClassUsageDiagnoser once
11244   // the class has been completely parsed.
11245   if (!CurContext->isRecord() &&
11246       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11247                              AbstractParamType))
11248     New->setInvalidDecl();
11249 
11250   // Parameter declarators cannot be interface types. All ObjC objects are
11251   // passed by reference.
11252   if (T->isObjCObjectType()) {
11253     SourceLocation TypeEndLoc =
11254         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11255     Diag(NameLoc,
11256          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11257       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11258     T = Context.getObjCObjectPointerType(T);
11259     New->setType(T);
11260   }
11261 
11262   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11263   // duration shall not be qualified by an address-space qualifier."
11264   // Since all parameters have automatic store duration, they can not have
11265   // an address space.
11266   if (T.getAddressSpace() != 0) {
11267     // OpenCL allows function arguments declared to be an array of a type
11268     // to be qualified with an address space.
11269     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11270       Diag(NameLoc, diag::err_arg_with_address_space);
11271       New->setInvalidDecl();
11272     }
11273   }
11274 
11275   return New;
11276 }
11277 
11278 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11279                                            SourceLocation LocAfterDecls) {
11280   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11281 
11282   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11283   // for a K&R function.
11284   if (!FTI.hasPrototype) {
11285     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11286       --i;
11287       if (FTI.Params[i].Param == nullptr) {
11288         SmallString<256> Code;
11289         llvm::raw_svector_ostream(Code)
11290             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11291         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11292             << FTI.Params[i].Ident
11293             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11294 
11295         // Implicitly declare the argument as type 'int' for lack of a better
11296         // type.
11297         AttributeFactory attrs;
11298         DeclSpec DS(attrs);
11299         const char* PrevSpec; // unused
11300         unsigned DiagID; // unused
11301         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11302                            DiagID, Context.getPrintingPolicy());
11303         // Use the identifier location for the type source range.
11304         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11305         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11306         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11307         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11308         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11309       }
11310     }
11311   }
11312 }
11313 
11314 Decl *
11315 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11316                               MultiTemplateParamsArg TemplateParameterLists,
11317                               SkipBodyInfo *SkipBody) {
11318   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11319   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11320   Scope *ParentScope = FnBodyScope->getParent();
11321 
11322   D.setFunctionDefinitionKind(FDK_Definition);
11323   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11324   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11325 }
11326 
11327 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11328   Consumer.HandleInlineFunctionDefinition(D);
11329 }
11330 
11331 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11332                              const FunctionDecl*& PossibleZeroParamPrototype) {
11333   // Don't warn about invalid declarations.
11334   if (FD->isInvalidDecl())
11335     return false;
11336 
11337   // Or declarations that aren't global.
11338   if (!FD->isGlobal())
11339     return false;
11340 
11341   // Don't warn about C++ member functions.
11342   if (isa<CXXMethodDecl>(FD))
11343     return false;
11344 
11345   // Don't warn about 'main'.
11346   if (FD->isMain())
11347     return false;
11348 
11349   // Don't warn about inline functions.
11350   if (FD->isInlined())
11351     return false;
11352 
11353   // Don't warn about function templates.
11354   if (FD->getDescribedFunctionTemplate())
11355     return false;
11356 
11357   // Don't warn about function template specializations.
11358   if (FD->isFunctionTemplateSpecialization())
11359     return false;
11360 
11361   // Don't warn for OpenCL kernels.
11362   if (FD->hasAttr<OpenCLKernelAttr>())
11363     return false;
11364 
11365   // Don't warn on explicitly deleted functions.
11366   if (FD->isDeleted())
11367     return false;
11368 
11369   bool MissingPrototype = true;
11370   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11371        Prev; Prev = Prev->getPreviousDecl()) {
11372     // Ignore any declarations that occur in function or method
11373     // scope, because they aren't visible from the header.
11374     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11375       continue;
11376 
11377     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11378     if (FD->getNumParams() == 0)
11379       PossibleZeroParamPrototype = Prev;
11380     break;
11381   }
11382 
11383   return MissingPrototype;
11384 }
11385 
11386 void
11387 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11388                                    const FunctionDecl *EffectiveDefinition,
11389                                    SkipBodyInfo *SkipBody) {
11390   // Don't complain if we're in GNU89 mode and the previous definition
11391   // was an extern inline function.
11392   const FunctionDecl *Definition = EffectiveDefinition;
11393   if (!Definition)
11394     if (!FD->isDefined(Definition))
11395       return;
11396 
11397   if (canRedefineFunction(Definition, getLangOpts()))
11398     return;
11399 
11400   // If we don't have a visible definition of the function, and it's inline or
11401   // a template, skip the new definition.
11402   if (SkipBody && !hasVisibleDefinition(Definition) &&
11403       (Definition->getFormalLinkage() == InternalLinkage ||
11404        Definition->isInlined() ||
11405        Definition->getDescribedFunctionTemplate() ||
11406        Definition->getNumTemplateParameterLists())) {
11407     SkipBody->ShouldSkip = true;
11408     if (auto *TD = Definition->getDescribedFunctionTemplate())
11409       makeMergedDefinitionVisible(TD, FD->getLocation());
11410     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11411                                 FD->getLocation());
11412     return;
11413   }
11414 
11415   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11416       Definition->getStorageClass() == SC_Extern)
11417     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11418         << FD->getDeclName() << getLangOpts().CPlusPlus;
11419   else
11420     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11421 
11422   Diag(Definition->getLocation(), diag::note_previous_definition);
11423   FD->setInvalidDecl();
11424 }
11425 
11426 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11427                                    Sema &S) {
11428   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11429 
11430   LambdaScopeInfo *LSI = S.PushLambdaScope();
11431   LSI->CallOperator = CallOperator;
11432   LSI->Lambda = LambdaClass;
11433   LSI->ReturnType = CallOperator->getReturnType();
11434   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11435 
11436   if (LCD == LCD_None)
11437     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11438   else if (LCD == LCD_ByCopy)
11439     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11440   else if (LCD == LCD_ByRef)
11441     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11442   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11443 
11444   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11445   LSI->Mutable = !CallOperator->isConst();
11446 
11447   // Add the captures to the LSI so they can be noted as already
11448   // captured within tryCaptureVar.
11449   auto I = LambdaClass->field_begin();
11450   for (const auto &C : LambdaClass->captures()) {
11451     if (C.capturesVariable()) {
11452       VarDecl *VD = C.getCapturedVar();
11453       if (VD->isInitCapture())
11454         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11455       QualType CaptureType = VD->getType();
11456       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11457       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11458           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11459           /*EllipsisLoc*/C.isPackExpansion()
11460                          ? C.getEllipsisLoc() : SourceLocation(),
11461           CaptureType, /*Expr*/ nullptr);
11462 
11463     } else if (C.capturesThis()) {
11464       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11465                               /*Expr*/ nullptr,
11466                               C.getCaptureKind() == LCK_StarThis);
11467     } else {
11468       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11469     }
11470     ++I;
11471   }
11472 }
11473 
11474 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11475                                     SkipBodyInfo *SkipBody) {
11476   // Clear the last template instantiation error context.
11477   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11478 
11479   if (!D)
11480     return D;
11481   FunctionDecl *FD = nullptr;
11482 
11483   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11484     FD = FunTmpl->getTemplatedDecl();
11485   else
11486     FD = cast<FunctionDecl>(D);
11487 
11488   // See if this is a redefinition.
11489   if (!FD->isLateTemplateParsed()) {
11490     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11491 
11492     // If we're skipping the body, we're done. Don't enter the scope.
11493     if (SkipBody && SkipBody->ShouldSkip)
11494       return D;
11495   }
11496 
11497   // If we are instantiating a generic lambda call operator, push
11498   // a LambdaScopeInfo onto the function stack.  But use the information
11499   // that's already been calculated (ActOnLambdaExpr) to prime the current
11500   // LambdaScopeInfo.
11501   // When the template operator is being specialized, the LambdaScopeInfo,
11502   // has to be properly restored so that tryCaptureVariable doesn't try
11503   // and capture any new variables. In addition when calculating potential
11504   // captures during transformation of nested lambdas, it is necessary to
11505   // have the LSI properly restored.
11506   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11507     assert(ActiveTemplateInstantiations.size() &&
11508       "There should be an active template instantiation on the stack "
11509       "when instantiating a generic lambda!");
11510     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11511   }
11512   else
11513     // Enter a new function scope
11514     PushFunctionScope();
11515 
11516   // Builtin functions cannot be defined.
11517   if (unsigned BuiltinID = FD->getBuiltinID()) {
11518     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11519         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11520       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11521       FD->setInvalidDecl();
11522     }
11523   }
11524 
11525   // The return type of a function definition must be complete
11526   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11527   QualType ResultType = FD->getReturnType();
11528   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11529       !FD->isInvalidDecl() &&
11530       RequireCompleteType(FD->getLocation(), ResultType,
11531                           diag::err_func_def_incomplete_result))
11532     FD->setInvalidDecl();
11533 
11534   if (FnBodyScope)
11535     PushDeclContext(FnBodyScope, FD);
11536 
11537   // Check the validity of our function parameters
11538   CheckParmsForFunctionDef(FD->parameters(),
11539                            /*CheckParameterNames=*/true);
11540 
11541   // Introduce our parameters into the function scope
11542   for (auto Param : FD->parameters()) {
11543     Param->setOwningFunction(FD);
11544 
11545     // If this has an identifier, add it to the scope stack.
11546     if (Param->getIdentifier() && FnBodyScope) {
11547       CheckShadow(FnBodyScope, Param);
11548 
11549       PushOnScopeChains(Param, FnBodyScope);
11550     }
11551   }
11552 
11553   // If we had any tags defined in the function prototype,
11554   // introduce them into the function scope.
11555   if (FnBodyScope) {
11556     for (ArrayRef<NamedDecl *>::iterator
11557              I = FD->getDeclsInPrototypeScope().begin(),
11558              E = FD->getDeclsInPrototypeScope().end();
11559          I != E; ++I) {
11560       NamedDecl *D = *I;
11561 
11562       // Some of these decls (like enums) may have been pinned to the
11563       // translation unit for lack of a real context earlier. If so, remove
11564       // from the translation unit and reattach to the current context.
11565       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11566         // Is the decl actually in the context?
11567         if (Context.getTranslationUnitDecl()->containsDecl(D))
11568           Context.getTranslationUnitDecl()->removeDecl(D);
11569         // Either way, reassign the lexical decl context to our FunctionDecl.
11570         D->setLexicalDeclContext(CurContext);
11571       }
11572 
11573       // If the decl has a non-null name, make accessible in the current scope.
11574       if (!D->getName().empty())
11575         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11576 
11577       // Similarly, dive into enums and fish their constants out, making them
11578       // accessible in this scope.
11579       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11580         for (auto *EI : ED->enumerators())
11581           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11582       }
11583     }
11584   }
11585 
11586   // Ensure that the function's exception specification is instantiated.
11587   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11588     ResolveExceptionSpec(D->getLocation(), FPT);
11589 
11590   // dllimport cannot be applied to non-inline function definitions.
11591   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11592       !FD->isTemplateInstantiation()) {
11593     assert(!FD->hasAttr<DLLExportAttr>());
11594     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11595     FD->setInvalidDecl();
11596     return D;
11597   }
11598   // We want to attach documentation to original Decl (which might be
11599   // a function template).
11600   ActOnDocumentableDecl(D);
11601   if (getCurLexicalContext()->isObjCContainer() &&
11602       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11603       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11604     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11605 
11606   return D;
11607 }
11608 
11609 /// \brief Given the set of return statements within a function body,
11610 /// compute the variables that are subject to the named return value
11611 /// optimization.
11612 ///
11613 /// Each of the variables that is subject to the named return value
11614 /// optimization will be marked as NRVO variables in the AST, and any
11615 /// return statement that has a marked NRVO variable as its NRVO candidate can
11616 /// use the named return value optimization.
11617 ///
11618 /// This function applies a very simplistic algorithm for NRVO: if every return
11619 /// statement in the scope of a variable has the same NRVO candidate, that
11620 /// candidate is an NRVO variable.
11621 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11622   ReturnStmt **Returns = Scope->Returns.data();
11623 
11624   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11625     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11626       if (!NRVOCandidate->isNRVOVariable())
11627         Returns[I]->setNRVOCandidate(nullptr);
11628     }
11629   }
11630 }
11631 
11632 bool Sema::canDelayFunctionBody(const Declarator &D) {
11633   // We can't delay parsing the body of a constexpr function template (yet).
11634   if (D.getDeclSpec().isConstexprSpecified())
11635     return false;
11636 
11637   // We can't delay parsing the body of a function template with a deduced
11638   // return type (yet).
11639   if (D.getDeclSpec().containsPlaceholderType()) {
11640     // If the placeholder introduces a non-deduced trailing return type,
11641     // we can still delay parsing it.
11642     if (D.getNumTypeObjects()) {
11643       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11644       if (Outer.Kind == DeclaratorChunk::Function &&
11645           Outer.Fun.hasTrailingReturnType()) {
11646         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11647         return Ty.isNull() || !Ty->isUndeducedType();
11648       }
11649     }
11650     return false;
11651   }
11652 
11653   return true;
11654 }
11655 
11656 bool Sema::canSkipFunctionBody(Decl *D) {
11657   // We cannot skip the body of a function (or function template) which is
11658   // constexpr, since we may need to evaluate its body in order to parse the
11659   // rest of the file.
11660   // We cannot skip the body of a function with an undeduced return type,
11661   // because any callers of that function need to know the type.
11662   if (const FunctionDecl *FD = D->getAsFunction())
11663     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11664       return false;
11665   return Consumer.shouldSkipFunctionBody(D);
11666 }
11667 
11668 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11669   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11670     FD->setHasSkippedBody();
11671   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11672     MD->setHasSkippedBody();
11673   return Decl;
11674 }
11675 
11676 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11677   return ActOnFinishFunctionBody(D, BodyArg, false);
11678 }
11679 
11680 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11681                                     bool IsInstantiation) {
11682   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11683 
11684   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11685   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11686 
11687   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11688     CheckCompletedCoroutineBody(FD, Body);
11689 
11690   if (FD) {
11691     FD->setBody(Body);
11692 
11693     if (getLangOpts().CPlusPlus14) {
11694       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11695           FD->getReturnType()->isUndeducedType()) {
11696         // If the function has a deduced result type but contains no 'return'
11697         // statements, the result type as written must be exactly 'auto', and
11698         // the deduced result type is 'void'.
11699         if (!FD->getReturnType()->getAs<AutoType>()) {
11700           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11701               << FD->getReturnType();
11702           FD->setInvalidDecl();
11703         } else {
11704           // Substitute 'void' for the 'auto' in the type.
11705           TypeLoc ResultType = getReturnTypeLoc(FD);
11706           Context.adjustDeducedFunctionResultType(
11707               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11708         }
11709       }
11710     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11711       // In C++11, we don't use 'auto' deduction rules for lambda call
11712       // operators because we don't support return type deduction.
11713       auto *LSI = getCurLambda();
11714       if (LSI->HasImplicitReturnType) {
11715         deduceClosureReturnType(*LSI);
11716 
11717         // C++11 [expr.prim.lambda]p4:
11718         //   [...] if there are no return statements in the compound-statement
11719         //   [the deduced type is] the type void
11720         QualType RetType =
11721             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11722 
11723         // Update the return type to the deduced type.
11724         const FunctionProtoType *Proto =
11725             FD->getType()->getAs<FunctionProtoType>();
11726         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11727                                             Proto->getExtProtoInfo()));
11728       }
11729     }
11730 
11731     // The only way to be included in UndefinedButUsed is if there is an
11732     // ODR use before the definition. Avoid the expensive map lookup if this
11733     // is the first declaration.
11734     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11735       if (!FD->isExternallyVisible())
11736         UndefinedButUsed.erase(FD);
11737       else if (FD->isInlined() &&
11738                !LangOpts.GNUInline &&
11739                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11740         UndefinedButUsed.erase(FD);
11741     }
11742 
11743     // If the function implicitly returns zero (like 'main') or is naked,
11744     // don't complain about missing return statements.
11745     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11746       WP.disableCheckFallThrough();
11747 
11748     // MSVC permits the use of pure specifier (=0) on function definition,
11749     // defined at class scope, warn about this non-standard construct.
11750     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11751       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11752 
11753     if (!FD->isInvalidDecl()) {
11754       // Don't diagnose unused parameters of defaulted or deleted functions.
11755       if (!FD->isDeleted() && !FD->isDefaulted())
11756         DiagnoseUnusedParameters(FD->parameters());
11757       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11758                                              FD->getReturnType(), FD);
11759 
11760       // If this is a structor, we need a vtable.
11761       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11762         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11763       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11764         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11765 
11766       // Try to apply the named return value optimization. We have to check
11767       // if we can do this here because lambdas keep return statements around
11768       // to deduce an implicit return type.
11769       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11770           !FD->isDependentContext())
11771         computeNRVO(Body, getCurFunction());
11772     }
11773 
11774     // GNU warning -Wmissing-prototypes:
11775     //   Warn if a global function is defined without a previous
11776     //   prototype declaration. This warning is issued even if the
11777     //   definition itself provides a prototype. The aim is to detect
11778     //   global functions that fail to be declared in header files.
11779     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11780     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11781       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11782 
11783       if (PossibleZeroParamPrototype) {
11784         // We found a declaration that is not a prototype,
11785         // but that could be a zero-parameter prototype
11786         if (TypeSourceInfo *TI =
11787                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11788           TypeLoc TL = TI->getTypeLoc();
11789           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11790             Diag(PossibleZeroParamPrototype->getLocation(),
11791                  diag::note_declaration_not_a_prototype)
11792                 << PossibleZeroParamPrototype
11793                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11794         }
11795       }
11796     }
11797 
11798     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11799       const CXXMethodDecl *KeyFunction;
11800       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11801           MD->isVirtual() &&
11802           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11803           MD == KeyFunction->getCanonicalDecl()) {
11804         // Update the key-function state if necessary for this ABI.
11805         if (FD->isInlined() &&
11806             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11807           Context.setNonKeyFunction(MD);
11808 
11809           // If the newly-chosen key function is already defined, then we
11810           // need to mark the vtable as used retroactively.
11811           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11812           const FunctionDecl *Definition;
11813           if (KeyFunction && KeyFunction->isDefined(Definition))
11814             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11815         } else {
11816           // We just defined they key function; mark the vtable as used.
11817           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11818         }
11819       }
11820     }
11821 
11822     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11823            "Function parsing confused");
11824   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11825     assert(MD == getCurMethodDecl() && "Method parsing confused");
11826     MD->setBody(Body);
11827     if (!MD->isInvalidDecl()) {
11828       DiagnoseUnusedParameters(MD->parameters());
11829       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11830                                              MD->getReturnType(), MD);
11831 
11832       if (Body)
11833         computeNRVO(Body, getCurFunction());
11834     }
11835     if (getCurFunction()->ObjCShouldCallSuper) {
11836       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11837         << MD->getSelector().getAsString();
11838       getCurFunction()->ObjCShouldCallSuper = false;
11839     }
11840     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11841       const ObjCMethodDecl *InitMethod = nullptr;
11842       bool isDesignated =
11843           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11844       assert(isDesignated && InitMethod);
11845       (void)isDesignated;
11846 
11847       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11848         auto IFace = MD->getClassInterface();
11849         if (!IFace)
11850           return false;
11851         auto SuperD = IFace->getSuperClass();
11852         if (!SuperD)
11853           return false;
11854         return SuperD->getIdentifier() ==
11855             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11856       };
11857       // Don't issue this warning for unavailable inits or direct subclasses
11858       // of NSObject.
11859       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11860         Diag(MD->getLocation(),
11861              diag::warn_objc_designated_init_missing_super_call);
11862         Diag(InitMethod->getLocation(),
11863              diag::note_objc_designated_init_marked_here);
11864       }
11865       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11866     }
11867     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11868       // Don't issue this warning for unavaialable inits.
11869       if (!MD->isUnavailable())
11870         Diag(MD->getLocation(),
11871              diag::warn_objc_secondary_init_missing_init_call);
11872       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11873     }
11874   } else {
11875     return nullptr;
11876   }
11877 
11878   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
11879     DiagnoseUnguardedAvailabilityViolations(dcl);
11880 
11881   assert(!getCurFunction()->ObjCShouldCallSuper &&
11882          "This should only be set for ObjC methods, which should have been "
11883          "handled in the block above.");
11884 
11885   // Verify and clean out per-function state.
11886   if (Body && (!FD || !FD->isDefaulted())) {
11887     // C++ constructors that have function-try-blocks can't have return
11888     // statements in the handlers of that block. (C++ [except.handle]p14)
11889     // Verify this.
11890     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11891       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11892 
11893     // Verify that gotos and switch cases don't jump into scopes illegally.
11894     if (getCurFunction()->NeedsScopeChecking() &&
11895         !PP.isCodeCompletionEnabled())
11896       DiagnoseInvalidJumps(Body);
11897 
11898     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11899       if (!Destructor->getParent()->isDependentType())
11900         CheckDestructor(Destructor);
11901 
11902       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11903                                              Destructor->getParent());
11904     }
11905 
11906     // If any errors have occurred, clear out any temporaries that may have
11907     // been leftover. This ensures that these temporaries won't be picked up for
11908     // deletion in some later function.
11909     if (getDiagnostics().hasErrorOccurred() ||
11910         getDiagnostics().getSuppressAllDiagnostics()) {
11911       DiscardCleanupsInEvaluationContext();
11912     }
11913     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11914         !isa<FunctionTemplateDecl>(dcl)) {
11915       // Since the body is valid, issue any analysis-based warnings that are
11916       // enabled.
11917       ActivePolicy = &WP;
11918     }
11919 
11920     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11921         (!CheckConstexprFunctionDecl(FD) ||
11922          !CheckConstexprFunctionBody(FD, Body)))
11923       FD->setInvalidDecl();
11924 
11925     if (FD && FD->hasAttr<NakedAttr>()) {
11926       for (const Stmt *S : Body->children()) {
11927         // Allow local register variables without initializer as they don't
11928         // require prologue.
11929         bool RegisterVariables = false;
11930         if (auto *DS = dyn_cast<DeclStmt>(S)) {
11931           for (const auto *Decl : DS->decls()) {
11932             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
11933               RegisterVariables =
11934                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
11935               if (!RegisterVariables)
11936                 break;
11937             }
11938           }
11939         }
11940         if (RegisterVariables)
11941           continue;
11942         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11943           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11944           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11945           FD->setInvalidDecl();
11946           break;
11947         }
11948       }
11949     }
11950 
11951     assert(ExprCleanupObjects.size() ==
11952                ExprEvalContexts.back().NumCleanupObjects &&
11953            "Leftover temporaries in function");
11954     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
11955     assert(MaybeODRUseExprs.empty() &&
11956            "Leftover expressions for odr-use checking");
11957   }
11958 
11959   if (!IsInstantiation)
11960     PopDeclContext();
11961 
11962   PopFunctionScopeInfo(ActivePolicy, dcl);
11963   // If any errors have occurred, clear out any temporaries that may have
11964   // been leftover. This ensures that these temporaries won't be picked up for
11965   // deletion in some later function.
11966   if (getDiagnostics().hasErrorOccurred()) {
11967     DiscardCleanupsInEvaluationContext();
11968   }
11969 
11970   return dcl;
11971 }
11972 
11973 /// When we finish delayed parsing of an attribute, we must attach it to the
11974 /// relevant Decl.
11975 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11976                                        ParsedAttributes &Attrs) {
11977   // Always attach attributes to the underlying decl.
11978   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11979     D = TD->getTemplatedDecl();
11980   ProcessDeclAttributeList(S, D, Attrs.getList());
11981 
11982   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11983     if (Method->isStatic())
11984       checkThisInStaticMemberFunctionAttributes(Method);
11985 }
11986 
11987 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11988 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11989 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11990                                           IdentifierInfo &II, Scope *S) {
11991   // Before we produce a declaration for an implicitly defined
11992   // function, see whether there was a locally-scoped declaration of
11993   // this name as a function or variable. If so, use that
11994   // (non-visible) declaration, and complain about it.
11995   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11996     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11997     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11998     return ExternCPrev;
11999   }
12000 
12001   // Extension in C99.  Legal in C90, but warn about it.
12002   unsigned diag_id;
12003   if (II.getName().startswith("__builtin_"))
12004     diag_id = diag::warn_builtin_unknown;
12005   else if (getLangOpts().C99)
12006     diag_id = diag::ext_implicit_function_decl;
12007   else
12008     diag_id = diag::warn_implicit_function_decl;
12009   Diag(Loc, diag_id) << &II;
12010 
12011   // Because typo correction is expensive, only do it if the implicit
12012   // function declaration is going to be treated as an error.
12013   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12014     TypoCorrection Corrected;
12015     if (S &&
12016         (Corrected = CorrectTypo(
12017              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12018              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12019       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12020                    /*ErrorRecovery*/false);
12021   }
12022 
12023   // Set a Declarator for the implicit definition: int foo();
12024   const char *Dummy;
12025   AttributeFactory attrFactory;
12026   DeclSpec DS(attrFactory);
12027   unsigned DiagID;
12028   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12029                                   Context.getPrintingPolicy());
12030   (void)Error; // Silence warning.
12031   assert(!Error && "Error setting up implicit decl!");
12032   SourceLocation NoLoc;
12033   Declarator D(DS, Declarator::BlockContext);
12034   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12035                                              /*IsAmbiguous=*/false,
12036                                              /*LParenLoc=*/NoLoc,
12037                                              /*Params=*/nullptr,
12038                                              /*NumParams=*/0,
12039                                              /*EllipsisLoc=*/NoLoc,
12040                                              /*RParenLoc=*/NoLoc,
12041                                              /*TypeQuals=*/0,
12042                                              /*RefQualifierIsLvalueRef=*/true,
12043                                              /*RefQualifierLoc=*/NoLoc,
12044                                              /*ConstQualifierLoc=*/NoLoc,
12045                                              /*VolatileQualifierLoc=*/NoLoc,
12046                                              /*RestrictQualifierLoc=*/NoLoc,
12047                                              /*MutableLoc=*/NoLoc,
12048                                              EST_None,
12049                                              /*ESpecRange=*/SourceRange(),
12050                                              /*Exceptions=*/nullptr,
12051                                              /*ExceptionRanges=*/nullptr,
12052                                              /*NumExceptions=*/0,
12053                                              /*NoexceptExpr=*/nullptr,
12054                                              /*ExceptionSpecTokens=*/nullptr,
12055                                              Loc, Loc, D),
12056                 DS.getAttributes(),
12057                 SourceLocation());
12058   D.SetIdentifier(&II, Loc);
12059 
12060   // Insert this function into translation-unit scope.
12061 
12062   DeclContext *PrevDC = CurContext;
12063   CurContext = Context.getTranslationUnitDecl();
12064 
12065   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12066   FD->setImplicit();
12067 
12068   CurContext = PrevDC;
12069 
12070   AddKnownFunctionAttributes(FD);
12071 
12072   return FD;
12073 }
12074 
12075 /// \brief Adds any function attributes that we know a priori based on
12076 /// the declaration of this function.
12077 ///
12078 /// These attributes can apply both to implicitly-declared builtins
12079 /// (like __builtin___printf_chk) or to library-declared functions
12080 /// like NSLog or printf.
12081 ///
12082 /// We need to check for duplicate attributes both here and where user-written
12083 /// attributes are applied to declarations.
12084 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12085   if (FD->isInvalidDecl())
12086     return;
12087 
12088   // If this is a built-in function, map its builtin attributes to
12089   // actual attributes.
12090   if (unsigned BuiltinID = FD->getBuiltinID()) {
12091     // Handle printf-formatting attributes.
12092     unsigned FormatIdx;
12093     bool HasVAListArg;
12094     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12095       if (!FD->hasAttr<FormatAttr>()) {
12096         const char *fmt = "printf";
12097         unsigned int NumParams = FD->getNumParams();
12098         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12099             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12100           fmt = "NSString";
12101         FD->addAttr(FormatAttr::CreateImplicit(Context,
12102                                                &Context.Idents.get(fmt),
12103                                                FormatIdx+1,
12104                                                HasVAListArg ? 0 : FormatIdx+2,
12105                                                FD->getLocation()));
12106       }
12107     }
12108     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12109                                              HasVAListArg)) {
12110      if (!FD->hasAttr<FormatAttr>())
12111        FD->addAttr(FormatAttr::CreateImplicit(Context,
12112                                               &Context.Idents.get("scanf"),
12113                                               FormatIdx+1,
12114                                               HasVAListArg ? 0 : FormatIdx+2,
12115                                               FD->getLocation()));
12116     }
12117 
12118     // Mark const if we don't care about errno and that is the only
12119     // thing preventing the function from being const. This allows
12120     // IRgen to use LLVM intrinsics for such functions.
12121     if (!getLangOpts().MathErrno &&
12122         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12123       if (!FD->hasAttr<ConstAttr>())
12124         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12125     }
12126 
12127     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12128         !FD->hasAttr<ReturnsTwiceAttr>())
12129       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12130                                          FD->getLocation()));
12131     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12132       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12133     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12134       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12135     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12136       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12137     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12138         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12139       // Add the appropriate attribute, depending on the CUDA compilation mode
12140       // and which target the builtin belongs to. For example, during host
12141       // compilation, aux builtins are __device__, while the rest are __host__.
12142       if (getLangOpts().CUDAIsDevice !=
12143           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12144         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12145       else
12146         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12147     }
12148   }
12149 
12150   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12151   // throw, add an implicit nothrow attribute to any extern "C" function we come
12152   // across.
12153   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12154       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12155     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12156     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12157       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12158   }
12159 
12160   IdentifierInfo *Name = FD->getIdentifier();
12161   if (!Name)
12162     return;
12163   if ((!getLangOpts().CPlusPlus &&
12164        FD->getDeclContext()->isTranslationUnit()) ||
12165       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12166        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12167        LinkageSpecDecl::lang_c)) {
12168     // Okay: this could be a libc/libm/Objective-C function we know
12169     // about.
12170   } else
12171     return;
12172 
12173   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12174     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12175     // target-specific builtins, perhaps?
12176     if (!FD->hasAttr<FormatAttr>())
12177       FD->addAttr(FormatAttr::CreateImplicit(Context,
12178                                              &Context.Idents.get("printf"), 2,
12179                                              Name->isStr("vasprintf") ? 0 : 3,
12180                                              FD->getLocation()));
12181   }
12182 
12183   if (Name->isStr("__CFStringMakeConstantString")) {
12184     // We already have a __builtin___CFStringMakeConstantString,
12185     // but builds that use -fno-constant-cfstrings don't go through that.
12186     if (!FD->hasAttr<FormatArgAttr>())
12187       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12188                                                 FD->getLocation()));
12189   }
12190 }
12191 
12192 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12193                                     TypeSourceInfo *TInfo) {
12194   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12195   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12196 
12197   if (!TInfo) {
12198     assert(D.isInvalidType() && "no declarator info for valid type");
12199     TInfo = Context.getTrivialTypeSourceInfo(T);
12200   }
12201 
12202   // Scope manipulation handled by caller.
12203   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12204                                            D.getLocStart(),
12205                                            D.getIdentifierLoc(),
12206                                            D.getIdentifier(),
12207                                            TInfo);
12208 
12209   // Bail out immediately if we have an invalid declaration.
12210   if (D.isInvalidType()) {
12211     NewTD->setInvalidDecl();
12212     return NewTD;
12213   }
12214 
12215   if (D.getDeclSpec().isModulePrivateSpecified()) {
12216     if (CurContext->isFunctionOrMethod())
12217       Diag(NewTD->getLocation(), diag::err_module_private_local)
12218         << 2 << NewTD->getDeclName()
12219         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12220         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12221     else
12222       NewTD->setModulePrivate();
12223   }
12224 
12225   // C++ [dcl.typedef]p8:
12226   //   If the typedef declaration defines an unnamed class (or
12227   //   enum), the first typedef-name declared by the declaration
12228   //   to be that class type (or enum type) is used to denote the
12229   //   class type (or enum type) for linkage purposes only.
12230   // We need to check whether the type was declared in the declaration.
12231   switch (D.getDeclSpec().getTypeSpecType()) {
12232   case TST_enum:
12233   case TST_struct:
12234   case TST_interface:
12235   case TST_union:
12236   case TST_class: {
12237     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12238     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12239     break;
12240   }
12241 
12242   default:
12243     break;
12244   }
12245 
12246   return NewTD;
12247 }
12248 
12249 /// \brief Check that this is a valid underlying type for an enum declaration.
12250 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12251   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12252   QualType T = TI->getType();
12253 
12254   if (T->isDependentType())
12255     return false;
12256 
12257   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12258     if (BT->isInteger())
12259       return false;
12260 
12261   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12262   return true;
12263 }
12264 
12265 /// Check whether this is a valid redeclaration of a previous enumeration.
12266 /// \return true if the redeclaration was invalid.
12267 bool Sema::CheckEnumRedeclaration(
12268     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12269     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12270   bool IsFixed = !EnumUnderlyingTy.isNull();
12271 
12272   if (IsScoped != Prev->isScoped()) {
12273     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12274       << Prev->isScoped();
12275     Diag(Prev->getLocation(), diag::note_previous_declaration);
12276     return true;
12277   }
12278 
12279   if (IsFixed && Prev->isFixed()) {
12280     if (!EnumUnderlyingTy->isDependentType() &&
12281         !Prev->getIntegerType()->isDependentType() &&
12282         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12283                                         Prev->getIntegerType())) {
12284       // TODO: Highlight the underlying type of the redeclaration.
12285       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12286         << EnumUnderlyingTy << Prev->getIntegerType();
12287       Diag(Prev->getLocation(), diag::note_previous_declaration)
12288           << Prev->getIntegerTypeRange();
12289       return true;
12290     }
12291   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12292     ;
12293   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12294     ;
12295   } else if (IsFixed != Prev->isFixed()) {
12296     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12297       << Prev->isFixed();
12298     Diag(Prev->getLocation(), diag::note_previous_declaration);
12299     return true;
12300   }
12301 
12302   return false;
12303 }
12304 
12305 /// \brief Get diagnostic %select index for tag kind for
12306 /// redeclaration diagnostic message.
12307 /// WARNING: Indexes apply to particular diagnostics only!
12308 ///
12309 /// \returns diagnostic %select index.
12310 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12311   switch (Tag) {
12312   case TTK_Struct: return 0;
12313   case TTK_Interface: return 1;
12314   case TTK_Class:  return 2;
12315   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12316   }
12317 }
12318 
12319 /// \brief Determine if tag kind is a class-key compatible with
12320 /// class for redeclaration (class, struct, or __interface).
12321 ///
12322 /// \returns true iff the tag kind is compatible.
12323 static bool isClassCompatTagKind(TagTypeKind Tag)
12324 {
12325   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12326 }
12327 
12328 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl) {
12329   if (isa<TypedefDecl>(PrevDecl))
12330     return NTK_Typedef;
12331   else if (isa<TypeAliasDecl>(PrevDecl))
12332     return NTK_TypeAlias;
12333   else if (isa<ClassTemplateDecl>(PrevDecl))
12334     return NTK_Template;
12335   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12336     return NTK_TypeAliasTemplate;
12337   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12338     return NTK_TemplateTemplateArgument;
12339   return NTK_Unknown;
12340 }
12341 
12342 /// \brief Determine whether a tag with a given kind is acceptable
12343 /// as a redeclaration of the given tag declaration.
12344 ///
12345 /// \returns true if the new tag kind is acceptable, false otherwise.
12346 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12347                                         TagTypeKind NewTag, bool isDefinition,
12348                                         SourceLocation NewTagLoc,
12349                                         const IdentifierInfo *Name) {
12350   // C++ [dcl.type.elab]p3:
12351   //   The class-key or enum keyword present in the
12352   //   elaborated-type-specifier shall agree in kind with the
12353   //   declaration to which the name in the elaborated-type-specifier
12354   //   refers. This rule also applies to the form of
12355   //   elaborated-type-specifier that declares a class-name or
12356   //   friend class since it can be construed as referring to the
12357   //   definition of the class. Thus, in any
12358   //   elaborated-type-specifier, the enum keyword shall be used to
12359   //   refer to an enumeration (7.2), the union class-key shall be
12360   //   used to refer to a union (clause 9), and either the class or
12361   //   struct class-key shall be used to refer to a class (clause 9)
12362   //   declared using the class or struct class-key.
12363   TagTypeKind OldTag = Previous->getTagKind();
12364   if (!isDefinition || !isClassCompatTagKind(NewTag))
12365     if (OldTag == NewTag)
12366       return true;
12367 
12368   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12369     // Warn about the struct/class tag mismatch.
12370     bool isTemplate = false;
12371     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12372       isTemplate = Record->getDescribedClassTemplate();
12373 
12374     if (!ActiveTemplateInstantiations.empty()) {
12375       // In a template instantiation, do not offer fix-its for tag mismatches
12376       // since they usually mess up the template instead of fixing the problem.
12377       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12378         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12379         << getRedeclDiagFromTagKind(OldTag);
12380       return true;
12381     }
12382 
12383     if (isDefinition) {
12384       // On definitions, check previous tags and issue a fix-it for each
12385       // one that doesn't match the current tag.
12386       if (Previous->getDefinition()) {
12387         // Don't suggest fix-its for redefinitions.
12388         return true;
12389       }
12390 
12391       bool previousMismatch = false;
12392       for (auto I : Previous->redecls()) {
12393         if (I->getTagKind() != NewTag) {
12394           if (!previousMismatch) {
12395             previousMismatch = true;
12396             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12397               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12398               << getRedeclDiagFromTagKind(I->getTagKind());
12399           }
12400           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12401             << getRedeclDiagFromTagKind(NewTag)
12402             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12403                  TypeWithKeyword::getTagTypeKindName(NewTag));
12404         }
12405       }
12406       return true;
12407     }
12408 
12409     // Check for a previous definition.  If current tag and definition
12410     // are same type, do nothing.  If no definition, but disagree with
12411     // with previous tag type, give a warning, but no fix-it.
12412     const TagDecl *Redecl = Previous->getDefinition() ?
12413                             Previous->getDefinition() : Previous;
12414     if (Redecl->getTagKind() == NewTag) {
12415       return true;
12416     }
12417 
12418     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12419       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12420       << getRedeclDiagFromTagKind(OldTag);
12421     Diag(Redecl->getLocation(), diag::note_previous_use);
12422 
12423     // If there is a previous definition, suggest a fix-it.
12424     if (Previous->getDefinition()) {
12425         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12426           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12427           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12428                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12429     }
12430 
12431     return true;
12432   }
12433   return false;
12434 }
12435 
12436 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12437 /// from an outer enclosing namespace or file scope inside a friend declaration.
12438 /// This should provide the commented out code in the following snippet:
12439 ///   namespace N {
12440 ///     struct X;
12441 ///     namespace M {
12442 ///       struct Y { friend struct /*N::*/ X; };
12443 ///     }
12444 ///   }
12445 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12446                                          SourceLocation NameLoc) {
12447   // While the decl is in a namespace, do repeated lookup of that name and see
12448   // if we get the same namespace back.  If we do not, continue until
12449   // translation unit scope, at which point we have a fully qualified NNS.
12450   SmallVector<IdentifierInfo *, 4> Namespaces;
12451   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12452   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12453     // This tag should be declared in a namespace, which can only be enclosed by
12454     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12455     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12456     if (!Namespace || Namespace->isAnonymousNamespace())
12457       return FixItHint();
12458     IdentifierInfo *II = Namespace->getIdentifier();
12459     Namespaces.push_back(II);
12460     NamedDecl *Lookup = SemaRef.LookupSingleName(
12461         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12462     if (Lookup == Namespace)
12463       break;
12464   }
12465 
12466   // Once we have all the namespaces, reverse them to go outermost first, and
12467   // build an NNS.
12468   SmallString<64> Insertion;
12469   llvm::raw_svector_ostream OS(Insertion);
12470   if (DC->isTranslationUnit())
12471     OS << "::";
12472   std::reverse(Namespaces.begin(), Namespaces.end());
12473   for (auto *II : Namespaces)
12474     OS << II->getName() << "::";
12475   return FixItHint::CreateInsertion(NameLoc, Insertion);
12476 }
12477 
12478 /// \brief Determine whether a tag originally declared in context \p OldDC can
12479 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12480 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12481 /// using-declaration).
12482 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12483                                          DeclContext *NewDC) {
12484   OldDC = OldDC->getRedeclContext();
12485   NewDC = NewDC->getRedeclContext();
12486 
12487   if (OldDC->Equals(NewDC))
12488     return true;
12489 
12490   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12491   // encloses the other).
12492   if (S.getLangOpts().MSVCCompat &&
12493       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12494     return true;
12495 
12496   return false;
12497 }
12498 
12499 /// Find the DeclContext in which a tag is implicitly declared if we see an
12500 /// elaborated type specifier in the specified context, and lookup finds
12501 /// nothing.
12502 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12503   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12504     DC = DC->getParent();
12505   return DC;
12506 }
12507 
12508 /// Find the Scope in which a tag is implicitly declared if we see an
12509 /// elaborated type specifier in the specified context, and lookup finds
12510 /// nothing.
12511 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12512   while (S->isClassScope() ||
12513          (LangOpts.CPlusPlus &&
12514           S->isFunctionPrototypeScope()) ||
12515          ((S->getFlags() & Scope::DeclScope) == 0) ||
12516          (S->getEntity() && S->getEntity()->isTransparentContext()))
12517     S = S->getParent();
12518   return S;
12519 }
12520 
12521 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12522 /// former case, Name will be non-null.  In the later case, Name will be null.
12523 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12524 /// reference/declaration/definition of a tag.
12525 ///
12526 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12527 /// trailing-type-specifier) other than one in an alias-declaration.
12528 ///
12529 /// \param SkipBody If non-null, will be set to indicate if the caller should
12530 /// skip the definition of this tag and treat it as if it were a declaration.
12531 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12532                      SourceLocation KWLoc, CXXScopeSpec &SS,
12533                      IdentifierInfo *Name, SourceLocation NameLoc,
12534                      AttributeList *Attr, AccessSpecifier AS,
12535                      SourceLocation ModulePrivateLoc,
12536                      MultiTemplateParamsArg TemplateParameterLists,
12537                      bool &OwnedDecl, bool &IsDependent,
12538                      SourceLocation ScopedEnumKWLoc,
12539                      bool ScopedEnumUsesClassTag,
12540                      TypeResult UnderlyingType,
12541                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12542   // If this is not a definition, it must have a name.
12543   IdentifierInfo *OrigName = Name;
12544   assert((Name != nullptr || TUK == TUK_Definition) &&
12545          "Nameless record must be a definition!");
12546   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12547 
12548   OwnedDecl = false;
12549   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12550   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12551 
12552   // FIXME: Check explicit specializations more carefully.
12553   bool isExplicitSpecialization = false;
12554   bool Invalid = false;
12555 
12556   // We only need to do this matching if we have template parameters
12557   // or a scope specifier, which also conveniently avoids this work
12558   // for non-C++ cases.
12559   if (TemplateParameterLists.size() > 0 ||
12560       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12561     if (TemplateParameterList *TemplateParams =
12562             MatchTemplateParametersToScopeSpecifier(
12563                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12564                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12565       if (Kind == TTK_Enum) {
12566         Diag(KWLoc, diag::err_enum_template);
12567         return nullptr;
12568       }
12569 
12570       if (TemplateParams->size() > 0) {
12571         // This is a declaration or definition of a class template (which may
12572         // be a member of another template).
12573 
12574         if (Invalid)
12575           return nullptr;
12576 
12577         OwnedDecl = false;
12578         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12579                                                SS, Name, NameLoc, Attr,
12580                                                TemplateParams, AS,
12581                                                ModulePrivateLoc,
12582                                                /*FriendLoc*/SourceLocation(),
12583                                                TemplateParameterLists.size()-1,
12584                                                TemplateParameterLists.data(),
12585                                                SkipBody);
12586         return Result.get();
12587       } else {
12588         // The "template<>" header is extraneous.
12589         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12590           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12591         isExplicitSpecialization = true;
12592       }
12593     }
12594   }
12595 
12596   // Figure out the underlying type if this a enum declaration. We need to do
12597   // this early, because it's needed to detect if this is an incompatible
12598   // redeclaration.
12599   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12600   bool EnumUnderlyingIsImplicit = false;
12601 
12602   if (Kind == TTK_Enum) {
12603     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12604       // No underlying type explicitly specified, or we failed to parse the
12605       // type, default to int.
12606       EnumUnderlying = Context.IntTy.getTypePtr();
12607     else if (UnderlyingType.get()) {
12608       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12609       // integral type; any cv-qualification is ignored.
12610       TypeSourceInfo *TI = nullptr;
12611       GetTypeFromParser(UnderlyingType.get(), &TI);
12612       EnumUnderlying = TI;
12613 
12614       if (CheckEnumUnderlyingType(TI))
12615         // Recover by falling back to int.
12616         EnumUnderlying = Context.IntTy.getTypePtr();
12617 
12618       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12619                                           UPPC_FixedUnderlyingType))
12620         EnumUnderlying = Context.IntTy.getTypePtr();
12621 
12622     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12623       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12624         // Microsoft enums are always of int type.
12625         EnumUnderlying = Context.IntTy.getTypePtr();
12626         EnumUnderlyingIsImplicit = true;
12627       }
12628     }
12629   }
12630 
12631   DeclContext *SearchDC = CurContext;
12632   DeclContext *DC = CurContext;
12633   bool isStdBadAlloc = false;
12634   bool isStdAlignValT = false;
12635 
12636   RedeclarationKind Redecl = ForRedeclaration;
12637   if (TUK == TUK_Friend || TUK == TUK_Reference)
12638     Redecl = NotForRedeclaration;
12639 
12640   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12641   if (Name && SS.isNotEmpty()) {
12642     // We have a nested-name tag ('struct foo::bar').
12643 
12644     // Check for invalid 'foo::'.
12645     if (SS.isInvalid()) {
12646       Name = nullptr;
12647       goto CreateNewDecl;
12648     }
12649 
12650     // If this is a friend or a reference to a class in a dependent
12651     // context, don't try to make a decl for it.
12652     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12653       DC = computeDeclContext(SS, false);
12654       if (!DC) {
12655         IsDependent = true;
12656         return nullptr;
12657       }
12658     } else {
12659       DC = computeDeclContext(SS, true);
12660       if (!DC) {
12661         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12662           << SS.getRange();
12663         return nullptr;
12664       }
12665     }
12666 
12667     if (RequireCompleteDeclContext(SS, DC))
12668       return nullptr;
12669 
12670     SearchDC = DC;
12671     // Look-up name inside 'foo::'.
12672     LookupQualifiedName(Previous, DC);
12673 
12674     if (Previous.isAmbiguous())
12675       return nullptr;
12676 
12677     if (Previous.empty()) {
12678       // Name lookup did not find anything. However, if the
12679       // nested-name-specifier refers to the current instantiation,
12680       // and that current instantiation has any dependent base
12681       // classes, we might find something at instantiation time: treat
12682       // this as a dependent elaborated-type-specifier.
12683       // But this only makes any sense for reference-like lookups.
12684       if (Previous.wasNotFoundInCurrentInstantiation() &&
12685           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12686         IsDependent = true;
12687         return nullptr;
12688       }
12689 
12690       // A tag 'foo::bar' must already exist.
12691       Diag(NameLoc, diag::err_not_tag_in_scope)
12692         << Kind << Name << DC << SS.getRange();
12693       Name = nullptr;
12694       Invalid = true;
12695       goto CreateNewDecl;
12696     }
12697   } else if (Name) {
12698     // C++14 [class.mem]p14:
12699     //   If T is the name of a class, then each of the following shall have a
12700     //   name different from T:
12701     //    -- every member of class T that is itself a type
12702     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12703         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12704       return nullptr;
12705 
12706     // If this is a named struct, check to see if there was a previous forward
12707     // declaration or definition.
12708     // FIXME: We're looking into outer scopes here, even when we
12709     // shouldn't be. Doing so can result in ambiguities that we
12710     // shouldn't be diagnosing.
12711     LookupName(Previous, S);
12712 
12713     // When declaring or defining a tag, ignore ambiguities introduced
12714     // by types using'ed into this scope.
12715     if (Previous.isAmbiguous() &&
12716         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12717       LookupResult::Filter F = Previous.makeFilter();
12718       while (F.hasNext()) {
12719         NamedDecl *ND = F.next();
12720         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12721                 SearchDC->getRedeclContext()))
12722           F.erase();
12723       }
12724       F.done();
12725     }
12726 
12727     // C++11 [namespace.memdef]p3:
12728     //   If the name in a friend declaration is neither qualified nor
12729     //   a template-id and the declaration is a function or an
12730     //   elaborated-type-specifier, the lookup to determine whether
12731     //   the entity has been previously declared shall not consider
12732     //   any scopes outside the innermost enclosing namespace.
12733     //
12734     // MSVC doesn't implement the above rule for types, so a friend tag
12735     // declaration may be a redeclaration of a type declared in an enclosing
12736     // scope.  They do implement this rule for friend functions.
12737     //
12738     // Does it matter that this should be by scope instead of by
12739     // semantic context?
12740     if (!Previous.empty() && TUK == TUK_Friend) {
12741       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12742       LookupResult::Filter F = Previous.makeFilter();
12743       bool FriendSawTagOutsideEnclosingNamespace = false;
12744       while (F.hasNext()) {
12745         NamedDecl *ND = F.next();
12746         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12747         if (DC->isFileContext() &&
12748             !EnclosingNS->Encloses(ND->getDeclContext())) {
12749           if (getLangOpts().MSVCCompat)
12750             FriendSawTagOutsideEnclosingNamespace = true;
12751           else
12752             F.erase();
12753         }
12754       }
12755       F.done();
12756 
12757       // Diagnose this MSVC extension in the easy case where lookup would have
12758       // unambiguously found something outside the enclosing namespace.
12759       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12760         NamedDecl *ND = Previous.getFoundDecl();
12761         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12762             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12763       }
12764     }
12765 
12766     // Note:  there used to be some attempt at recovery here.
12767     if (Previous.isAmbiguous())
12768       return nullptr;
12769 
12770     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12771       // FIXME: This makes sure that we ignore the contexts associated
12772       // with C structs, unions, and enums when looking for a matching
12773       // tag declaration or definition. See the similar lookup tweak
12774       // in Sema::LookupName; is there a better way to deal with this?
12775       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12776         SearchDC = SearchDC->getParent();
12777     }
12778   }
12779 
12780   if (Previous.isSingleResult() &&
12781       Previous.getFoundDecl()->isTemplateParameter()) {
12782     // Maybe we will complain about the shadowed template parameter.
12783     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12784     // Just pretend that we didn't see the previous declaration.
12785     Previous.clear();
12786   }
12787 
12788   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12789       DC->Equals(getStdNamespace())) {
12790     if (Name->isStr("bad_alloc")) {
12791       // This is a declaration of or a reference to "std::bad_alloc".
12792       isStdBadAlloc = true;
12793 
12794       // If std::bad_alloc has been implicitly declared (but made invisible to
12795       // name lookup), fill in this implicit declaration as the previous
12796       // declaration, so that the declarations get chained appropriately.
12797       if (Previous.empty() && StdBadAlloc)
12798         Previous.addDecl(getStdBadAlloc());
12799     } else if (Name->isStr("align_val_t")) {
12800       isStdAlignValT = true;
12801       if (Previous.empty() && StdAlignValT)
12802         Previous.addDecl(getStdAlignValT());
12803     }
12804   }
12805 
12806   // If we didn't find a previous declaration, and this is a reference
12807   // (or friend reference), move to the correct scope.  In C++, we
12808   // also need to do a redeclaration lookup there, just in case
12809   // there's a shadow friend decl.
12810   if (Name && Previous.empty() &&
12811       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12812     if (Invalid) goto CreateNewDecl;
12813     assert(SS.isEmpty());
12814 
12815     if (TUK == TUK_Reference) {
12816       // C++ [basic.scope.pdecl]p5:
12817       //   -- for an elaborated-type-specifier of the form
12818       //
12819       //          class-key identifier
12820       //
12821       //      if the elaborated-type-specifier is used in the
12822       //      decl-specifier-seq or parameter-declaration-clause of a
12823       //      function defined in namespace scope, the identifier is
12824       //      declared as a class-name in the namespace that contains
12825       //      the declaration; otherwise, except as a friend
12826       //      declaration, the identifier is declared in the smallest
12827       //      non-class, non-function-prototype scope that contains the
12828       //      declaration.
12829       //
12830       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12831       // C structs and unions.
12832       //
12833       // It is an error in C++ to declare (rather than define) an enum
12834       // type, including via an elaborated type specifier.  We'll
12835       // diagnose that later; for now, declare the enum in the same
12836       // scope as we would have picked for any other tag type.
12837       //
12838       // GNU C also supports this behavior as part of its incomplete
12839       // enum types extension, while GNU C++ does not.
12840       //
12841       // Find the context where we'll be declaring the tag.
12842       // FIXME: We would like to maintain the current DeclContext as the
12843       // lexical context,
12844       SearchDC = getTagInjectionContext(SearchDC);
12845 
12846       // Find the scope where we'll be declaring the tag.
12847       S = getTagInjectionScope(S, getLangOpts());
12848     } else {
12849       assert(TUK == TUK_Friend);
12850       // C++ [namespace.memdef]p3:
12851       //   If a friend declaration in a non-local class first declares a
12852       //   class or function, the friend class or function is a member of
12853       //   the innermost enclosing namespace.
12854       SearchDC = SearchDC->getEnclosingNamespaceContext();
12855     }
12856 
12857     // In C++, we need to do a redeclaration lookup to properly
12858     // diagnose some problems.
12859     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12860     // hidden declaration so that we don't get ambiguity errors when using a
12861     // type declared by an elaborated-type-specifier.  In C that is not correct
12862     // and we should instead merge compatible types found by lookup.
12863     if (getLangOpts().CPlusPlus) {
12864       Previous.setRedeclarationKind(ForRedeclaration);
12865       LookupQualifiedName(Previous, SearchDC);
12866     } else {
12867       Previous.setRedeclarationKind(ForRedeclaration);
12868       LookupName(Previous, S);
12869     }
12870   }
12871 
12872   // If we have a known previous declaration to use, then use it.
12873   if (Previous.empty() && SkipBody && SkipBody->Previous)
12874     Previous.addDecl(SkipBody->Previous);
12875 
12876   if (!Previous.empty()) {
12877     NamedDecl *PrevDecl = Previous.getFoundDecl();
12878     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12879 
12880     // It's okay to have a tag decl in the same scope as a typedef
12881     // which hides a tag decl in the same scope.  Finding this
12882     // insanity with a redeclaration lookup can only actually happen
12883     // in C++.
12884     //
12885     // This is also okay for elaborated-type-specifiers, which is
12886     // technically forbidden by the current standard but which is
12887     // okay according to the likely resolution of an open issue;
12888     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12889     if (getLangOpts().CPlusPlus) {
12890       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12891         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12892           TagDecl *Tag = TT->getDecl();
12893           if (Tag->getDeclName() == Name &&
12894               Tag->getDeclContext()->getRedeclContext()
12895                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12896             PrevDecl = Tag;
12897             Previous.clear();
12898             Previous.addDecl(Tag);
12899             Previous.resolveKind();
12900           }
12901         }
12902       }
12903     }
12904 
12905     // If this is a redeclaration of a using shadow declaration, it must
12906     // declare a tag in the same context. In MSVC mode, we allow a
12907     // redefinition if either context is within the other.
12908     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12909       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12910       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12911           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12912           !(OldTag && isAcceptableTagRedeclContext(
12913                           *this, OldTag->getDeclContext(), SearchDC))) {
12914         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12915         Diag(Shadow->getTargetDecl()->getLocation(),
12916              diag::note_using_decl_target);
12917         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12918             << 0;
12919         // Recover by ignoring the old declaration.
12920         Previous.clear();
12921         goto CreateNewDecl;
12922       }
12923     }
12924 
12925     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12926       // If this is a use of a previous tag, or if the tag is already declared
12927       // in the same scope (so that the definition/declaration completes or
12928       // rementions the tag), reuse the decl.
12929       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12930           isDeclInScope(DirectPrevDecl, SearchDC, S,
12931                         SS.isNotEmpty() || isExplicitSpecialization)) {
12932         // Make sure that this wasn't declared as an enum and now used as a
12933         // struct or something similar.
12934         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12935                                           TUK == TUK_Definition, KWLoc,
12936                                           Name)) {
12937           bool SafeToContinue
12938             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12939                Kind != TTK_Enum);
12940           if (SafeToContinue)
12941             Diag(KWLoc, diag::err_use_with_wrong_tag)
12942               << Name
12943               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12944                                               PrevTagDecl->getKindName());
12945           else
12946             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12947           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12948 
12949           if (SafeToContinue)
12950             Kind = PrevTagDecl->getTagKind();
12951           else {
12952             // Recover by making this an anonymous redefinition.
12953             Name = nullptr;
12954             Previous.clear();
12955             Invalid = true;
12956           }
12957         }
12958 
12959         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12960           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12961 
12962           // If this is an elaborated-type-specifier for a scoped enumeration,
12963           // the 'class' keyword is not necessary and not permitted.
12964           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12965             if (ScopedEnum)
12966               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12967                 << PrevEnum->isScoped()
12968                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12969             return PrevTagDecl;
12970           }
12971 
12972           QualType EnumUnderlyingTy;
12973           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12974             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12975           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12976             EnumUnderlyingTy = QualType(T, 0);
12977 
12978           // All conflicts with previous declarations are recovered by
12979           // returning the previous declaration, unless this is a definition,
12980           // in which case we want the caller to bail out.
12981           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12982                                      ScopedEnum, EnumUnderlyingTy,
12983                                      EnumUnderlyingIsImplicit, PrevEnum))
12984             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12985         }
12986 
12987         // C++11 [class.mem]p1:
12988         //   A member shall not be declared twice in the member-specification,
12989         //   except that a nested class or member class template can be declared
12990         //   and then later defined.
12991         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12992             S->isDeclScope(PrevDecl)) {
12993           Diag(NameLoc, diag::ext_member_redeclared);
12994           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12995         }
12996 
12997         if (!Invalid) {
12998           // If this is a use, just return the declaration we found, unless
12999           // we have attributes.
13000           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13001             if (Attr) {
13002               // FIXME: Diagnose these attributes. For now, we create a new
13003               // declaration to hold them.
13004             } else if (TUK == TUK_Reference &&
13005                        (PrevTagDecl->getFriendObjectKind() ==
13006                             Decl::FOK_Undeclared ||
13007                         PP.getModuleContainingLocation(
13008                             PrevDecl->getLocation()) !=
13009                             PP.getModuleContainingLocation(KWLoc)) &&
13010                        SS.isEmpty()) {
13011               // This declaration is a reference to an existing entity, but
13012               // has different visibility from that entity: it either makes
13013               // a friend visible or it makes a type visible in a new module.
13014               // In either case, create a new declaration. We only do this if
13015               // the declaration would have meant the same thing if no prior
13016               // declaration were found, that is, if it was found in the same
13017               // scope where we would have injected a declaration.
13018               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13019                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13020                 return PrevTagDecl;
13021               // This is in the injected scope, create a new declaration in
13022               // that scope.
13023               S = getTagInjectionScope(S, getLangOpts());
13024             } else {
13025               return PrevTagDecl;
13026             }
13027           }
13028 
13029           // Diagnose attempts to redefine a tag.
13030           if (TUK == TUK_Definition) {
13031             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13032               // If we're defining a specialization and the previous definition
13033               // is from an implicit instantiation, don't emit an error
13034               // here; we'll catch this in the general case below.
13035               bool IsExplicitSpecializationAfterInstantiation = false;
13036               if (isExplicitSpecialization) {
13037                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13038                   IsExplicitSpecializationAfterInstantiation =
13039                     RD->getTemplateSpecializationKind() !=
13040                     TSK_ExplicitSpecialization;
13041                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13042                   IsExplicitSpecializationAfterInstantiation =
13043                     ED->getTemplateSpecializationKind() !=
13044                     TSK_ExplicitSpecialization;
13045               }
13046 
13047               NamedDecl *Hidden = nullptr;
13048               if (SkipBody && getLangOpts().CPlusPlus &&
13049                   !hasVisibleDefinition(Def, &Hidden)) {
13050                 // There is a definition of this tag, but it is not visible. We
13051                 // explicitly make use of C++'s one definition rule here, and
13052                 // assume that this definition is identical to the hidden one
13053                 // we already have. Make the existing definition visible and
13054                 // use it in place of this one.
13055                 SkipBody->ShouldSkip = true;
13056                 makeMergedDefinitionVisible(Hidden, KWLoc);
13057                 return Def;
13058               } else if (!IsExplicitSpecializationAfterInstantiation) {
13059                 // A redeclaration in function prototype scope in C isn't
13060                 // visible elsewhere, so merely issue a warning.
13061                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13062                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13063                 else
13064                   Diag(NameLoc, diag::err_redefinition) << Name;
13065                 Diag(Def->getLocation(), diag::note_previous_definition);
13066                 // If this is a redefinition, recover by making this
13067                 // struct be anonymous, which will make any later
13068                 // references get the previous definition.
13069                 Name = nullptr;
13070                 Previous.clear();
13071                 Invalid = true;
13072               }
13073             } else {
13074               // If the type is currently being defined, complain
13075               // about a nested redefinition.
13076               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13077               if (TD->isBeingDefined()) {
13078                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13079                 Diag(PrevTagDecl->getLocation(),
13080                      diag::note_previous_definition);
13081                 Name = nullptr;
13082                 Previous.clear();
13083                 Invalid = true;
13084               }
13085             }
13086 
13087             // Okay, this is definition of a previously declared or referenced
13088             // tag. We're going to create a new Decl for it.
13089           }
13090 
13091           // Okay, we're going to make a redeclaration.  If this is some kind
13092           // of reference, make sure we build the redeclaration in the same DC
13093           // as the original, and ignore the current access specifier.
13094           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13095             SearchDC = PrevTagDecl->getDeclContext();
13096             AS = AS_none;
13097           }
13098         }
13099         // If we get here we have (another) forward declaration or we
13100         // have a definition.  Just create a new decl.
13101 
13102       } else {
13103         // If we get here, this is a definition of a new tag type in a nested
13104         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13105         // new decl/type.  We set PrevDecl to NULL so that the entities
13106         // have distinct types.
13107         Previous.clear();
13108       }
13109       // If we get here, we're going to create a new Decl. If PrevDecl
13110       // is non-NULL, it's a definition of the tag declared by
13111       // PrevDecl. If it's NULL, we have a new definition.
13112 
13113     // Otherwise, PrevDecl is not a tag, but was found with tag
13114     // lookup.  This is only actually possible in C++, where a few
13115     // things like templates still live in the tag namespace.
13116     } else {
13117       // Use a better diagnostic if an elaborated-type-specifier
13118       // found the wrong kind of type on the first
13119       // (non-redeclaration) lookup.
13120       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13121           !Previous.isForRedeclaration()) {
13122         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl);
13123         Diag(NameLoc, diag::err_tag_reference_non_tag) << NTK;
13124         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13125         Invalid = true;
13126 
13127       // Otherwise, only diagnose if the declaration is in scope.
13128       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13129                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13130         // do nothing
13131 
13132       // Diagnose implicit declarations introduced by elaborated types.
13133       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13134         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl);
13135         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13136         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13137         Invalid = true;
13138 
13139       // Otherwise it's a declaration.  Call out a particularly common
13140       // case here.
13141       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13142         unsigned Kind = 0;
13143         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13144         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13145           << Name << Kind << TND->getUnderlyingType();
13146         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13147         Invalid = true;
13148 
13149       // Otherwise, diagnose.
13150       } else {
13151         // The tag name clashes with something else in the target scope,
13152         // issue an error and recover by making this tag be anonymous.
13153         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13154         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13155         Name = nullptr;
13156         Invalid = true;
13157       }
13158 
13159       // The existing declaration isn't relevant to us; we're in a
13160       // new scope, so clear out the previous declaration.
13161       Previous.clear();
13162     }
13163   }
13164 
13165 CreateNewDecl:
13166 
13167   TagDecl *PrevDecl = nullptr;
13168   if (Previous.isSingleResult())
13169     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13170 
13171   // If there is an identifier, use the location of the identifier as the
13172   // location of the decl, otherwise use the location of the struct/union
13173   // keyword.
13174   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13175 
13176   // Otherwise, create a new declaration. If there is a previous
13177   // declaration of the same entity, the two will be linked via
13178   // PrevDecl.
13179   TagDecl *New;
13180 
13181   bool IsForwardReference = false;
13182   if (Kind == TTK_Enum) {
13183     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13184     // enum X { A, B, C } D;    D should chain to X.
13185     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13186                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13187                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13188 
13189     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13190       StdAlignValT = cast<EnumDecl>(New);
13191 
13192     // If this is an undefined enum, warn.
13193     if (TUK != TUK_Definition && !Invalid) {
13194       TagDecl *Def;
13195       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13196           cast<EnumDecl>(New)->isFixed()) {
13197         // C++0x: 7.2p2: opaque-enum-declaration.
13198         // Conflicts are diagnosed above. Do nothing.
13199       }
13200       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13201         Diag(Loc, diag::ext_forward_ref_enum_def)
13202           << New;
13203         Diag(Def->getLocation(), diag::note_previous_definition);
13204       } else {
13205         unsigned DiagID = diag::ext_forward_ref_enum;
13206         if (getLangOpts().MSVCCompat)
13207           DiagID = diag::ext_ms_forward_ref_enum;
13208         else if (getLangOpts().CPlusPlus)
13209           DiagID = diag::err_forward_ref_enum;
13210         Diag(Loc, DiagID);
13211 
13212         // If this is a forward-declared reference to an enumeration, make a
13213         // note of it; we won't actually be introducing the declaration into
13214         // the declaration context.
13215         if (TUK == TUK_Reference)
13216           IsForwardReference = true;
13217       }
13218     }
13219 
13220     if (EnumUnderlying) {
13221       EnumDecl *ED = cast<EnumDecl>(New);
13222       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13223         ED->setIntegerTypeSourceInfo(TI);
13224       else
13225         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13226       ED->setPromotionType(ED->getIntegerType());
13227     }
13228   } else {
13229     // struct/union/class
13230 
13231     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13232     // struct X { int A; } D;    D should chain to X.
13233     if (getLangOpts().CPlusPlus) {
13234       // FIXME: Look for a way to use RecordDecl for simple structs.
13235       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13236                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13237 
13238       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13239         StdBadAlloc = cast<CXXRecordDecl>(New);
13240     } else
13241       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13242                                cast_or_null<RecordDecl>(PrevDecl));
13243   }
13244 
13245   // C++11 [dcl.type]p3:
13246   //   A type-specifier-seq shall not define a class or enumeration [...].
13247   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13248     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13249       << Context.getTagDeclType(New);
13250     Invalid = true;
13251   }
13252 
13253   // Maybe add qualifier info.
13254   if (SS.isNotEmpty()) {
13255     if (SS.isSet()) {
13256       // If this is either a declaration or a definition, check the
13257       // nested-name-specifier against the current context. We don't do this
13258       // for explicit specializations, because they have similar checking
13259       // (with more specific diagnostics) in the call to
13260       // CheckMemberSpecialization, below.
13261       if (!isExplicitSpecialization &&
13262           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13263           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13264         Invalid = true;
13265 
13266       New->setQualifierInfo(SS.getWithLocInContext(Context));
13267       if (TemplateParameterLists.size() > 0) {
13268         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13269       }
13270     }
13271     else
13272       Invalid = true;
13273   }
13274 
13275   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13276     // Add alignment attributes if necessary; these attributes are checked when
13277     // the ASTContext lays out the structure.
13278     //
13279     // It is important for implementing the correct semantics that this
13280     // happen here (in act on tag decl). The #pragma pack stack is
13281     // maintained as a result of parser callbacks which can occur at
13282     // many points during the parsing of a struct declaration (because
13283     // the #pragma tokens are effectively skipped over during the
13284     // parsing of the struct).
13285     if (TUK == TUK_Definition) {
13286       AddAlignmentAttributesForRecord(RD);
13287       AddMsStructLayoutForRecord(RD);
13288     }
13289   }
13290 
13291   if (ModulePrivateLoc.isValid()) {
13292     if (isExplicitSpecialization)
13293       Diag(New->getLocation(), diag::err_module_private_specialization)
13294         << 2
13295         << FixItHint::CreateRemoval(ModulePrivateLoc);
13296     // __module_private__ does not apply to local classes. However, we only
13297     // diagnose this as an error when the declaration specifiers are
13298     // freestanding. Here, we just ignore the __module_private__.
13299     else if (!SearchDC->isFunctionOrMethod())
13300       New->setModulePrivate();
13301   }
13302 
13303   // If this is a specialization of a member class (of a class template),
13304   // check the specialization.
13305   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13306     Invalid = true;
13307 
13308   // If we're declaring or defining a tag in function prototype scope in C,
13309   // note that this type can only be used within the function and add it to
13310   // the list of decls to inject into the function definition scope.
13311   if ((Name || Kind == TTK_Enum) &&
13312       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13313     if (getLangOpts().CPlusPlus) {
13314       // C++ [dcl.fct]p6:
13315       //   Types shall not be defined in return or parameter types.
13316       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13317         Diag(Loc, diag::err_type_defined_in_param_type)
13318             << Name;
13319         Invalid = true;
13320       }
13321     } else if (!PrevDecl) {
13322       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13323     }
13324     DeclsInPrototypeScope.push_back(New);
13325   }
13326 
13327   if (Invalid)
13328     New->setInvalidDecl();
13329 
13330   if (Attr)
13331     ProcessDeclAttributeList(S, New, Attr);
13332 
13333   // Set the lexical context. If the tag has a C++ scope specifier, the
13334   // lexical context will be different from the semantic context.
13335   New->setLexicalDeclContext(CurContext);
13336 
13337   // Mark this as a friend decl if applicable.
13338   // In Microsoft mode, a friend declaration also acts as a forward
13339   // declaration so we always pass true to setObjectOfFriendDecl to make
13340   // the tag name visible.
13341   if (TUK == TUK_Friend)
13342     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13343 
13344   // Set the access specifier.
13345   if (!Invalid && SearchDC->isRecord())
13346     SetMemberAccessSpecifier(New, PrevDecl, AS);
13347 
13348   if (TUK == TUK_Definition)
13349     New->startDefinition();
13350 
13351   // If this has an identifier, add it to the scope stack.
13352   if (TUK == TUK_Friend) {
13353     // We might be replacing an existing declaration in the lookup tables;
13354     // if so, borrow its access specifier.
13355     if (PrevDecl)
13356       New->setAccess(PrevDecl->getAccess());
13357 
13358     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13359     DC->makeDeclVisibleInContext(New);
13360     if (Name) // can be null along some error paths
13361       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13362         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13363   } else if (Name) {
13364     S = getNonFieldDeclScope(S);
13365     PushOnScopeChains(New, S, !IsForwardReference);
13366     if (IsForwardReference)
13367       SearchDC->makeDeclVisibleInContext(New);
13368   } else {
13369     CurContext->addDecl(New);
13370   }
13371 
13372   // If this is the C FILE type, notify the AST context.
13373   if (IdentifierInfo *II = New->getIdentifier())
13374     if (!New->isInvalidDecl() &&
13375         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13376         II->isStr("FILE"))
13377       Context.setFILEDecl(New);
13378 
13379   if (PrevDecl)
13380     mergeDeclAttributes(New, PrevDecl);
13381 
13382   // If there's a #pragma GCC visibility in scope, set the visibility of this
13383   // record.
13384   AddPushedVisibilityAttribute(New);
13385 
13386   OwnedDecl = true;
13387   // In C++, don't return an invalid declaration. We can't recover well from
13388   // the cases where we make the type anonymous.
13389   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13390 }
13391 
13392 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13393   AdjustDeclIfTemplate(TagD);
13394   TagDecl *Tag = cast<TagDecl>(TagD);
13395 
13396   // Enter the tag context.
13397   PushDeclContext(S, Tag);
13398 
13399   ActOnDocumentableDecl(TagD);
13400 
13401   // If there's a #pragma GCC visibility in scope, set the visibility of this
13402   // record.
13403   AddPushedVisibilityAttribute(Tag);
13404 }
13405 
13406 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13407   assert(isa<ObjCContainerDecl>(IDecl) &&
13408          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13409   DeclContext *OCD = cast<DeclContext>(IDecl);
13410   assert(getContainingDC(OCD) == CurContext &&
13411       "The next DeclContext should be lexically contained in the current one.");
13412   CurContext = OCD;
13413   return IDecl;
13414 }
13415 
13416 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13417                                            SourceLocation FinalLoc,
13418                                            bool IsFinalSpelledSealed,
13419                                            SourceLocation LBraceLoc) {
13420   AdjustDeclIfTemplate(TagD);
13421   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13422 
13423   FieldCollector->StartClass();
13424 
13425   if (!Record->getIdentifier())
13426     return;
13427 
13428   if (FinalLoc.isValid())
13429     Record->addAttr(new (Context)
13430                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13431 
13432   // C++ [class]p2:
13433   //   [...] The class-name is also inserted into the scope of the
13434   //   class itself; this is known as the injected-class-name. For
13435   //   purposes of access checking, the injected-class-name is treated
13436   //   as if it were a public member name.
13437   CXXRecordDecl *InjectedClassName
13438     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13439                             Record->getLocStart(), Record->getLocation(),
13440                             Record->getIdentifier(),
13441                             /*PrevDecl=*/nullptr,
13442                             /*DelayTypeCreation=*/true);
13443   Context.getTypeDeclType(InjectedClassName, Record);
13444   InjectedClassName->setImplicit();
13445   InjectedClassName->setAccess(AS_public);
13446   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13447       InjectedClassName->setDescribedClassTemplate(Template);
13448   PushOnScopeChains(InjectedClassName, S);
13449   assert(InjectedClassName->isInjectedClassName() &&
13450          "Broken injected-class-name");
13451 }
13452 
13453 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13454                                     SourceRange BraceRange) {
13455   AdjustDeclIfTemplate(TagD);
13456   TagDecl *Tag = cast<TagDecl>(TagD);
13457   Tag->setBraceRange(BraceRange);
13458 
13459   // Make sure we "complete" the definition even it is invalid.
13460   if (Tag->isBeingDefined()) {
13461     assert(Tag->isInvalidDecl() && "We should already have completed it");
13462     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13463       RD->completeDefinition();
13464   }
13465 
13466   if (isa<CXXRecordDecl>(Tag))
13467     FieldCollector->FinishClass();
13468 
13469   // Exit this scope of this tag's definition.
13470   PopDeclContext();
13471 
13472   if (getCurLexicalContext()->isObjCContainer() &&
13473       Tag->getDeclContext()->isFileContext())
13474     Tag->setTopLevelDeclInObjCContainer();
13475 
13476   // Notify the consumer that we've defined a tag.
13477   if (!Tag->isInvalidDecl())
13478     Consumer.HandleTagDeclDefinition(Tag);
13479 }
13480 
13481 void Sema::ActOnObjCContainerFinishDefinition() {
13482   // Exit this scope of this interface definition.
13483   PopDeclContext();
13484 }
13485 
13486 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13487   assert(DC == CurContext && "Mismatch of container contexts");
13488   OriginalLexicalContext = DC;
13489   ActOnObjCContainerFinishDefinition();
13490 }
13491 
13492 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13493   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13494   OriginalLexicalContext = nullptr;
13495 }
13496 
13497 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13498   AdjustDeclIfTemplate(TagD);
13499   TagDecl *Tag = cast<TagDecl>(TagD);
13500   Tag->setInvalidDecl();
13501 
13502   // Make sure we "complete" the definition even it is invalid.
13503   if (Tag->isBeingDefined()) {
13504     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13505       RD->completeDefinition();
13506   }
13507 
13508   // We're undoing ActOnTagStartDefinition here, not
13509   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13510   // the FieldCollector.
13511 
13512   PopDeclContext();
13513 }
13514 
13515 // Note that FieldName may be null for anonymous bitfields.
13516 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13517                                 IdentifierInfo *FieldName,
13518                                 QualType FieldTy, bool IsMsStruct,
13519                                 Expr *BitWidth, bool *ZeroWidth) {
13520   // Default to true; that shouldn't confuse checks for emptiness
13521   if (ZeroWidth)
13522     *ZeroWidth = true;
13523 
13524   // C99 6.7.2.1p4 - verify the field type.
13525   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13526   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13527     // Handle incomplete types with specific error.
13528     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13529       return ExprError();
13530     if (FieldName)
13531       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13532         << FieldName << FieldTy << BitWidth->getSourceRange();
13533     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13534       << FieldTy << BitWidth->getSourceRange();
13535   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13536                                              UPPC_BitFieldWidth))
13537     return ExprError();
13538 
13539   // If the bit-width is type- or value-dependent, don't try to check
13540   // it now.
13541   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13542     return BitWidth;
13543 
13544   llvm::APSInt Value;
13545   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13546   if (ICE.isInvalid())
13547     return ICE;
13548   BitWidth = ICE.get();
13549 
13550   if (Value != 0 && ZeroWidth)
13551     *ZeroWidth = false;
13552 
13553   // Zero-width bitfield is ok for anonymous field.
13554   if (Value == 0 && FieldName)
13555     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13556 
13557   if (Value.isSigned() && Value.isNegative()) {
13558     if (FieldName)
13559       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13560                << FieldName << Value.toString(10);
13561     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13562       << Value.toString(10);
13563   }
13564 
13565   if (!FieldTy->isDependentType()) {
13566     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13567     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13568     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13569 
13570     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13571     // ABI.
13572     bool CStdConstraintViolation =
13573         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13574     bool MSBitfieldViolation =
13575         Value.ugt(TypeStorageSize) &&
13576         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13577     if (CStdConstraintViolation || MSBitfieldViolation) {
13578       unsigned DiagWidth =
13579           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13580       if (FieldName)
13581         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13582                << FieldName << (unsigned)Value.getZExtValue()
13583                << !CStdConstraintViolation << DiagWidth;
13584 
13585       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13586              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13587              << DiagWidth;
13588     }
13589 
13590     // Warn on types where the user might conceivably expect to get all
13591     // specified bits as value bits: that's all integral types other than
13592     // 'bool'.
13593     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13594       if (FieldName)
13595         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13596             << FieldName << (unsigned)Value.getZExtValue()
13597             << (unsigned)TypeWidth;
13598       else
13599         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13600             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13601     }
13602   }
13603 
13604   return BitWidth;
13605 }
13606 
13607 /// ActOnField - Each field of a C struct/union is passed into this in order
13608 /// to create a FieldDecl object for it.
13609 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13610                        Declarator &D, Expr *BitfieldWidth) {
13611   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13612                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13613                                /*InitStyle=*/ICIS_NoInit, AS_public);
13614   return Res;
13615 }
13616 
13617 /// HandleField - Analyze a field of a C struct or a C++ data member.
13618 ///
13619 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13620                              SourceLocation DeclStart,
13621                              Declarator &D, Expr *BitWidth,
13622                              InClassInitStyle InitStyle,
13623                              AccessSpecifier AS) {
13624   if (D.isDecompositionDeclarator()) {
13625     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13626     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13627       << Decomp.getSourceRange();
13628     return nullptr;
13629   }
13630 
13631   IdentifierInfo *II = D.getIdentifier();
13632   SourceLocation Loc = DeclStart;
13633   if (II) Loc = D.getIdentifierLoc();
13634 
13635   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13636   QualType T = TInfo->getType();
13637   if (getLangOpts().CPlusPlus) {
13638     CheckExtraCXXDefaultArguments(D);
13639 
13640     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13641                                         UPPC_DataMemberType)) {
13642       D.setInvalidType();
13643       T = Context.IntTy;
13644       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13645     }
13646   }
13647 
13648   // TR 18037 does not allow fields to be declared with address spaces.
13649   if (T.getQualifiers().hasAddressSpace()) {
13650     Diag(Loc, diag::err_field_with_address_space);
13651     D.setInvalidType();
13652   }
13653 
13654   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13655   // used as structure or union field: image, sampler, event or block types.
13656   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13657                           T->isSamplerT() || T->isBlockPointerType())) {
13658     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13659     D.setInvalidType();
13660   }
13661 
13662   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13663 
13664   if (D.getDeclSpec().isInlineSpecified())
13665     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13666         << getLangOpts().CPlusPlus1z;
13667   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13668     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13669          diag::err_invalid_thread)
13670       << DeclSpec::getSpecifierName(TSCS);
13671 
13672   // Check to see if this name was declared as a member previously
13673   NamedDecl *PrevDecl = nullptr;
13674   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13675   LookupName(Previous, S);
13676   switch (Previous.getResultKind()) {
13677     case LookupResult::Found:
13678     case LookupResult::FoundUnresolvedValue:
13679       PrevDecl = Previous.getAsSingle<NamedDecl>();
13680       break;
13681 
13682     case LookupResult::FoundOverloaded:
13683       PrevDecl = Previous.getRepresentativeDecl();
13684       break;
13685 
13686     case LookupResult::NotFound:
13687     case LookupResult::NotFoundInCurrentInstantiation:
13688     case LookupResult::Ambiguous:
13689       break;
13690   }
13691   Previous.suppressDiagnostics();
13692 
13693   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13694     // Maybe we will complain about the shadowed template parameter.
13695     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13696     // Just pretend that we didn't see the previous declaration.
13697     PrevDecl = nullptr;
13698   }
13699 
13700   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13701     PrevDecl = nullptr;
13702 
13703   bool Mutable
13704     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13705   SourceLocation TSSL = D.getLocStart();
13706   FieldDecl *NewFD
13707     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13708                      TSSL, AS, PrevDecl, &D);
13709 
13710   if (NewFD->isInvalidDecl())
13711     Record->setInvalidDecl();
13712 
13713   if (D.getDeclSpec().isModulePrivateSpecified())
13714     NewFD->setModulePrivate();
13715 
13716   if (NewFD->isInvalidDecl() && PrevDecl) {
13717     // Don't introduce NewFD into scope; there's already something
13718     // with the same name in the same scope.
13719   } else if (II) {
13720     PushOnScopeChains(NewFD, S);
13721   } else
13722     Record->addDecl(NewFD);
13723 
13724   return NewFD;
13725 }
13726 
13727 /// \brief Build a new FieldDecl and check its well-formedness.
13728 ///
13729 /// This routine builds a new FieldDecl given the fields name, type,
13730 /// record, etc. \p PrevDecl should refer to any previous declaration
13731 /// with the same name and in the same scope as the field to be
13732 /// created.
13733 ///
13734 /// \returns a new FieldDecl.
13735 ///
13736 /// \todo The Declarator argument is a hack. It will be removed once
13737 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13738                                 TypeSourceInfo *TInfo,
13739                                 RecordDecl *Record, SourceLocation Loc,
13740                                 bool Mutable, Expr *BitWidth,
13741                                 InClassInitStyle InitStyle,
13742                                 SourceLocation TSSL,
13743                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13744                                 Declarator *D) {
13745   IdentifierInfo *II = Name.getAsIdentifierInfo();
13746   bool InvalidDecl = false;
13747   if (D) InvalidDecl = D->isInvalidType();
13748 
13749   // If we receive a broken type, recover by assuming 'int' and
13750   // marking this declaration as invalid.
13751   if (T.isNull()) {
13752     InvalidDecl = true;
13753     T = Context.IntTy;
13754   }
13755 
13756   QualType EltTy = Context.getBaseElementType(T);
13757   if (!EltTy->isDependentType()) {
13758     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13759       // Fields of incomplete type force their record to be invalid.
13760       Record->setInvalidDecl();
13761       InvalidDecl = true;
13762     } else {
13763       NamedDecl *Def;
13764       EltTy->isIncompleteType(&Def);
13765       if (Def && Def->isInvalidDecl()) {
13766         Record->setInvalidDecl();
13767         InvalidDecl = true;
13768       }
13769     }
13770   }
13771 
13772   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13773   if (BitWidth && getLangOpts().OpenCL) {
13774     Diag(Loc, diag::err_opencl_bitfields);
13775     InvalidDecl = true;
13776   }
13777 
13778   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13779   // than a variably modified type.
13780   if (!InvalidDecl && T->isVariablyModifiedType()) {
13781     bool SizeIsNegative;
13782     llvm::APSInt Oversized;
13783 
13784     TypeSourceInfo *FixedTInfo =
13785       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13786                                                     SizeIsNegative,
13787                                                     Oversized);
13788     if (FixedTInfo) {
13789       Diag(Loc, diag::warn_illegal_constant_array_size);
13790       TInfo = FixedTInfo;
13791       T = FixedTInfo->getType();
13792     } else {
13793       if (SizeIsNegative)
13794         Diag(Loc, diag::err_typecheck_negative_array_size);
13795       else if (Oversized.getBoolValue())
13796         Diag(Loc, diag::err_array_too_large)
13797           << Oversized.toString(10);
13798       else
13799         Diag(Loc, diag::err_typecheck_field_variable_size);
13800       InvalidDecl = true;
13801     }
13802   }
13803 
13804   // Fields can not have abstract class types
13805   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13806                                              diag::err_abstract_type_in_decl,
13807                                              AbstractFieldType))
13808     InvalidDecl = true;
13809 
13810   bool ZeroWidth = false;
13811   if (InvalidDecl)
13812     BitWidth = nullptr;
13813   // If this is declared as a bit-field, check the bit-field.
13814   if (BitWidth) {
13815     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13816                               &ZeroWidth).get();
13817     if (!BitWidth) {
13818       InvalidDecl = true;
13819       BitWidth = nullptr;
13820       ZeroWidth = false;
13821     }
13822   }
13823 
13824   // Check that 'mutable' is consistent with the type of the declaration.
13825   if (!InvalidDecl && Mutable) {
13826     unsigned DiagID = 0;
13827     if (T->isReferenceType())
13828       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13829                                         : diag::err_mutable_reference;
13830     else if (T.isConstQualified())
13831       DiagID = diag::err_mutable_const;
13832 
13833     if (DiagID) {
13834       SourceLocation ErrLoc = Loc;
13835       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13836         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13837       Diag(ErrLoc, DiagID);
13838       if (DiagID != diag::ext_mutable_reference) {
13839         Mutable = false;
13840         InvalidDecl = true;
13841       }
13842     }
13843   }
13844 
13845   // C++11 [class.union]p8 (DR1460):
13846   //   At most one variant member of a union may have a
13847   //   brace-or-equal-initializer.
13848   if (InitStyle != ICIS_NoInit)
13849     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13850 
13851   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13852                                        BitWidth, Mutable, InitStyle);
13853   if (InvalidDecl)
13854     NewFD->setInvalidDecl();
13855 
13856   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13857     Diag(Loc, diag::err_duplicate_member) << II;
13858     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13859     NewFD->setInvalidDecl();
13860   }
13861 
13862   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13863     if (Record->isUnion()) {
13864       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13865         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13866         if (RDecl->getDefinition()) {
13867           // C++ [class.union]p1: An object of a class with a non-trivial
13868           // constructor, a non-trivial copy constructor, a non-trivial
13869           // destructor, or a non-trivial copy assignment operator
13870           // cannot be a member of a union, nor can an array of such
13871           // objects.
13872           if (CheckNontrivialField(NewFD))
13873             NewFD->setInvalidDecl();
13874         }
13875       }
13876 
13877       // C++ [class.union]p1: If a union contains a member of reference type,
13878       // the program is ill-formed, except when compiling with MSVC extensions
13879       // enabled.
13880       if (EltTy->isReferenceType()) {
13881         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13882                                     diag::ext_union_member_of_reference_type :
13883                                     diag::err_union_member_of_reference_type)
13884           << NewFD->getDeclName() << EltTy;
13885         if (!getLangOpts().MicrosoftExt)
13886           NewFD->setInvalidDecl();
13887       }
13888     }
13889   }
13890 
13891   // FIXME: We need to pass in the attributes given an AST
13892   // representation, not a parser representation.
13893   if (D) {
13894     // FIXME: The current scope is almost... but not entirely... correct here.
13895     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13896 
13897     if (NewFD->hasAttrs())
13898       CheckAlignasUnderalignment(NewFD);
13899   }
13900 
13901   // In auto-retain/release, infer strong retension for fields of
13902   // retainable type.
13903   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13904     NewFD->setInvalidDecl();
13905 
13906   if (T.isObjCGCWeak())
13907     Diag(Loc, diag::warn_attribute_weak_on_field);
13908 
13909   NewFD->setAccess(AS);
13910   return NewFD;
13911 }
13912 
13913 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13914   assert(FD);
13915   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13916 
13917   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13918     return false;
13919 
13920   QualType EltTy = Context.getBaseElementType(FD->getType());
13921   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13922     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13923     if (RDecl->getDefinition()) {
13924       // We check for copy constructors before constructors
13925       // because otherwise we'll never get complaints about
13926       // copy constructors.
13927 
13928       CXXSpecialMember member = CXXInvalid;
13929       // We're required to check for any non-trivial constructors. Since the
13930       // implicit default constructor is suppressed if there are any
13931       // user-declared constructors, we just need to check that there is a
13932       // trivial default constructor and a trivial copy constructor. (We don't
13933       // worry about move constructors here, since this is a C++98 check.)
13934       if (RDecl->hasNonTrivialCopyConstructor())
13935         member = CXXCopyConstructor;
13936       else if (!RDecl->hasTrivialDefaultConstructor())
13937         member = CXXDefaultConstructor;
13938       else if (RDecl->hasNonTrivialCopyAssignment())
13939         member = CXXCopyAssignment;
13940       else if (RDecl->hasNonTrivialDestructor())
13941         member = CXXDestructor;
13942 
13943       if (member != CXXInvalid) {
13944         if (!getLangOpts().CPlusPlus11 &&
13945             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13946           // Objective-C++ ARC: it is an error to have a non-trivial field of
13947           // a union. However, system headers in Objective-C programs
13948           // occasionally have Objective-C lifetime objects within unions,
13949           // and rather than cause the program to fail, we make those
13950           // members unavailable.
13951           SourceLocation Loc = FD->getLocation();
13952           if (getSourceManager().isInSystemHeader(Loc)) {
13953             if (!FD->hasAttr<UnavailableAttr>())
13954               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13955                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13956             return false;
13957           }
13958         }
13959 
13960         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13961                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13962                diag::err_illegal_union_or_anon_struct_member)
13963           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13964         DiagnoseNontrivial(RDecl, member);
13965         return !getLangOpts().CPlusPlus11;
13966       }
13967     }
13968   }
13969 
13970   return false;
13971 }
13972 
13973 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13974 ///  AST enum value.
13975 static ObjCIvarDecl::AccessControl
13976 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13977   switch (ivarVisibility) {
13978   default: llvm_unreachable("Unknown visitibility kind");
13979   case tok::objc_private: return ObjCIvarDecl::Private;
13980   case tok::objc_public: return ObjCIvarDecl::Public;
13981   case tok::objc_protected: return ObjCIvarDecl::Protected;
13982   case tok::objc_package: return ObjCIvarDecl::Package;
13983   }
13984 }
13985 
13986 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13987 /// in order to create an IvarDecl object for it.
13988 Decl *Sema::ActOnIvar(Scope *S,
13989                                 SourceLocation DeclStart,
13990                                 Declarator &D, Expr *BitfieldWidth,
13991                                 tok::ObjCKeywordKind Visibility) {
13992 
13993   IdentifierInfo *II = D.getIdentifier();
13994   Expr *BitWidth = (Expr*)BitfieldWidth;
13995   SourceLocation Loc = DeclStart;
13996   if (II) Loc = D.getIdentifierLoc();
13997 
13998   // FIXME: Unnamed fields can be handled in various different ways, for
13999   // example, unnamed unions inject all members into the struct namespace!
14000 
14001   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14002   QualType T = TInfo->getType();
14003 
14004   if (BitWidth) {
14005     // 6.7.2.1p3, 6.7.2.1p4
14006     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14007     if (!BitWidth)
14008       D.setInvalidType();
14009   } else {
14010     // Not a bitfield.
14011 
14012     // validate II.
14013 
14014   }
14015   if (T->isReferenceType()) {
14016     Diag(Loc, diag::err_ivar_reference_type);
14017     D.setInvalidType();
14018   }
14019   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14020   // than a variably modified type.
14021   else if (T->isVariablyModifiedType()) {
14022     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14023     D.setInvalidType();
14024   }
14025 
14026   // Get the visibility (access control) for this ivar.
14027   ObjCIvarDecl::AccessControl ac =
14028     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14029                                         : ObjCIvarDecl::None;
14030   // Must set ivar's DeclContext to its enclosing interface.
14031   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14032   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14033     return nullptr;
14034   ObjCContainerDecl *EnclosingContext;
14035   if (ObjCImplementationDecl *IMPDecl =
14036       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14037     if (LangOpts.ObjCRuntime.isFragile()) {
14038     // Case of ivar declared in an implementation. Context is that of its class.
14039       EnclosingContext = IMPDecl->getClassInterface();
14040       assert(EnclosingContext && "Implementation has no class interface!");
14041     }
14042     else
14043       EnclosingContext = EnclosingDecl;
14044   } else {
14045     if (ObjCCategoryDecl *CDecl =
14046         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14047       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14048         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14049         return nullptr;
14050       }
14051     }
14052     EnclosingContext = EnclosingDecl;
14053   }
14054 
14055   // Construct the decl.
14056   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14057                                              DeclStart, Loc, II, T,
14058                                              TInfo, ac, (Expr *)BitfieldWidth);
14059 
14060   if (II) {
14061     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14062                                            ForRedeclaration);
14063     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14064         && !isa<TagDecl>(PrevDecl)) {
14065       Diag(Loc, diag::err_duplicate_member) << II;
14066       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14067       NewID->setInvalidDecl();
14068     }
14069   }
14070 
14071   // Process attributes attached to the ivar.
14072   ProcessDeclAttributes(S, NewID, D);
14073 
14074   if (D.isInvalidType())
14075     NewID->setInvalidDecl();
14076 
14077   // In ARC, infer 'retaining' for ivars of retainable type.
14078   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14079     NewID->setInvalidDecl();
14080 
14081   if (D.getDeclSpec().isModulePrivateSpecified())
14082     NewID->setModulePrivate();
14083 
14084   if (II) {
14085     // FIXME: When interfaces are DeclContexts, we'll need to add
14086     // these to the interface.
14087     S->AddDecl(NewID);
14088     IdResolver.AddDecl(NewID);
14089   }
14090 
14091   if (LangOpts.ObjCRuntime.isNonFragile() &&
14092       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14093     Diag(Loc, diag::warn_ivars_in_interface);
14094 
14095   return NewID;
14096 }
14097 
14098 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14099 /// class and class extensions. For every class \@interface and class
14100 /// extension \@interface, if the last ivar is a bitfield of any type,
14101 /// then add an implicit `char :0` ivar to the end of that interface.
14102 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14103                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14104   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14105     return;
14106 
14107   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14108   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14109 
14110   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14111     return;
14112   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14113   if (!ID) {
14114     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14115       if (!CD->IsClassExtension())
14116         return;
14117     }
14118     // No need to add this to end of @implementation.
14119     else
14120       return;
14121   }
14122   // All conditions are met. Add a new bitfield to the tail end of ivars.
14123   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14124   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14125 
14126   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14127                               DeclLoc, DeclLoc, nullptr,
14128                               Context.CharTy,
14129                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14130                                                                DeclLoc),
14131                               ObjCIvarDecl::Private, BW,
14132                               true);
14133   AllIvarDecls.push_back(Ivar);
14134 }
14135 
14136 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14137                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14138                        SourceLocation RBrac, AttributeList *Attr) {
14139   assert(EnclosingDecl && "missing record or interface decl");
14140 
14141   // If this is an Objective-C @implementation or category and we have
14142   // new fields here we should reset the layout of the interface since
14143   // it will now change.
14144   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14145     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14146     switch (DC->getKind()) {
14147     default: break;
14148     case Decl::ObjCCategory:
14149       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14150       break;
14151     case Decl::ObjCImplementation:
14152       Context.
14153         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14154       break;
14155     }
14156   }
14157 
14158   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14159 
14160   // Start counting up the number of named members; make sure to include
14161   // members of anonymous structs and unions in the total.
14162   unsigned NumNamedMembers = 0;
14163   if (Record) {
14164     for (const auto *I : Record->decls()) {
14165       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14166         if (IFD->getDeclName())
14167           ++NumNamedMembers;
14168     }
14169   }
14170 
14171   // Verify that all the fields are okay.
14172   SmallVector<FieldDecl*, 32> RecFields;
14173 
14174   bool ARCErrReported = false;
14175   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14176        i != end; ++i) {
14177     FieldDecl *FD = cast<FieldDecl>(*i);
14178 
14179     // Get the type for the field.
14180     const Type *FDTy = FD->getType().getTypePtr();
14181 
14182     if (!FD->isAnonymousStructOrUnion()) {
14183       // Remember all fields written by the user.
14184       RecFields.push_back(FD);
14185     }
14186 
14187     // If the field is already invalid for some reason, don't emit more
14188     // diagnostics about it.
14189     if (FD->isInvalidDecl()) {
14190       EnclosingDecl->setInvalidDecl();
14191       continue;
14192     }
14193 
14194     // C99 6.7.2.1p2:
14195     //   A structure or union shall not contain a member with
14196     //   incomplete or function type (hence, a structure shall not
14197     //   contain an instance of itself, but may contain a pointer to
14198     //   an instance of itself), except that the last member of a
14199     //   structure with more than one named member may have incomplete
14200     //   array type; such a structure (and any union containing,
14201     //   possibly recursively, a member that is such a structure)
14202     //   shall not be a member of a structure or an element of an
14203     //   array.
14204     if (FDTy->isFunctionType()) {
14205       // Field declared as a function.
14206       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14207         << FD->getDeclName();
14208       FD->setInvalidDecl();
14209       EnclosingDecl->setInvalidDecl();
14210       continue;
14211     } else if (FDTy->isIncompleteArrayType() && Record &&
14212                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14213                 ((getLangOpts().MicrosoftExt ||
14214                   getLangOpts().CPlusPlus) &&
14215                  (i + 1 == Fields.end() || Record->isUnion())))) {
14216       // Flexible array member.
14217       // Microsoft and g++ is more permissive regarding flexible array.
14218       // It will accept flexible array in union and also
14219       // as the sole element of a struct/class.
14220       unsigned DiagID = 0;
14221       if (Record->isUnion())
14222         DiagID = getLangOpts().MicrosoftExt
14223                      ? diag::ext_flexible_array_union_ms
14224                      : getLangOpts().CPlusPlus
14225                            ? diag::ext_flexible_array_union_gnu
14226                            : diag::err_flexible_array_union;
14227       else if (NumNamedMembers < 1)
14228         DiagID = getLangOpts().MicrosoftExt
14229                      ? diag::ext_flexible_array_empty_aggregate_ms
14230                      : getLangOpts().CPlusPlus
14231                            ? diag::ext_flexible_array_empty_aggregate_gnu
14232                            : diag::err_flexible_array_empty_aggregate;
14233 
14234       if (DiagID)
14235         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14236                                         << Record->getTagKind();
14237       // While the layout of types that contain virtual bases is not specified
14238       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14239       // virtual bases after the derived members.  This would make a flexible
14240       // array member declared at the end of an object not adjacent to the end
14241       // of the type.
14242       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14243         if (RD->getNumVBases() != 0)
14244           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14245             << FD->getDeclName() << Record->getTagKind();
14246       if (!getLangOpts().C99)
14247         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14248           << FD->getDeclName() << Record->getTagKind();
14249 
14250       // If the element type has a non-trivial destructor, we would not
14251       // implicitly destroy the elements, so disallow it for now.
14252       //
14253       // FIXME: GCC allows this. We should probably either implicitly delete
14254       // the destructor of the containing class, or just allow this.
14255       QualType BaseElem = Context.getBaseElementType(FD->getType());
14256       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14257         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14258           << FD->getDeclName() << FD->getType();
14259         FD->setInvalidDecl();
14260         EnclosingDecl->setInvalidDecl();
14261         continue;
14262       }
14263       // Okay, we have a legal flexible array member at the end of the struct.
14264       Record->setHasFlexibleArrayMember(true);
14265     } else if (!FDTy->isDependentType() &&
14266                RequireCompleteType(FD->getLocation(), FD->getType(),
14267                                    diag::err_field_incomplete)) {
14268       // Incomplete type
14269       FD->setInvalidDecl();
14270       EnclosingDecl->setInvalidDecl();
14271       continue;
14272     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14273       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14274         // A type which contains a flexible array member is considered to be a
14275         // flexible array member.
14276         Record->setHasFlexibleArrayMember(true);
14277         if (!Record->isUnion()) {
14278           // If this is a struct/class and this is not the last element, reject
14279           // it.  Note that GCC supports variable sized arrays in the middle of
14280           // structures.
14281           if (i + 1 != Fields.end())
14282             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14283               << FD->getDeclName() << FD->getType();
14284           else {
14285             // We support flexible arrays at the end of structs in
14286             // other structs as an extension.
14287             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14288               << FD->getDeclName();
14289           }
14290         }
14291       }
14292       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14293           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14294                                  diag::err_abstract_type_in_decl,
14295                                  AbstractIvarType)) {
14296         // Ivars can not have abstract class types
14297         FD->setInvalidDecl();
14298       }
14299       if (Record && FDTTy->getDecl()->hasObjectMember())
14300         Record->setHasObjectMember(true);
14301       if (Record && FDTTy->getDecl()->hasVolatileMember())
14302         Record->setHasVolatileMember(true);
14303     } else if (FDTy->isObjCObjectType()) {
14304       /// A field cannot be an Objective-c object
14305       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14306         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14307       QualType T = Context.getObjCObjectPointerType(FD->getType());
14308       FD->setType(T);
14309     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14310                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14311       // It's an error in ARC if a field has lifetime.
14312       // We don't want to report this in a system header, though,
14313       // so we just make the field unavailable.
14314       // FIXME: that's really not sufficient; we need to make the type
14315       // itself invalid to, say, initialize or copy.
14316       QualType T = FD->getType();
14317       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14318       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14319         SourceLocation loc = FD->getLocation();
14320         if (getSourceManager().isInSystemHeader(loc)) {
14321           if (!FD->hasAttr<UnavailableAttr>()) {
14322             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14323                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14324           }
14325         } else {
14326           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14327             << T->isBlockPointerType() << Record->getTagKind();
14328         }
14329         ARCErrReported = true;
14330       }
14331     } else if (getLangOpts().ObjC1 &&
14332                getLangOpts().getGC() != LangOptions::NonGC &&
14333                Record && !Record->hasObjectMember()) {
14334       if (FD->getType()->isObjCObjectPointerType() ||
14335           FD->getType().isObjCGCStrong())
14336         Record->setHasObjectMember(true);
14337       else if (Context.getAsArrayType(FD->getType())) {
14338         QualType BaseType = Context.getBaseElementType(FD->getType());
14339         if (BaseType->isRecordType() &&
14340             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14341           Record->setHasObjectMember(true);
14342         else if (BaseType->isObjCObjectPointerType() ||
14343                  BaseType.isObjCGCStrong())
14344                Record->setHasObjectMember(true);
14345       }
14346     }
14347     if (Record && FD->getType().isVolatileQualified())
14348       Record->setHasVolatileMember(true);
14349     // Keep track of the number of named members.
14350     if (FD->getIdentifier())
14351       ++NumNamedMembers;
14352   }
14353 
14354   // Okay, we successfully defined 'Record'.
14355   if (Record) {
14356     bool Completed = false;
14357     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14358       if (!CXXRecord->isInvalidDecl()) {
14359         // Set access bits correctly on the directly-declared conversions.
14360         for (CXXRecordDecl::conversion_iterator
14361                I = CXXRecord->conversion_begin(),
14362                E = CXXRecord->conversion_end(); I != E; ++I)
14363           I.setAccess((*I)->getAccess());
14364       }
14365 
14366       if (!CXXRecord->isDependentType()) {
14367         if (CXXRecord->hasUserDeclaredDestructor()) {
14368           // Adjust user-defined destructor exception spec.
14369           if (getLangOpts().CPlusPlus11)
14370             AdjustDestructorExceptionSpec(CXXRecord,
14371                                           CXXRecord->getDestructor());
14372         }
14373 
14374         if (!CXXRecord->isInvalidDecl()) {
14375           // Add any implicitly-declared members to this class.
14376           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14377 
14378           // If we have virtual base classes, we may end up finding multiple
14379           // final overriders for a given virtual function. Check for this
14380           // problem now.
14381           if (CXXRecord->getNumVBases()) {
14382             CXXFinalOverriderMap FinalOverriders;
14383             CXXRecord->getFinalOverriders(FinalOverriders);
14384 
14385             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14386                                              MEnd = FinalOverriders.end();
14387                  M != MEnd; ++M) {
14388               for (OverridingMethods::iterator SO = M->second.begin(),
14389                                             SOEnd = M->second.end();
14390                    SO != SOEnd; ++SO) {
14391                 assert(SO->second.size() > 0 &&
14392                        "Virtual function without overridding functions?");
14393                 if (SO->second.size() == 1)
14394                   continue;
14395 
14396                 // C++ [class.virtual]p2:
14397                 //   In a derived class, if a virtual member function of a base
14398                 //   class subobject has more than one final overrider the
14399                 //   program is ill-formed.
14400                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14401                   << (const NamedDecl *)M->first << Record;
14402                 Diag(M->first->getLocation(),
14403                      diag::note_overridden_virtual_function);
14404                 for (OverridingMethods::overriding_iterator
14405                           OM = SO->second.begin(),
14406                        OMEnd = SO->second.end();
14407                      OM != OMEnd; ++OM)
14408                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14409                     << (const NamedDecl *)M->first << OM->Method->getParent();
14410 
14411                 Record->setInvalidDecl();
14412               }
14413             }
14414             CXXRecord->completeDefinition(&FinalOverriders);
14415             Completed = true;
14416           }
14417         }
14418       }
14419     }
14420 
14421     if (!Completed)
14422       Record->completeDefinition();
14423 
14424     // We may have deferred checking for a deleted destructor. Check now.
14425     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14426       auto *Dtor = CXXRecord->getDestructor();
14427       if (Dtor && Dtor->isImplicit() &&
14428           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14429         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14430     }
14431 
14432     if (Record->hasAttrs()) {
14433       CheckAlignasUnderalignment(Record);
14434 
14435       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14436         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14437                                            IA->getRange(), IA->getBestCase(),
14438                                            IA->getSemanticSpelling());
14439     }
14440 
14441     // Check if the structure/union declaration is a type that can have zero
14442     // size in C. For C this is a language extension, for C++ it may cause
14443     // compatibility problems.
14444     bool CheckForZeroSize;
14445     if (!getLangOpts().CPlusPlus) {
14446       CheckForZeroSize = true;
14447     } else {
14448       // For C++ filter out types that cannot be referenced in C code.
14449       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14450       CheckForZeroSize =
14451           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14452           !CXXRecord->isDependentType() &&
14453           CXXRecord->isCLike();
14454     }
14455     if (CheckForZeroSize) {
14456       bool ZeroSize = true;
14457       bool IsEmpty = true;
14458       unsigned NonBitFields = 0;
14459       for (RecordDecl::field_iterator I = Record->field_begin(),
14460                                       E = Record->field_end();
14461            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14462         IsEmpty = false;
14463         if (I->isUnnamedBitfield()) {
14464           if (I->getBitWidthValue(Context) > 0)
14465             ZeroSize = false;
14466         } else {
14467           ++NonBitFields;
14468           QualType FieldType = I->getType();
14469           if (FieldType->isIncompleteType() ||
14470               !Context.getTypeSizeInChars(FieldType).isZero())
14471             ZeroSize = false;
14472         }
14473       }
14474 
14475       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14476       // allowed in C++, but warn if its declaration is inside
14477       // extern "C" block.
14478       if (ZeroSize) {
14479         Diag(RecLoc, getLangOpts().CPlusPlus ?
14480                          diag::warn_zero_size_struct_union_in_extern_c :
14481                          diag::warn_zero_size_struct_union_compat)
14482           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14483       }
14484 
14485       // Structs without named members are extension in C (C99 6.7.2.1p7),
14486       // but are accepted by GCC.
14487       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14488         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14489                                diag::ext_no_named_members_in_struct_union)
14490           << Record->isUnion();
14491       }
14492     }
14493   } else {
14494     ObjCIvarDecl **ClsFields =
14495       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14496     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14497       ID->setEndOfDefinitionLoc(RBrac);
14498       // Add ivar's to class's DeclContext.
14499       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14500         ClsFields[i]->setLexicalDeclContext(ID);
14501         ID->addDecl(ClsFields[i]);
14502       }
14503       // Must enforce the rule that ivars in the base classes may not be
14504       // duplicates.
14505       if (ID->getSuperClass())
14506         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14507     } else if (ObjCImplementationDecl *IMPDecl =
14508                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14509       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14510       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14511         // Ivar declared in @implementation never belongs to the implementation.
14512         // Only it is in implementation's lexical context.
14513         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14514       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14515       IMPDecl->setIvarLBraceLoc(LBrac);
14516       IMPDecl->setIvarRBraceLoc(RBrac);
14517     } else if (ObjCCategoryDecl *CDecl =
14518                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14519       // case of ivars in class extension; all other cases have been
14520       // reported as errors elsewhere.
14521       // FIXME. Class extension does not have a LocEnd field.
14522       // CDecl->setLocEnd(RBrac);
14523       // Add ivar's to class extension's DeclContext.
14524       // Diagnose redeclaration of private ivars.
14525       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14526       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14527         if (IDecl) {
14528           if (const ObjCIvarDecl *ClsIvar =
14529               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14530             Diag(ClsFields[i]->getLocation(),
14531                  diag::err_duplicate_ivar_declaration);
14532             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14533             continue;
14534           }
14535           for (const auto *Ext : IDecl->known_extensions()) {
14536             if (const ObjCIvarDecl *ClsExtIvar
14537                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14538               Diag(ClsFields[i]->getLocation(),
14539                    diag::err_duplicate_ivar_declaration);
14540               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14541               continue;
14542             }
14543           }
14544         }
14545         ClsFields[i]->setLexicalDeclContext(CDecl);
14546         CDecl->addDecl(ClsFields[i]);
14547       }
14548       CDecl->setIvarLBraceLoc(LBrac);
14549       CDecl->setIvarRBraceLoc(RBrac);
14550     }
14551   }
14552 
14553   if (Attr)
14554     ProcessDeclAttributeList(S, Record, Attr);
14555 }
14556 
14557 /// \brief Determine whether the given integral value is representable within
14558 /// the given type T.
14559 static bool isRepresentableIntegerValue(ASTContext &Context,
14560                                         llvm::APSInt &Value,
14561                                         QualType T) {
14562   assert(T->isIntegralType(Context) && "Integral type required!");
14563   unsigned BitWidth = Context.getIntWidth(T);
14564 
14565   if (Value.isUnsigned() || Value.isNonNegative()) {
14566     if (T->isSignedIntegerOrEnumerationType())
14567       --BitWidth;
14568     return Value.getActiveBits() <= BitWidth;
14569   }
14570   return Value.getMinSignedBits() <= BitWidth;
14571 }
14572 
14573 // \brief Given an integral type, return the next larger integral type
14574 // (or a NULL type of no such type exists).
14575 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14576   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14577   // enum checking below.
14578   assert(T->isIntegralType(Context) && "Integral type required!");
14579   const unsigned NumTypes = 4;
14580   QualType SignedIntegralTypes[NumTypes] = {
14581     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14582   };
14583   QualType UnsignedIntegralTypes[NumTypes] = {
14584     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14585     Context.UnsignedLongLongTy
14586   };
14587 
14588   unsigned BitWidth = Context.getTypeSize(T);
14589   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14590                                                         : UnsignedIntegralTypes;
14591   for (unsigned I = 0; I != NumTypes; ++I)
14592     if (Context.getTypeSize(Types[I]) > BitWidth)
14593       return Types[I];
14594 
14595   return QualType();
14596 }
14597 
14598 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14599                                           EnumConstantDecl *LastEnumConst,
14600                                           SourceLocation IdLoc,
14601                                           IdentifierInfo *Id,
14602                                           Expr *Val) {
14603   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14604   llvm::APSInt EnumVal(IntWidth);
14605   QualType EltTy;
14606 
14607   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14608     Val = nullptr;
14609 
14610   if (Val)
14611     Val = DefaultLvalueConversion(Val).get();
14612 
14613   if (Val) {
14614     if (Enum->isDependentType() || Val->isTypeDependent())
14615       EltTy = Context.DependentTy;
14616     else {
14617       SourceLocation ExpLoc;
14618       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14619           !getLangOpts().MSVCCompat) {
14620         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14621         // constant-expression in the enumerator-definition shall be a converted
14622         // constant expression of the underlying type.
14623         EltTy = Enum->getIntegerType();
14624         ExprResult Converted =
14625           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14626                                            CCEK_Enumerator);
14627         if (Converted.isInvalid())
14628           Val = nullptr;
14629         else
14630           Val = Converted.get();
14631       } else if (!Val->isValueDependent() &&
14632                  !(Val = VerifyIntegerConstantExpression(Val,
14633                                                          &EnumVal).get())) {
14634         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14635       } else {
14636         if (Enum->isFixed()) {
14637           EltTy = Enum->getIntegerType();
14638 
14639           // In Obj-C and Microsoft mode, require the enumeration value to be
14640           // representable in the underlying type of the enumeration. In C++11,
14641           // we perform a non-narrowing conversion as part of converted constant
14642           // expression checking.
14643           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14644             if (getLangOpts().MSVCCompat) {
14645               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14646               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14647             } else
14648               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14649           } else
14650             Val = ImpCastExprToType(Val, EltTy,
14651                                     EltTy->isBooleanType() ?
14652                                     CK_IntegralToBoolean : CK_IntegralCast)
14653                     .get();
14654         } else if (getLangOpts().CPlusPlus) {
14655           // C++11 [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           //     - If an initializer is specified for an enumerator, the
14659           //       initializing value has the same type as the expression.
14660           EltTy = Val->getType();
14661         } else {
14662           // C99 6.7.2.2p2:
14663           //   The expression that defines the value of an enumeration constant
14664           //   shall be an integer constant expression that has a value
14665           //   representable as an int.
14666 
14667           // Complain if the value is not representable in an int.
14668           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14669             Diag(IdLoc, diag::ext_enum_value_not_int)
14670               << EnumVal.toString(10) << Val->getSourceRange()
14671               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14672           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14673             // Force the type of the expression to 'int'.
14674             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14675           }
14676           EltTy = Val->getType();
14677         }
14678       }
14679     }
14680   }
14681 
14682   if (!Val) {
14683     if (Enum->isDependentType())
14684       EltTy = Context.DependentTy;
14685     else if (!LastEnumConst) {
14686       // C++0x [dcl.enum]p5:
14687       //   If the underlying type is not fixed, the type of each enumerator
14688       //   is the type of its initializing value:
14689       //     - If no initializer is specified for the first enumerator, the
14690       //       initializing value has an unspecified integral type.
14691       //
14692       // GCC uses 'int' for its unspecified integral type, as does
14693       // C99 6.7.2.2p3.
14694       if (Enum->isFixed()) {
14695         EltTy = Enum->getIntegerType();
14696       }
14697       else {
14698         EltTy = Context.IntTy;
14699       }
14700     } else {
14701       // Assign the last value + 1.
14702       EnumVal = LastEnumConst->getInitVal();
14703       ++EnumVal;
14704       EltTy = LastEnumConst->getType();
14705 
14706       // Check for overflow on increment.
14707       if (EnumVal < LastEnumConst->getInitVal()) {
14708         // C++0x [dcl.enum]p5:
14709         //   If the underlying type is not fixed, the type of each enumerator
14710         //   is the type of its initializing value:
14711         //
14712         //     - Otherwise the type of the initializing value is the same as
14713         //       the type of the initializing value of the preceding enumerator
14714         //       unless the incremented value is not representable in that type,
14715         //       in which case the type is an unspecified integral type
14716         //       sufficient to contain the incremented value. If no such type
14717         //       exists, the program is ill-formed.
14718         QualType T = getNextLargerIntegralType(Context, EltTy);
14719         if (T.isNull() || Enum->isFixed()) {
14720           // There is no integral type larger enough to represent this
14721           // value. Complain, then allow the value to wrap around.
14722           EnumVal = LastEnumConst->getInitVal();
14723           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14724           ++EnumVal;
14725           if (Enum->isFixed())
14726             // When the underlying type is fixed, this is ill-formed.
14727             Diag(IdLoc, diag::err_enumerator_wrapped)
14728               << EnumVal.toString(10)
14729               << EltTy;
14730           else
14731             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14732               << EnumVal.toString(10);
14733         } else {
14734           EltTy = T;
14735         }
14736 
14737         // Retrieve the last enumerator's value, extent that type to the
14738         // type that is supposed to be large enough to represent the incremented
14739         // value, then increment.
14740         EnumVal = LastEnumConst->getInitVal();
14741         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14742         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14743         ++EnumVal;
14744 
14745         // If we're not in C++, diagnose the overflow of enumerator values,
14746         // which in C99 means that the enumerator value is not representable in
14747         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14748         // permits enumerator values that are representable in some larger
14749         // integral type.
14750         if (!getLangOpts().CPlusPlus && !T.isNull())
14751           Diag(IdLoc, diag::warn_enum_value_overflow);
14752       } else if (!getLangOpts().CPlusPlus &&
14753                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14754         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14755         Diag(IdLoc, diag::ext_enum_value_not_int)
14756           << EnumVal.toString(10) << 1;
14757       }
14758     }
14759   }
14760 
14761   if (!EltTy->isDependentType()) {
14762     // Make the enumerator value match the signedness and size of the
14763     // enumerator's type.
14764     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14765     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14766   }
14767 
14768   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14769                                   Val, EnumVal);
14770 }
14771 
14772 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14773                                                 SourceLocation IILoc) {
14774   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14775       !getLangOpts().CPlusPlus)
14776     return SkipBodyInfo();
14777 
14778   // We have an anonymous enum definition. Look up the first enumerator to
14779   // determine if we should merge the definition with an existing one and
14780   // skip the body.
14781   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14782                                          ForRedeclaration);
14783   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14784   if (!PrevECD)
14785     return SkipBodyInfo();
14786 
14787   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14788   NamedDecl *Hidden;
14789   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14790     SkipBodyInfo Skip;
14791     Skip.Previous = Hidden;
14792     return Skip;
14793   }
14794 
14795   return SkipBodyInfo();
14796 }
14797 
14798 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14799                               SourceLocation IdLoc, IdentifierInfo *Id,
14800                               AttributeList *Attr,
14801                               SourceLocation EqualLoc, Expr *Val) {
14802   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14803   EnumConstantDecl *LastEnumConst =
14804     cast_or_null<EnumConstantDecl>(lastEnumConst);
14805 
14806   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14807   // we find one that is.
14808   S = getNonFieldDeclScope(S);
14809 
14810   // Verify that there isn't already something declared with this name in this
14811   // scope.
14812   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14813                                          ForRedeclaration);
14814   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14815     // Maybe we will complain about the shadowed template parameter.
14816     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14817     // Just pretend that we didn't see the previous declaration.
14818     PrevDecl = nullptr;
14819   }
14820 
14821   // C++ [class.mem]p15:
14822   // If T is the name of a class, then each of the following shall have a name
14823   // different from T:
14824   // - every enumerator of every member of class T that is an unscoped
14825   // enumerated type
14826   if (!TheEnumDecl->isScoped())
14827     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14828                             DeclarationNameInfo(Id, IdLoc));
14829 
14830   EnumConstantDecl *New =
14831     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14832   if (!New)
14833     return nullptr;
14834 
14835   if (PrevDecl) {
14836     // When in C++, we may get a TagDecl with the same name; in this case the
14837     // enum constant will 'hide' the tag.
14838     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14839            "Received TagDecl when not in C++!");
14840     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14841         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14842       if (isa<EnumConstantDecl>(PrevDecl))
14843         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14844       else
14845         Diag(IdLoc, diag::err_redefinition) << Id;
14846       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14847       return nullptr;
14848     }
14849   }
14850 
14851   // Process attributes.
14852   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14853 
14854   // Register this decl in the current scope stack.
14855   New->setAccess(TheEnumDecl->getAccess());
14856   PushOnScopeChains(New, S);
14857 
14858   ActOnDocumentableDecl(New);
14859 
14860   return New;
14861 }
14862 
14863 // Returns true when the enum initial expression does not trigger the
14864 // duplicate enum warning.  A few common cases are exempted as follows:
14865 // Element2 = Element1
14866 // Element2 = Element1 + 1
14867 // Element2 = Element1 - 1
14868 // Where Element2 and Element1 are from the same enum.
14869 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14870   Expr *InitExpr = ECD->getInitExpr();
14871   if (!InitExpr)
14872     return true;
14873   InitExpr = InitExpr->IgnoreImpCasts();
14874 
14875   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14876     if (!BO->isAdditiveOp())
14877       return true;
14878     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14879     if (!IL)
14880       return true;
14881     if (IL->getValue() != 1)
14882       return true;
14883 
14884     InitExpr = BO->getLHS();
14885   }
14886 
14887   // This checks if the elements are from the same enum.
14888   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14889   if (!DRE)
14890     return true;
14891 
14892   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14893   if (!EnumConstant)
14894     return true;
14895 
14896   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14897       Enum)
14898     return true;
14899 
14900   return false;
14901 }
14902 
14903 namespace {
14904 struct DupKey {
14905   int64_t val;
14906   bool isTombstoneOrEmptyKey;
14907   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14908     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14909 };
14910 
14911 static DupKey GetDupKey(const llvm::APSInt& Val) {
14912   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14913                 false);
14914 }
14915 
14916 struct DenseMapInfoDupKey {
14917   static DupKey getEmptyKey() { return DupKey(0, true); }
14918   static DupKey getTombstoneKey() { return DupKey(1, true); }
14919   static unsigned getHashValue(const DupKey Key) {
14920     return (unsigned)(Key.val * 37);
14921   }
14922   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14923     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14924            LHS.val == RHS.val;
14925   }
14926 };
14927 } // end anonymous namespace
14928 
14929 // Emits a warning when an element is implicitly set a value that
14930 // a previous element has already been set to.
14931 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14932                                         EnumDecl *Enum,
14933                                         QualType EnumType) {
14934   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14935     return;
14936   // Avoid anonymous enums
14937   if (!Enum->getIdentifier())
14938     return;
14939 
14940   // Only check for small enums.
14941   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14942     return;
14943 
14944   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14945   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14946 
14947   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14948   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14949           ValueToVectorMap;
14950 
14951   DuplicatesVector DupVector;
14952   ValueToVectorMap EnumMap;
14953 
14954   // Populate the EnumMap with all values represented by enum constants without
14955   // an initialier.
14956   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14957     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14958 
14959     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14960     // this constant.  Skip this enum since it may be ill-formed.
14961     if (!ECD) {
14962       return;
14963     }
14964 
14965     if (ECD->getInitExpr())
14966       continue;
14967 
14968     DupKey Key = GetDupKey(ECD->getInitVal());
14969     DeclOrVector &Entry = EnumMap[Key];
14970 
14971     // First time encountering this value.
14972     if (Entry.isNull())
14973       Entry = ECD;
14974   }
14975 
14976   // Create vectors for any values that has duplicates.
14977   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14978     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14979     if (!ValidDuplicateEnum(ECD, Enum))
14980       continue;
14981 
14982     DupKey Key = GetDupKey(ECD->getInitVal());
14983 
14984     DeclOrVector& Entry = EnumMap[Key];
14985     if (Entry.isNull())
14986       continue;
14987 
14988     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14989       // Ensure constants are different.
14990       if (D == ECD)
14991         continue;
14992 
14993       // Create new vector and push values onto it.
14994       ECDVector *Vec = new ECDVector();
14995       Vec->push_back(D);
14996       Vec->push_back(ECD);
14997 
14998       // Update entry to point to the duplicates vector.
14999       Entry = Vec;
15000 
15001       // Store the vector somewhere we can consult later for quick emission of
15002       // diagnostics.
15003       DupVector.push_back(Vec);
15004       continue;
15005     }
15006 
15007     ECDVector *Vec = Entry.get<ECDVector*>();
15008     // Make sure constants are not added more than once.
15009     if (*Vec->begin() == ECD)
15010       continue;
15011 
15012     Vec->push_back(ECD);
15013   }
15014 
15015   // Emit diagnostics.
15016   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15017                                   DupVectorEnd = DupVector.end();
15018        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15019     ECDVector *Vec = *DupVectorIter;
15020     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15021 
15022     // Emit warning for one enum constant.
15023     ECDVector::iterator I = Vec->begin();
15024     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15025       << (*I)->getName() << (*I)->getInitVal().toString(10)
15026       << (*I)->getSourceRange();
15027     ++I;
15028 
15029     // Emit one note for each of the remaining enum constants with
15030     // the same value.
15031     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15032       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15033         << (*I)->getName() << (*I)->getInitVal().toString(10)
15034         << (*I)->getSourceRange();
15035     delete Vec;
15036   }
15037 }
15038 
15039 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15040                              bool AllowMask) const {
15041   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15042   assert(ED->isCompleteDefinition() && "expected enum definition");
15043 
15044   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15045   llvm::APInt &FlagBits = R.first->second;
15046 
15047   if (R.second) {
15048     for (auto *E : ED->enumerators()) {
15049       const auto &EVal = E->getInitVal();
15050       // Only single-bit enumerators introduce new flag values.
15051       if (EVal.isPowerOf2())
15052         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15053     }
15054   }
15055 
15056   // A value is in a flag enum if either its bits are a subset of the enum's
15057   // flag bits (the first condition) or we are allowing masks and the same is
15058   // true of its complement (the second condition). When masks are allowed, we
15059   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15060   //
15061   // While it's true that any value could be used as a mask, the assumption is
15062   // that a mask will have all of the insignificant bits set. Anything else is
15063   // likely a logic error.
15064   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15065   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15066 }
15067 
15068 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15069                          Decl *EnumDeclX,
15070                          ArrayRef<Decl *> Elements,
15071                          Scope *S, AttributeList *Attr) {
15072   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15073   QualType EnumType = Context.getTypeDeclType(Enum);
15074 
15075   if (Attr)
15076     ProcessDeclAttributeList(S, Enum, Attr);
15077 
15078   if (Enum->isDependentType()) {
15079     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15080       EnumConstantDecl *ECD =
15081         cast_or_null<EnumConstantDecl>(Elements[i]);
15082       if (!ECD) continue;
15083 
15084       ECD->setType(EnumType);
15085     }
15086 
15087     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15088     return;
15089   }
15090 
15091   // TODO: If the result value doesn't fit in an int, it must be a long or long
15092   // long value.  ISO C does not support this, but GCC does as an extension,
15093   // emit a warning.
15094   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15095   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15096   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15097 
15098   // Verify that all the values are okay, compute the size of the values, and
15099   // reverse the list.
15100   unsigned NumNegativeBits = 0;
15101   unsigned NumPositiveBits = 0;
15102 
15103   // Keep track of whether all elements have type int.
15104   bool AllElementsInt = true;
15105 
15106   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15107     EnumConstantDecl *ECD =
15108       cast_or_null<EnumConstantDecl>(Elements[i]);
15109     if (!ECD) continue;  // Already issued a diagnostic.
15110 
15111     const llvm::APSInt &InitVal = ECD->getInitVal();
15112 
15113     // Keep track of the size of positive and negative values.
15114     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15115       NumPositiveBits = std::max(NumPositiveBits,
15116                                  (unsigned)InitVal.getActiveBits());
15117     else
15118       NumNegativeBits = std::max(NumNegativeBits,
15119                                  (unsigned)InitVal.getMinSignedBits());
15120 
15121     // Keep track of whether every enum element has type int (very commmon).
15122     if (AllElementsInt)
15123       AllElementsInt = ECD->getType() == Context.IntTy;
15124   }
15125 
15126   // Figure out the type that should be used for this enum.
15127   QualType BestType;
15128   unsigned BestWidth;
15129 
15130   // C++0x N3000 [conv.prom]p3:
15131   //   An rvalue of an unscoped enumeration type whose underlying
15132   //   type is not fixed can be converted to an rvalue of the first
15133   //   of the following types that can represent all the values of
15134   //   the enumeration: int, unsigned int, long int, unsigned long
15135   //   int, long long int, or unsigned long long int.
15136   // C99 6.4.4.3p2:
15137   //   An identifier declared as an enumeration constant has type int.
15138   // The C99 rule is modified by a gcc extension
15139   QualType BestPromotionType;
15140 
15141   bool Packed = Enum->hasAttr<PackedAttr>();
15142   // -fshort-enums is the equivalent to specifying the packed attribute on all
15143   // enum definitions.
15144   if (LangOpts.ShortEnums)
15145     Packed = true;
15146 
15147   if (Enum->isFixed()) {
15148     BestType = Enum->getIntegerType();
15149     if (BestType->isPromotableIntegerType())
15150       BestPromotionType = Context.getPromotedIntegerType(BestType);
15151     else
15152       BestPromotionType = BestType;
15153 
15154     BestWidth = Context.getIntWidth(BestType);
15155   }
15156   else if (NumNegativeBits) {
15157     // If there is a negative value, figure out the smallest integer type (of
15158     // int/long/longlong) that fits.
15159     // If it's packed, check also if it fits a char or a short.
15160     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15161       BestType = Context.SignedCharTy;
15162       BestWidth = CharWidth;
15163     } else if (Packed && NumNegativeBits <= ShortWidth &&
15164                NumPositiveBits < ShortWidth) {
15165       BestType = Context.ShortTy;
15166       BestWidth = ShortWidth;
15167     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15168       BestType = Context.IntTy;
15169       BestWidth = IntWidth;
15170     } else {
15171       BestWidth = Context.getTargetInfo().getLongWidth();
15172 
15173       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15174         BestType = Context.LongTy;
15175       } else {
15176         BestWidth = Context.getTargetInfo().getLongLongWidth();
15177 
15178         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15179           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15180         BestType = Context.LongLongTy;
15181       }
15182     }
15183     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15184   } else {
15185     // If there is no negative value, figure out the smallest type that fits
15186     // all of the enumerator values.
15187     // If it's packed, check also if it fits a char or a short.
15188     if (Packed && NumPositiveBits <= CharWidth) {
15189       BestType = Context.UnsignedCharTy;
15190       BestPromotionType = Context.IntTy;
15191       BestWidth = CharWidth;
15192     } else if (Packed && NumPositiveBits <= ShortWidth) {
15193       BestType = Context.UnsignedShortTy;
15194       BestPromotionType = Context.IntTy;
15195       BestWidth = ShortWidth;
15196     } else if (NumPositiveBits <= IntWidth) {
15197       BestType = Context.UnsignedIntTy;
15198       BestWidth = IntWidth;
15199       BestPromotionType
15200         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15201                            ? Context.UnsignedIntTy : Context.IntTy;
15202     } else if (NumPositiveBits <=
15203                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15204       BestType = Context.UnsignedLongTy;
15205       BestPromotionType
15206         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15207                            ? Context.UnsignedLongTy : Context.LongTy;
15208     } else {
15209       BestWidth = Context.getTargetInfo().getLongLongWidth();
15210       assert(NumPositiveBits <= BestWidth &&
15211              "How could an initializer get larger than ULL?");
15212       BestType = Context.UnsignedLongLongTy;
15213       BestPromotionType
15214         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15215                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15216     }
15217   }
15218 
15219   // Loop over all of the enumerator constants, changing their types to match
15220   // the type of the enum if needed.
15221   for (auto *D : Elements) {
15222     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15223     if (!ECD) continue;  // Already issued a diagnostic.
15224 
15225     // Standard C says the enumerators have int type, but we allow, as an
15226     // extension, the enumerators to be larger than int size.  If each
15227     // enumerator value fits in an int, type it as an int, otherwise type it the
15228     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15229     // that X has type 'int', not 'unsigned'.
15230 
15231     // Determine whether the value fits into an int.
15232     llvm::APSInt InitVal = ECD->getInitVal();
15233 
15234     // If it fits into an integer type, force it.  Otherwise force it to match
15235     // the enum decl type.
15236     QualType NewTy;
15237     unsigned NewWidth;
15238     bool NewSign;
15239     if (!getLangOpts().CPlusPlus &&
15240         !Enum->isFixed() &&
15241         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15242       NewTy = Context.IntTy;
15243       NewWidth = IntWidth;
15244       NewSign = true;
15245     } else if (ECD->getType() == BestType) {
15246       // Already the right type!
15247       if (getLangOpts().CPlusPlus)
15248         // C++ [dcl.enum]p4: Following the closing brace of an
15249         // enum-specifier, each enumerator has the type of its
15250         // enumeration.
15251         ECD->setType(EnumType);
15252       continue;
15253     } else {
15254       NewTy = BestType;
15255       NewWidth = BestWidth;
15256       NewSign = BestType->isSignedIntegerOrEnumerationType();
15257     }
15258 
15259     // Adjust the APSInt value.
15260     InitVal = InitVal.extOrTrunc(NewWidth);
15261     InitVal.setIsSigned(NewSign);
15262     ECD->setInitVal(InitVal);
15263 
15264     // Adjust the Expr initializer and type.
15265     if (ECD->getInitExpr() &&
15266         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15267       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15268                                                 CK_IntegralCast,
15269                                                 ECD->getInitExpr(),
15270                                                 /*base paths*/ nullptr,
15271                                                 VK_RValue));
15272     if (getLangOpts().CPlusPlus)
15273       // C++ [dcl.enum]p4: Following the closing brace of an
15274       // enum-specifier, each enumerator has the type of its
15275       // enumeration.
15276       ECD->setType(EnumType);
15277     else
15278       ECD->setType(NewTy);
15279   }
15280 
15281   Enum->completeDefinition(BestType, BestPromotionType,
15282                            NumPositiveBits, NumNegativeBits);
15283 
15284   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15285 
15286   if (Enum->hasAttr<FlagEnumAttr>()) {
15287     for (Decl *D : Elements) {
15288       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15289       if (!ECD) continue;  // Already issued a diagnostic.
15290 
15291       llvm::APSInt InitVal = ECD->getInitVal();
15292       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15293           !IsValueInFlagEnum(Enum, InitVal, true))
15294         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15295           << ECD << Enum;
15296     }
15297   }
15298 
15299   // Now that the enum type is defined, ensure it's not been underaligned.
15300   if (Enum->hasAttrs())
15301     CheckAlignasUnderalignment(Enum);
15302 }
15303 
15304 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15305                                   SourceLocation StartLoc,
15306                                   SourceLocation EndLoc) {
15307   StringLiteral *AsmString = cast<StringLiteral>(expr);
15308 
15309   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15310                                                    AsmString, StartLoc,
15311                                                    EndLoc);
15312   CurContext->addDecl(New);
15313   return New;
15314 }
15315 
15316 static void checkModuleImportContext(Sema &S, Module *M,
15317                                      SourceLocation ImportLoc, DeclContext *DC,
15318                                      bool FromInclude = false) {
15319   SourceLocation ExternCLoc;
15320 
15321   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15322     switch (LSD->getLanguage()) {
15323     case LinkageSpecDecl::lang_c:
15324       if (ExternCLoc.isInvalid())
15325         ExternCLoc = LSD->getLocStart();
15326       break;
15327     case LinkageSpecDecl::lang_cxx:
15328       break;
15329     }
15330     DC = LSD->getParent();
15331   }
15332 
15333   while (isa<LinkageSpecDecl>(DC))
15334     DC = DC->getParent();
15335 
15336   if (!isa<TranslationUnitDecl>(DC)) {
15337     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15338                           ? diag::ext_module_import_not_at_top_level_noop
15339                           : diag::err_module_import_not_at_top_level_fatal)
15340         << M->getFullModuleName() << DC;
15341     S.Diag(cast<Decl>(DC)->getLocStart(),
15342            diag::note_module_import_not_at_top_level) << DC;
15343   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15344     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15345       << M->getFullModuleName();
15346     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15347   }
15348 }
15349 
15350 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15351   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15352 }
15353 
15354 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15355                                            ModuleDeclKind MDK,
15356                                            ModuleIdPath Path) {
15357   // 'module implementation' requires that we are not compiling a module of any
15358   // kind. 'module' and 'module partition' require that we are compiling a
15359   // module inteface (not a module map).
15360   auto CMK = getLangOpts().getCompilingModule();
15361   if (MDK == ModuleDeclKind::Implementation
15362           ? CMK != LangOptions::CMK_None
15363           : CMK != LangOptions::CMK_ModuleInterface) {
15364     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15365       << (unsigned)MDK;
15366     return nullptr;
15367   }
15368 
15369   // FIXME: Create a ModuleDecl and return it.
15370 
15371   // FIXME: Most of this work should be done by the preprocessor rather than
15372   // here, in case we look ahead across something where the current
15373   // module matters (eg a #include).
15374 
15375   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15376   // hierarchical module map modules, the dots here are just another character
15377   // that can appear in a module name. Flatten down to the actual module name.
15378   std::string ModuleName;
15379   for (auto &Piece : Path) {
15380     if (!ModuleName.empty())
15381       ModuleName += ".";
15382     ModuleName += Piece.first->getName();
15383   }
15384 
15385   // If a module name was explicitly specified on the command line, it must be
15386   // correct.
15387   if (!getLangOpts().CurrentModule.empty() &&
15388       getLangOpts().CurrentModule != ModuleName) {
15389     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15390         << SourceRange(Path.front().second, Path.back().second)
15391         << getLangOpts().CurrentModule;
15392     return nullptr;
15393   }
15394   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15395 
15396   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15397 
15398   switch (MDK) {
15399   case ModuleDeclKind::Module: {
15400     // FIXME: Check we're not in a submodule.
15401 
15402     // We can't have imported a definition of this module or parsed a module
15403     // map defining it already.
15404     if (auto *M = Map.findModule(ModuleName)) {
15405       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15406       if (M->DefinitionLoc.isValid())
15407         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15408       else if (const auto *FE = M->getASTFile())
15409         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15410             << FE->getName();
15411       return nullptr;
15412     }
15413 
15414     // Create a Module for the module that we're defining.
15415     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15416     assert(Mod && "module creation should not fail");
15417 
15418     // Enter the semantic scope of the module.
15419     ActOnModuleBegin(ModuleLoc, Mod);
15420     return nullptr;
15421   }
15422 
15423   case ModuleDeclKind::Partition:
15424     // FIXME: Check we are in a submodule of the named module.
15425     return nullptr;
15426 
15427   case ModuleDeclKind::Implementation:
15428     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15429         PP.getIdentifierInfo(ModuleName), Path[0].second);
15430 
15431     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15432     if (Import.isInvalid())
15433       return nullptr;
15434     return ConvertDeclToDeclGroup(Import.get());
15435   }
15436 
15437   llvm_unreachable("unexpected module decl kind");
15438 }
15439 
15440 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15441                                    SourceLocation ImportLoc,
15442                                    ModuleIdPath Path) {
15443   Module *Mod =
15444       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15445                                    /*IsIncludeDirective=*/false);
15446   if (!Mod)
15447     return true;
15448 
15449   VisibleModules.setVisible(Mod, ImportLoc);
15450 
15451   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15452 
15453   // FIXME: we should support importing a submodule within a different submodule
15454   // of the same top-level module. Until we do, make it an error rather than
15455   // silently ignoring the import.
15456   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15457   // warn on a redundant import of the current module?
15458   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15459       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15460     Diag(ImportLoc, getLangOpts().isCompilingModule()
15461                         ? diag::err_module_self_import
15462                         : diag::err_module_import_in_implementation)
15463         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15464 
15465   SmallVector<SourceLocation, 2> IdentifierLocs;
15466   Module *ModCheck = Mod;
15467   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15468     // If we've run out of module parents, just drop the remaining identifiers.
15469     // We need the length to be consistent.
15470     if (!ModCheck)
15471       break;
15472     ModCheck = ModCheck->Parent;
15473 
15474     IdentifierLocs.push_back(Path[I].second);
15475   }
15476 
15477   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15478   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15479                                           Mod, IdentifierLocs);
15480   if (!ModuleScopes.empty())
15481     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15482   TU->addDecl(Import);
15483   return Import;
15484 }
15485 
15486 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15487   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15488   BuildModuleInclude(DirectiveLoc, Mod);
15489 }
15490 
15491 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15492   // Determine whether we're in the #include buffer for a module. The #includes
15493   // in that buffer do not qualify as module imports; they're just an
15494   // implementation detail of us building the module.
15495   //
15496   // FIXME: Should we even get ActOnModuleInclude calls for those?
15497   bool IsInModuleIncludes =
15498       TUKind == TU_Module &&
15499       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15500 
15501   bool ShouldAddImport = !IsInModuleIncludes;
15502 
15503   // If this module import was due to an inclusion directive, create an
15504   // implicit import declaration to capture it in the AST.
15505   if (ShouldAddImport) {
15506     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15507     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15508                                                      DirectiveLoc, Mod,
15509                                                      DirectiveLoc);
15510     if (!ModuleScopes.empty())
15511       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15512     TU->addDecl(ImportD);
15513     Consumer.HandleImplicitImportDecl(ImportD);
15514   }
15515 
15516   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15517   VisibleModules.setVisible(Mod, DirectiveLoc);
15518 }
15519 
15520 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15521   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15522 
15523   ModuleScopes.push_back({});
15524   ModuleScopes.back().Module = Mod;
15525   if (getLangOpts().ModulesLocalVisibility)
15526     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15527 
15528   VisibleModules.setVisible(Mod, DirectiveLoc);
15529 }
15530 
15531 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15532   checkModuleImportContext(*this, Mod, EofLoc, CurContext);
15533 
15534   if (getLangOpts().ModulesLocalVisibility) {
15535     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15536     // Leaving a module hides namespace names, so our visible namespace cache
15537     // is now out of date.
15538     VisibleNamespaceCache.clear();
15539   }
15540 
15541   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15542          "left the wrong module scope");
15543   ModuleScopes.pop_back();
15544 
15545   // We got to the end of processing a #include of a local module. Create an
15546   // ImportDecl as we would for an imported module.
15547   FileID File = getSourceManager().getFileID(EofLoc);
15548   assert(File != getSourceManager().getMainFileID() &&
15549          "end of submodule in main source file");
15550   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15551   BuildModuleInclude(DirectiveLoc, Mod);
15552 }
15553 
15554 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15555                                                       Module *Mod) {
15556   // Bail if we're not allowed to implicitly import a module here.
15557   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15558     return;
15559 
15560   // Create the implicit import declaration.
15561   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15562   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15563                                                    Loc, Mod, Loc);
15564   TU->addDecl(ImportD);
15565   Consumer.HandleImplicitImportDecl(ImportD);
15566 
15567   // Make the module visible.
15568   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15569   VisibleModules.setVisible(Mod, Loc);
15570 }
15571 
15572 /// We have parsed the start of an export declaration, including the '{'
15573 /// (if present).
15574 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15575                                  SourceLocation LBraceLoc) {
15576   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15577 
15578   // C++ Modules TS draft:
15579   //   An export-declaration [...] shall not contain more than one
15580   //   export keyword.
15581   //
15582   // The intent here is that an export-declaration cannot appear within another
15583   // export-declaration.
15584   if (D->isExported())
15585     Diag(ExportLoc, diag::err_export_within_export);
15586 
15587   CurContext->addDecl(D);
15588   PushDeclContext(S, D);
15589   return D;
15590 }
15591 
15592 /// Complete the definition of an export declaration.
15593 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15594   auto *ED = cast<ExportDecl>(D);
15595   if (RBraceLoc.isValid())
15596     ED->setRBraceLoc(RBraceLoc);
15597 
15598   // FIXME: Diagnose export of internal-linkage declaration (including
15599   // anonymous namespace).
15600 
15601   PopDeclContext();
15602   return D;
15603 }
15604 
15605 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15606                                       IdentifierInfo* AliasName,
15607                                       SourceLocation PragmaLoc,
15608                                       SourceLocation NameLoc,
15609                                       SourceLocation AliasNameLoc) {
15610   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15611                                          LookupOrdinaryName);
15612   AsmLabelAttr *Attr =
15613       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15614 
15615   // If a declaration that:
15616   // 1) declares a function or a variable
15617   // 2) has external linkage
15618   // already exists, add a label attribute to it.
15619   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15620     if (isDeclExternC(PrevDecl))
15621       PrevDecl->addAttr(Attr);
15622     else
15623       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15624           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15625   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15626   } else
15627     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15628 }
15629 
15630 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15631                              SourceLocation PragmaLoc,
15632                              SourceLocation NameLoc) {
15633   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15634 
15635   if (PrevDecl) {
15636     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15637   } else {
15638     (void)WeakUndeclaredIdentifiers.insert(
15639       std::pair<IdentifierInfo*,WeakInfo>
15640         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15641   }
15642 }
15643 
15644 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15645                                 IdentifierInfo* AliasName,
15646                                 SourceLocation PragmaLoc,
15647                                 SourceLocation NameLoc,
15648                                 SourceLocation AliasNameLoc) {
15649   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15650                                     LookupOrdinaryName);
15651   WeakInfo W = WeakInfo(Name, NameLoc);
15652 
15653   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15654     if (!PrevDecl->hasAttr<AliasAttr>())
15655       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15656         DeclApplyPragmaWeak(TUScope, ND, W);
15657   } else {
15658     (void)WeakUndeclaredIdentifiers.insert(
15659       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15660   }
15661 }
15662 
15663 Decl *Sema::getObjCDeclContext() const {
15664   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15665 }
15666