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         AllowTemplates(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 = AllowTemplates && getAsTypeTemplateDecl(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 AllowTemplates;
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                              bool IsClassTemplateDeductionContext,
256                              IdentifierInfo **CorrectedII) {
257   // FIXME: Consider allowing this outside C++1z mode as an extension.
258   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260                               !isClassName && !HasTrailingDot;
261 
262   // Determine where we will perform name lookup.
263   DeclContext *LookupCtx = nullptr;
264   if (ObjectTypePtr) {
265     QualType ObjectType = ObjectTypePtr.get();
266     if (ObjectType->isRecordType())
267       LookupCtx = computeDeclContext(ObjectType);
268   } else if (SS && SS->isNotEmpty()) {
269     LookupCtx = computeDeclContext(*SS, false);
270 
271     if (!LookupCtx) {
272       if (isDependentScopeSpecifier(*SS)) {
273         // C++ [temp.res]p3:
274         //   A qualified-id that refers to a type and in which the
275         //   nested-name-specifier depends on a template-parameter (14.6.2)
276         //   shall be prefixed by the keyword typename to indicate that the
277         //   qualified-id denotes a type, forming an
278         //   elaborated-type-specifier (7.1.5.3).
279         //
280         // We therefore do not perform any name lookup if the result would
281         // refer to a member of an unknown specialization.
282         if (!isClassName && !IsCtorOrDtorName)
283           return nullptr;
284 
285         // We know from the grammar that this name refers to a type,
286         // so build a dependent node to describe the type.
287         if (WantNontrivialTypeSourceInfo)
288           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
289 
290         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
292                                        II, NameLoc);
293         return ParsedType::make(T);
294       }
295 
296       return nullptr;
297     }
298 
299     if (!LookupCtx->isDependentContext() &&
300         RequireCompleteDeclContext(*SS, LookupCtx))
301       return nullptr;
302   }
303 
304   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305   // lookup for class-names.
306   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
307                                       LookupOrdinaryName;
308   LookupResult Result(*this, &II, NameLoc, Kind);
309   if (LookupCtx) {
310     // Perform "qualified" name lookup into the declaration context we
311     // computed, which is either the type of the base of a member access
312     // expression or the declaration context associated with a prior
313     // nested-name-specifier.
314     LookupQualifiedName(Result, LookupCtx);
315 
316     if (ObjectTypePtr && Result.empty()) {
317       // C++ [basic.lookup.classref]p3:
318       //   If the unqualified-id is ~type-name, the type-name is looked up
319       //   in the context of the entire postfix-expression. If the type T of
320       //   the object expression is of a class type C, the type-name is also
321       //   looked up in the scope of class C. At least one of the lookups shall
322       //   find a name that refers to (possibly cv-qualified) T.
323       LookupName(Result, S);
324     }
325   } else {
326     // Perform unqualified name lookup.
327     LookupName(Result, S);
328 
329     // For unqualified lookup in a class template in MSVC mode, look into
330     // dependent base classes where the primary class template is known.
331     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332       if (ParsedType TypeInBase =
333               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
334         return TypeInBase;
335     }
336   }
337 
338   NamedDecl *IIDecl = nullptr;
339   switch (Result.getResultKind()) {
340   case LookupResult::NotFound:
341   case LookupResult::NotFoundInCurrentInstantiation:
342     if (CorrectedII) {
343       TypoCorrection Correction =
344           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345                       llvm::make_unique<TypeNameValidatorCCC>(
346                           true, isClassName, AllowDeducedTemplate),
347                       CTK_ErrorRecovery);
348       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
349       TemplateTy Template;
350       bool MemberOfUnknownSpecialization;
351       UnqualifiedId TemplateName;
352       TemplateName.setIdentifier(NewII, NameLoc);
353       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354       CXXScopeSpec NewSS, *NewSSPtr = SS;
355       if (SS && NNS) {
356         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
357         NewSSPtr = &NewSS;
358       }
359       if (Correction && (NNS || NewII != &II) &&
360           // Ignore a correction to a template type as the to-be-corrected
361           // identifier is not a template (typo correction for template names
362           // is handled elsewhere).
363           !(getLangOpts().CPlusPlus && NewSSPtr &&
364             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365                            Template, MemberOfUnknownSpecialization))) {
366         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367                                     isClassName, HasTrailingDot, ObjectTypePtr,
368                                     IsCtorOrDtorName,
369                                     WantNontrivialTypeSourceInfo,
370                                     IsClassTemplateDeductionContext);
371         if (Ty) {
372           diagnoseTypo(Correction,
373                        PDiag(diag::err_unknown_type_or_class_name_suggest)
374                          << Result.getLookupName() << isClassName);
375           if (SS && NNS)
376             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377           *CorrectedII = NewII;
378           return Ty;
379         }
380       }
381     }
382     // If typo correction failed or was not performed, fall through
383   case LookupResult::FoundOverloaded:
384   case LookupResult::FoundUnresolvedValue:
385     Result.suppressDiagnostics();
386     return nullptr;
387 
388   case LookupResult::Ambiguous:
389     // Recover from type-hiding ambiguities by hiding the type.  We'll
390     // do the lookup again when looking for an object, and we can
391     // diagnose the error then.  If we don't do this, then the error
392     // about hiding the type will be immediately followed by an error
393     // that only makes sense if the identifier was treated like a type.
394     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395       Result.suppressDiagnostics();
396       return nullptr;
397     }
398 
399     // Look to see if we have a type anywhere in the list of results.
400     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401          Res != ResEnd; ++Res) {
402       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
404         if (!IIDecl ||
405             (*Res)->getLocation().getRawEncoding() <
406               IIDecl->getLocation().getRawEncoding())
407           IIDecl = *Res;
408       }
409     }
410 
411     if (!IIDecl) {
412       // None of the entities we found is a type, so there is no way
413       // to even assume that the result is a type. In this case, don't
414       // complain about the ambiguity. The parser will either try to
415       // perform this lookup again (e.g., as an object name), which
416       // will produce the ambiguity, or will complain that it expected
417       // a type name.
418       Result.suppressDiagnostics();
419       return nullptr;
420     }
421 
422     // We found a type within the ambiguous lookup; diagnose the
423     // ambiguity and then return that type. This might be the right
424     // answer, or it might not be, but it suppresses any attempt to
425     // perform the name lookup again.
426     break;
427 
428   case LookupResult::Found:
429     IIDecl = Result.getFoundDecl();
430     break;
431   }
432 
433   assert(IIDecl && "Didn't find decl");
434 
435   QualType T;
436   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437     // C++ [class.qual]p2: A lookup that would find the injected-class-name
438     // instead names the constructors of the class, except when naming a class.
439     // This is ill-formed when we're not actually forming a ctor or dtor name.
440     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443         FoundRD->isInjectedClassName() &&
444         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
446           << &II << /*Type*/1;
447 
448     DiagnoseUseOfDecl(IIDecl, NameLoc);
449 
450     T = Context.getTypeDeclType(TD);
451     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454     if (!HasTrailingDot)
455       T = Context.getObjCInterfaceType(IDecl);
456   } else if (AllowDeducedTemplate) {
457     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
459                                                        QualType(), false);
460   }
461 
462   if (T.isNull()) {
463     // If it's not plausibly a type, suppress diagnostics.
464     Result.suppressDiagnostics();
465     return nullptr;
466   }
467 
468   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469   // constructor or destructor name (in such a case, the scope specifier
470   // will be attached to the enclosing Expr or Decl node).
471   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472       !isa<ObjCInterfaceDecl>(IIDecl)) {
473     if (WantNontrivialTypeSourceInfo) {
474       // Construct a type with type-source information.
475       TypeLocBuilder Builder;
476       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
477 
478       T = getElaboratedType(ETK_None, *SS, T);
479       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480       ElabTL.setElaboratedKeywordLoc(SourceLocation());
481       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
483     } else {
484       T = getElaboratedType(ETK_None, *SS, T);
485     }
486   }
487 
488   return ParsedType::make(T);
489 }
490 
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494   for (;; DC = DC->getLookupParent()) {
495     DC = DC->getPrimaryContext();
496     auto *ND = dyn_cast<NamespaceDecl>(DC);
497     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498       return NestedNameSpecifier::Create(Context, nullptr, ND);
499     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501                                          RD->getTypeForDecl());
502     else if (isa<TranslationUnitDecl>(DC))
503       return NestedNameSpecifier::GlobalSpecifier(Context);
504   }
505   llvm_unreachable("something isn't in TU scope?");
506 }
507 
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515     DC = DC->getPrimaryContext();
516     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517       if (MD->getParent()->hasAnyDependentBases())
518         return MD->getParent();
519   }
520   return nullptr;
521 }
522 
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524                                           SourceLocation NameLoc,
525                                           bool IsTemplateTypeArg) {
526   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
527 
528   NestedNameSpecifier *NNS = nullptr;
529   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530     // If we weren't able to parse a default template argument, delay lookup
531     // until instantiation time by making a non-dependent DependentTypeName. We
532     // pretend we saw a NestedNameSpecifier referring to the current scope, and
533     // lookup is retried.
534     // FIXME: This hurts our diagnostic quality, since we get errors like "no
535     // type named 'Foo' in 'current_namespace'" when the user didn't write any
536     // name specifiers.
537     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539   } else if (const CXXRecordDecl *RD =
540                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541     // Build a DependentNameType that will perform lookup into RD at
542     // instantiation time.
543     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544                                       RD->getTypeForDecl());
545 
546     // Diagnose that this identifier was undeclared, and retry the lookup during
547     // template instantiation.
548     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
549                                                                       << RD;
550   } else {
551     // This is not a situation that we should recover from.
552     return ParsedType();
553   }
554 
555   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
556 
557   // Build type location information.  We synthesized the qualifier, so we have
558   // to build a fake NestedNameSpecifierLoc.
559   NestedNameSpecifierLocBuilder NNSLocBuilder;
560   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
562 
563   TypeLocBuilder Builder;
564   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565   DepTL.setNameLoc(NameLoc);
566   DepTL.setElaboratedKeywordLoc(SourceLocation());
567   DepTL.setQualifierLoc(QualifierLoc);
568   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
569 }
570 
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo").  If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577   // Do a tag name lookup in this scope.
578   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579   LookupName(R, S, false);
580   R.suppressDiagnostics();
581   if (R.getResultKind() == LookupResult::Found)
582     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583       switch (TD->getTagKind()) {
584       case TTK_Struct: return DeclSpec::TST_struct;
585       case TTK_Interface: return DeclSpec::TST_interface;
586       case TTK_Union:  return DeclSpec::TST_union;
587       case TTK_Class:  return DeclSpec::TST_class;
588       case TTK_Enum:   return DeclSpec::TST_enum;
589       }
590     }
591 
592   return DeclSpec::TST_unspecified;
593 }
594 
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
599 /// @code
600 /// template<class T> class A {
601 /// public:
602 ///   typedef int TYPE;
603 /// };
604 /// template<class T> class B : public A<T> {
605 /// public:
606 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
607 /// };
608 /// @endcode
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610   if (CurContext->isRecord()) {
611     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
612       return true;
613 
614     const Type *Ty = SS->getScopeRep()->getAsType();
615 
616     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617     for (const auto &Base : RD->bases())
618       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
619         return true;
620     return S->isFunctionPrototypeScope();
621   }
622   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
623 }
624 
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626                                    SourceLocation IILoc,
627                                    Scope *S,
628                                    CXXScopeSpec *SS,
629                                    ParsedType &SuggestedType,
630                                    bool AllowClassTemplates) {
631   // We don't have anything to suggest (yet).
632   SuggestedType = nullptr;
633 
634   // There may have been a typo in the name of the type. Look up typo
635   // results, in case we have something that we can suggest.
636   if (TypoCorrection Corrected =
637           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
638                       llvm::make_unique<TypeNameValidatorCCC>(
639                           false, false, AllowClassTemplates),
640                       CTK_ErrorRecovery)) {
641     if (Corrected.isKeyword()) {
642       // We corrected to a keyword.
643       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
644       II = Corrected.getCorrectionAsIdentifierInfo();
645     } else {
646       // We found a similarly-named type or interface; suggest that.
647       if (!SS || !SS->isSet()) {
648         diagnoseTypo(Corrected,
649                      PDiag(diag::err_unknown_typename_suggest) << II);
650       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
651         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
652         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
653                                 II->getName().equals(CorrectedStr);
654         diagnoseTypo(Corrected,
655                      PDiag(diag::err_unknown_nested_typename_suggest)
656                        << II << DC << DroppedSpecifier << SS->getRange());
657       } else {
658         llvm_unreachable("could not have corrected a typo here");
659       }
660 
661       CXXScopeSpec tmpSS;
662       if (Corrected.getCorrectionSpecifier())
663         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
664                           SourceRange(IILoc));
665       // FIXME: Support class template argument deduction here.
666       SuggestedType =
667           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
668                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
669                       /*IsCtorOrDtorName=*/false,
670                       /*NonTrivialTypeSourceInfo=*/true);
671     }
672     return;
673   }
674 
675   if (getLangOpts().CPlusPlus) {
676     // See if II is a class template that the user forgot to pass arguments to.
677     UnqualifiedId Name;
678     Name.setIdentifier(II, IILoc);
679     CXXScopeSpec EmptySS;
680     TemplateTy TemplateResult;
681     bool MemberOfUnknownSpecialization;
682     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
683                        Name, nullptr, true, TemplateResult,
684                        MemberOfUnknownSpecialization) == TNK_Type_template) {
685       TemplateName TplName = TemplateResult.get();
686       Diag(IILoc, diag::err_template_missing_args)
687         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
688       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
689         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
690           << TplDecl->getTemplateParameters()->getSourceRange();
691       }
692       return;
693     }
694   }
695 
696   // FIXME: Should we move the logic that tries to recover from a missing tag
697   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
698 
699   if (!SS || (!SS->isSet() && !SS->isInvalid()))
700     Diag(IILoc, diag::err_unknown_typename) << II;
701   else if (DeclContext *DC = computeDeclContext(*SS, false))
702     Diag(IILoc, diag::err_typename_nested_not_found)
703       << II << DC << SS->getRange();
704   else if (isDependentScopeSpecifier(*SS)) {
705     unsigned DiagID = diag::err_typename_missing;
706     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
707       DiagID = diag::ext_typename_missing;
708 
709     Diag(SS->getRange().getBegin(), DiagID)
710       << SS->getScopeRep() << II->getName()
711       << SourceRange(SS->getRange().getBegin(), IILoc)
712       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
713     SuggestedType = ActOnTypenameType(S, SourceLocation(),
714                                       *SS, *II, IILoc).get();
715   } else {
716     assert(SS && SS->isInvalid() &&
717            "Invalid scope specifier has already been diagnosed");
718   }
719 }
720 
721 /// \brief Determine whether the given result set contains either a type name
722 /// or
723 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
724   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
725                        NextToken.is(tok::less);
726 
727   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
728     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
729       return true;
730 
731     if (CheckTemplate && isa<TemplateDecl>(*I))
732       return true;
733   }
734 
735   return false;
736 }
737 
738 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
739                                     Scope *S, CXXScopeSpec &SS,
740                                     IdentifierInfo *&Name,
741                                     SourceLocation NameLoc) {
742   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
743   SemaRef.LookupParsedName(R, S, &SS);
744   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
745     StringRef FixItTagName;
746     switch (Tag->getTagKind()) {
747       case TTK_Class:
748         FixItTagName = "class ";
749         break;
750 
751       case TTK_Enum:
752         FixItTagName = "enum ";
753         break;
754 
755       case TTK_Struct:
756         FixItTagName = "struct ";
757         break;
758 
759       case TTK_Interface:
760         FixItTagName = "__interface ";
761         break;
762 
763       case TTK_Union:
764         FixItTagName = "union ";
765         break;
766     }
767 
768     StringRef TagName = FixItTagName.drop_back();
769     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
770       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
771       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
772 
773     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
774          I != IEnd; ++I)
775       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
776         << Name << TagName;
777 
778     // Replace lookup results with just the tag decl.
779     Result.clear(Sema::LookupTagName);
780     SemaRef.LookupParsedName(Result, S, &SS);
781     return true;
782   }
783 
784   return false;
785 }
786 
787 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
788 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
789                                   QualType T, SourceLocation NameLoc) {
790   ASTContext &Context = S.Context;
791 
792   TypeLocBuilder Builder;
793   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
794 
795   T = S.getElaboratedType(ETK_None, SS, T);
796   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
797   ElabTL.setElaboratedKeywordLoc(SourceLocation());
798   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
799   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
800 }
801 
802 Sema::NameClassification
803 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
804                    SourceLocation NameLoc, const Token &NextToken,
805                    bool IsAddressOfOperand,
806                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
807   DeclarationNameInfo NameInfo(Name, NameLoc);
808   ObjCMethodDecl *CurMethod = getCurMethodDecl();
809 
810   if (NextToken.is(tok::coloncolon)) {
811     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
812     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
813   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
814              isCurrentClassName(*Name, S, &SS)) {
815     // Per [class.qual]p2, this names the constructors of SS, not the
816     // injected-class-name. We don't have a classification for that.
817     // There's not much point caching this result, since the parser
818     // will reject it later.
819     return NameClassification::Unknown();
820   }
821 
822   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
823   LookupParsedName(Result, S, &SS, !CurMethod);
824 
825   // For unqualified lookup in a class template in MSVC mode, look into
826   // dependent base classes where the primary class template is known.
827   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
828     if (ParsedType TypeInBase =
829             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
830       return TypeInBase;
831   }
832 
833   // Perform lookup for Objective-C instance variables (including automatically
834   // synthesized instance variables), if we're in an Objective-C method.
835   // FIXME: This lookup really, really needs to be folded in to the normal
836   // unqualified lookup mechanism.
837   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
838     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
839     if (E.get() || E.isInvalid())
840       return E;
841   }
842 
843   bool SecondTry = false;
844   bool IsFilteredTemplateName = false;
845 
846 Corrected:
847   switch (Result.getResultKind()) {
848   case LookupResult::NotFound:
849     // If an unqualified-id is followed by a '(', then we have a function
850     // call.
851     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
852       // In C++, this is an ADL-only call.
853       // FIXME: Reference?
854       if (getLangOpts().CPlusPlus)
855         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
856 
857       // C90 6.3.2.2:
858       //   If the expression that precedes the parenthesized argument list in a
859       //   function call consists solely of an identifier, and if no
860       //   declaration is visible for this identifier, the identifier is
861       //   implicitly declared exactly as if, in the innermost block containing
862       //   the function call, the declaration
863       //
864       //     extern int identifier ();
865       //
866       //   appeared.
867       //
868       // We also allow this in C99 as an extension.
869       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
870         Result.addDecl(D);
871         Result.resolveKind();
872         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
873       }
874     }
875 
876     // In C, we first see whether there is a tag type by the same name, in
877     // which case it's likely that the user just forgot to write "enum",
878     // "struct", or "union".
879     if (!getLangOpts().CPlusPlus && !SecondTry &&
880         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
881       break;
882     }
883 
884     // Perform typo correction to determine if there is another name that is
885     // close to this name.
886     if (!SecondTry && CCC) {
887       SecondTry = true;
888       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
889                                                  Result.getLookupKind(), S,
890                                                  &SS, std::move(CCC),
891                                                  CTK_ErrorRecovery)) {
892         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
893         unsigned QualifiedDiag = diag::err_no_member_suggest;
894 
895         NamedDecl *FirstDecl = Corrected.getFoundDecl();
896         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
897         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
898             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
899           UnqualifiedDiag = diag::err_no_template_suggest;
900           QualifiedDiag = diag::err_no_member_template_suggest;
901         } else if (UnderlyingFirstDecl &&
902                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
903                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
904                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
905           UnqualifiedDiag = diag::err_unknown_typename_suggest;
906           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
907         }
908 
909         if (SS.isEmpty()) {
910           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
911         } else {// FIXME: is this even reachable? Test it.
912           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
913           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
914                                   Name->getName().equals(CorrectedStr);
915           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
916                                     << Name << computeDeclContext(SS, false)
917                                     << DroppedSpecifier << SS.getRange());
918         }
919 
920         // Update the name, so that the caller has the new name.
921         Name = Corrected.getCorrectionAsIdentifierInfo();
922 
923         // Typo correction corrected to a keyword.
924         if (Corrected.isKeyword())
925           return Name;
926 
927         // Also update the LookupResult...
928         // FIXME: This should probably go away at some point
929         Result.clear();
930         Result.setLookupName(Corrected.getCorrection());
931         if (FirstDecl)
932           Result.addDecl(FirstDecl);
933 
934         // If we found an Objective-C instance variable, let
935         // LookupInObjCMethod build the appropriate expression to
936         // reference the ivar.
937         // FIXME: This is a gross hack.
938         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
939           Result.clear();
940           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
941           return E;
942         }
943 
944         goto Corrected;
945       }
946     }
947 
948     // We failed to correct; just fall through and let the parser deal with it.
949     Result.suppressDiagnostics();
950     return NameClassification::Unknown();
951 
952   case LookupResult::NotFoundInCurrentInstantiation: {
953     // We performed name lookup into the current instantiation, and there were
954     // dependent bases, so we treat this result the same way as any other
955     // dependent nested-name-specifier.
956 
957     // C++ [temp.res]p2:
958     //   A name used in a template declaration or definition and that is
959     //   dependent on a template-parameter is assumed not to name a type
960     //   unless the applicable name lookup finds a type name or the name is
961     //   qualified by the keyword typename.
962     //
963     // FIXME: If the next token is '<', we might want to ask the parser to
964     // perform some heroics to see if we actually have a
965     // template-argument-list, which would indicate a missing 'template'
966     // keyword here.
967     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
968                                       NameInfo, IsAddressOfOperand,
969                                       /*TemplateArgs=*/nullptr);
970   }
971 
972   case LookupResult::Found:
973   case LookupResult::FoundOverloaded:
974   case LookupResult::FoundUnresolvedValue:
975     break;
976 
977   case LookupResult::Ambiguous:
978     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
979         hasAnyAcceptableTemplateNames(Result)) {
980       // C++ [temp.local]p3:
981       //   A lookup that finds an injected-class-name (10.2) can result in an
982       //   ambiguity in certain cases (for example, if it is found in more than
983       //   one base class). If all of the injected-class-names that are found
984       //   refer to specializations of the same class template, and if the name
985       //   is followed by a template-argument-list, the reference refers to the
986       //   class template itself and not a specialization thereof, and is not
987       //   ambiguous.
988       //
989       // This filtering can make an ambiguous result into an unambiguous one,
990       // so try again after filtering out template names.
991       FilterAcceptableTemplateNames(Result);
992       if (!Result.isAmbiguous()) {
993         IsFilteredTemplateName = true;
994         break;
995       }
996     }
997 
998     // Diagnose the ambiguity and return an error.
999     return NameClassification::Error();
1000   }
1001 
1002   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1003       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1004     // C++ [temp.names]p3:
1005     //   After name lookup (3.4) finds that a name is a template-name or that
1006     //   an operator-function-id or a literal- operator-id refers to a set of
1007     //   overloaded functions any member of which is a function template if
1008     //   this is followed by a <, the < is always taken as the delimiter of a
1009     //   template-argument-list and never as the less-than operator.
1010     if (!IsFilteredTemplateName)
1011       FilterAcceptableTemplateNames(Result);
1012 
1013     if (!Result.empty()) {
1014       bool IsFunctionTemplate;
1015       bool IsVarTemplate;
1016       TemplateName Template;
1017       if (Result.end() - Result.begin() > 1) {
1018         IsFunctionTemplate = true;
1019         Template = Context.getOverloadedTemplateName(Result.begin(),
1020                                                      Result.end());
1021       } else {
1022         TemplateDecl *TD
1023           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1024         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1025         IsVarTemplate = isa<VarTemplateDecl>(TD);
1026 
1027         if (SS.isSet() && !SS.isInvalid())
1028           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1029                                                     /*TemplateKeyword=*/false,
1030                                                       TD);
1031         else
1032           Template = TemplateName(TD);
1033       }
1034 
1035       if (IsFunctionTemplate) {
1036         // Function templates always go through overload resolution, at which
1037         // point we'll perform the various checks (e.g., accessibility) we need
1038         // to based on which function we selected.
1039         Result.suppressDiagnostics();
1040 
1041         return NameClassification::FunctionTemplate(Template);
1042       }
1043 
1044       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1045                            : NameClassification::TypeTemplate(Template);
1046     }
1047   }
1048 
1049   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1050   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1051     DiagnoseUseOfDecl(Type, NameLoc);
1052     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1053     QualType T = Context.getTypeDeclType(Type);
1054     if (SS.isNotEmpty())
1055       return buildNestedType(*this, SS, T, NameLoc);
1056     return ParsedType::make(T);
1057   }
1058 
1059   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1060   if (!Class) {
1061     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1062     if (ObjCCompatibleAliasDecl *Alias =
1063             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1064       Class = Alias->getClassInterface();
1065   }
1066 
1067   if (Class) {
1068     DiagnoseUseOfDecl(Class, NameLoc);
1069 
1070     if (NextToken.is(tok::period)) {
1071       // Interface. <something> is parsed as a property reference expression.
1072       // Just return "unknown" as a fall-through for now.
1073       Result.suppressDiagnostics();
1074       return NameClassification::Unknown();
1075     }
1076 
1077     QualType T = Context.getObjCInterfaceType(Class);
1078     return ParsedType::make(T);
1079   }
1080 
1081   // We can have a type template here if we're classifying a template argument.
1082   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1083       !isa<VarTemplateDecl>(FirstDecl))
1084     return NameClassification::TypeTemplate(
1085         TemplateName(cast<TemplateDecl>(FirstDecl)));
1086 
1087   // Check for a tag type hidden by a non-type decl in a few cases where it
1088   // seems likely a type is wanted instead of the non-type that was found.
1089   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1090   if ((NextToken.is(tok::identifier) ||
1091        (NextIsOp &&
1092         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1093       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1094     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     QualType T = Context.getTypeDeclType(Type);
1097     if (SS.isNotEmpty())
1098       return buildNestedType(*this, SS, T, NameLoc);
1099     return ParsedType::make(T);
1100   }
1101 
1102   if (FirstDecl->isCXXClassMember())
1103     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1104                                            nullptr, S);
1105 
1106   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1107   return BuildDeclarationNameExpr(SS, Result, ADL);
1108 }
1109 
1110 Sema::TemplateNameKindForDiagnostics
1111 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1112   auto *TD = Name.getAsTemplateDecl();
1113   if (!TD)
1114     return TemplateNameKindForDiagnostics::DependentTemplate;
1115   if (isa<ClassTemplateDecl>(TD))
1116     return TemplateNameKindForDiagnostics::ClassTemplate;
1117   if (isa<FunctionTemplateDecl>(TD))
1118     return TemplateNameKindForDiagnostics::FunctionTemplate;
1119   if (isa<VarTemplateDecl>(TD))
1120     return TemplateNameKindForDiagnostics::VarTemplate;
1121   if (isa<TypeAliasTemplateDecl>(TD))
1122     return TemplateNameKindForDiagnostics::AliasTemplate;
1123   if (isa<TemplateTemplateParmDecl>(TD))
1124     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1125   return TemplateNameKindForDiagnostics::DependentTemplate;
1126 }
1127 
1128 // Determines the context to return to after temporarily entering a
1129 // context.  This depends in an unnecessarily complicated way on the
1130 // exact ordering of callbacks from the parser.
1131 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1132 
1133   // Functions defined inline within classes aren't parsed until we've
1134   // finished parsing the top-level class, so the top-level class is
1135   // the context we'll need to return to.
1136   // A Lambda call operator whose parent is a class must not be treated
1137   // as an inline member function.  A Lambda can be used legally
1138   // either as an in-class member initializer or a default argument.  These
1139   // are parsed once the class has been marked complete and so the containing
1140   // context would be the nested class (when the lambda is defined in one);
1141   // If the class is not complete, then the lambda is being used in an
1142   // ill-formed fashion (such as to specify the width of a bit-field, or
1143   // in an array-bound) - in which case we still want to return the
1144   // lexically containing DC (which could be a nested class).
1145   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1146     DC = DC->getLexicalParent();
1147 
1148     // A function not defined within a class will always return to its
1149     // lexical context.
1150     if (!isa<CXXRecordDecl>(DC))
1151       return DC;
1152 
1153     // A C++ inline method/friend is parsed *after* the topmost class
1154     // it was declared in is fully parsed ("complete");  the topmost
1155     // class is the context we need to return to.
1156     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1157       DC = RD;
1158 
1159     // Return the declaration context of the topmost class the inline method is
1160     // declared in.
1161     return DC;
1162   }
1163 
1164   return DC->getLexicalParent();
1165 }
1166 
1167 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1168   assert(getContainingDC(DC) == CurContext &&
1169       "The next DeclContext should be lexically contained in the current one.");
1170   CurContext = DC;
1171   S->setEntity(DC);
1172 }
1173 
1174 void Sema::PopDeclContext() {
1175   assert(CurContext && "DeclContext imbalance!");
1176 
1177   CurContext = getContainingDC(CurContext);
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180 
1181 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1182                                                                     Decl *D) {
1183   // Unlike PushDeclContext, the context to which we return is not necessarily
1184   // the containing DC of TD, because the new context will be some pre-existing
1185   // TagDecl definition instead of a fresh one.
1186   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1187   CurContext = cast<TagDecl>(D)->getDefinition();
1188   assert(CurContext && "skipping definition of undefined tag");
1189   // Start lookups from the parent of the current context; we don't want to look
1190   // into the pre-existing complete definition.
1191   S->setEntity(CurContext->getLookupParent());
1192   return Result;
1193 }
1194 
1195 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1196   CurContext = static_cast<decltype(CurContext)>(Context);
1197 }
1198 
1199 /// EnterDeclaratorContext - Used when we must lookup names in the context
1200 /// of a declarator's nested name specifier.
1201 ///
1202 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1203   // C++0x [basic.lookup.unqual]p13:
1204   //   A name used in the definition of a static data member of class
1205   //   X (after the qualified-id of the static member) is looked up as
1206   //   if the name was used in a member function of X.
1207   // C++0x [basic.lookup.unqual]p14:
1208   //   If a variable member of a namespace is defined outside of the
1209   //   scope of its namespace then any name used in the definition of
1210   //   the variable member (after the declarator-id) is looked up as
1211   //   if the definition of the variable member occurred in its
1212   //   namespace.
1213   // Both of these imply that we should push a scope whose context
1214   // is the semantic context of the declaration.  We can't use
1215   // PushDeclContext here because that context is not necessarily
1216   // lexically contained in the current context.  Fortunately,
1217   // the containing scope should have the appropriate information.
1218 
1219   assert(!S->getEntity() && "scope already has entity");
1220 
1221 #ifndef NDEBUG
1222   Scope *Ancestor = S->getParent();
1223   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1224   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1225 #endif
1226 
1227   CurContext = DC;
1228   S->setEntity(DC);
1229 }
1230 
1231 void Sema::ExitDeclaratorContext(Scope *S) {
1232   assert(S->getEntity() == CurContext && "Context imbalance!");
1233 
1234   // Switch back to the lexical context.  The safety of this is
1235   // enforced by an assert in EnterDeclaratorContext.
1236   Scope *Ancestor = S->getParent();
1237   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1238   CurContext = Ancestor->getEntity();
1239 
1240   // We don't need to do anything with the scope, which is going to
1241   // disappear.
1242 }
1243 
1244 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1245   // We assume that the caller has already called
1246   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1247   FunctionDecl *FD = D->getAsFunction();
1248   if (!FD)
1249     return;
1250 
1251   // Same implementation as PushDeclContext, but enters the context
1252   // from the lexical parent, rather than the top-level class.
1253   assert(CurContext == FD->getLexicalParent() &&
1254     "The next DeclContext should be lexically contained in the current one.");
1255   CurContext = FD;
1256   S->setEntity(CurContext);
1257 
1258   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1259     ParmVarDecl *Param = FD->getParamDecl(P);
1260     // If the parameter has an identifier, then add it to the scope
1261     if (Param->getIdentifier()) {
1262       S->AddDecl(Param);
1263       IdResolver.AddDecl(Param);
1264     }
1265   }
1266 }
1267 
1268 void Sema::ActOnExitFunctionContext() {
1269   // Same implementation as PopDeclContext, but returns to the lexical parent,
1270   // rather than the top-level class.
1271   assert(CurContext && "DeclContext imbalance!");
1272   CurContext = CurContext->getLexicalParent();
1273   assert(CurContext && "Popped translation unit!");
1274 }
1275 
1276 /// \brief Determine whether we allow overloading of the function
1277 /// PrevDecl with another declaration.
1278 ///
1279 /// This routine determines whether overloading is possible, not
1280 /// whether some new function is actually an overload. It will return
1281 /// true in C++ (where we can always provide overloads) or, as an
1282 /// extension, in C when the previous function is already an
1283 /// overloaded function declaration or has the "overloadable"
1284 /// attribute.
1285 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1286                                        ASTContext &Context) {
1287   if (Context.getLangOpts().CPlusPlus)
1288     return true;
1289 
1290   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1291     return true;
1292 
1293   return (Previous.getResultKind() == LookupResult::Found
1294           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1295 }
1296 
1297 /// Add this decl to the scope shadowed decl chains.
1298 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1299   // Move up the scope chain until we find the nearest enclosing
1300   // non-transparent context. The declaration will be introduced into this
1301   // scope.
1302   while (S->getEntity() && S->getEntity()->isTransparentContext())
1303     S = S->getParent();
1304 
1305   // Add scoped declarations into their context, so that they can be
1306   // found later. Declarations without a context won't be inserted
1307   // into any context.
1308   if (AddToContext)
1309     CurContext->addDecl(D);
1310 
1311   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1312   // are function-local declarations.
1313   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1314       !D->getDeclContext()->getRedeclContext()->Equals(
1315         D->getLexicalDeclContext()->getRedeclContext()) &&
1316       !D->getLexicalDeclContext()->isFunctionOrMethod())
1317     return;
1318 
1319   // Template instantiations should also not be pushed into scope.
1320   if (isa<FunctionDecl>(D) &&
1321       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1322     return;
1323 
1324   // If this replaces anything in the current scope,
1325   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1326                                IEnd = IdResolver.end();
1327   for (; I != IEnd; ++I) {
1328     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1329       S->RemoveDecl(*I);
1330       IdResolver.RemoveDecl(*I);
1331 
1332       // Should only need to replace one decl.
1333       break;
1334     }
1335   }
1336 
1337   S->AddDecl(D);
1338 
1339   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1340     // Implicitly-generated labels may end up getting generated in an order that
1341     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1342     // the label at the appropriate place in the identifier chain.
1343     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1344       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1345       if (IDC == CurContext) {
1346         if (!S->isDeclScope(*I))
1347           continue;
1348       } else if (IDC->Encloses(CurContext))
1349         break;
1350     }
1351 
1352     IdResolver.InsertDeclAfter(I, D);
1353   } else {
1354     IdResolver.AddDecl(D);
1355   }
1356 }
1357 
1358 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1359   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1360     TUScope->AddDecl(D);
1361 }
1362 
1363 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1364                          bool AllowInlineNamespace) {
1365   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1366 }
1367 
1368 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1369   DeclContext *TargetDC = DC->getPrimaryContext();
1370   do {
1371     if (DeclContext *ScopeDC = S->getEntity())
1372       if (ScopeDC->getPrimaryContext() == TargetDC)
1373         return S;
1374   } while ((S = S->getParent()));
1375 
1376   return nullptr;
1377 }
1378 
1379 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1380                                             DeclContext*,
1381                                             ASTContext&);
1382 
1383 /// Filters out lookup results that don't fall within the given scope
1384 /// as determined by isDeclInScope.
1385 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1386                                 bool ConsiderLinkage,
1387                                 bool AllowInlineNamespace) {
1388   LookupResult::Filter F = R.makeFilter();
1389   while (F.hasNext()) {
1390     NamedDecl *D = F.next();
1391 
1392     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1393       continue;
1394 
1395     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1396       continue;
1397 
1398     F.erase();
1399   }
1400 
1401   F.done();
1402 }
1403 
1404 static bool isUsingDecl(NamedDecl *D) {
1405   return isa<UsingShadowDecl>(D) ||
1406          isa<UnresolvedUsingTypenameDecl>(D) ||
1407          isa<UnresolvedUsingValueDecl>(D);
1408 }
1409 
1410 /// Removes using shadow declarations from the lookup results.
1411 static void RemoveUsingDecls(LookupResult &R) {
1412   LookupResult::Filter F = R.makeFilter();
1413   while (F.hasNext())
1414     if (isUsingDecl(F.next()))
1415       F.erase();
1416 
1417   F.done();
1418 }
1419 
1420 /// \brief Check for this common pattern:
1421 /// @code
1422 /// class S {
1423 ///   S(const S&); // DO NOT IMPLEMENT
1424 ///   void operator=(const S&); // DO NOT IMPLEMENT
1425 /// };
1426 /// @endcode
1427 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1428   // FIXME: Should check for private access too but access is set after we get
1429   // the decl here.
1430   if (D->doesThisDeclarationHaveABody())
1431     return false;
1432 
1433   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1434     return CD->isCopyConstructor();
1435   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1436     return Method->isCopyAssignmentOperator();
1437   return false;
1438 }
1439 
1440 // We need this to handle
1441 //
1442 // typedef struct {
1443 //   void *foo() { return 0; }
1444 // } A;
1445 //
1446 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1447 // for example. If 'A', foo will have external linkage. If we have '*A',
1448 // foo will have no linkage. Since we can't know until we get to the end
1449 // of the typedef, this function finds out if D might have non-external linkage.
1450 // Callers should verify at the end of the TU if it D has external linkage or
1451 // not.
1452 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1453   const DeclContext *DC = D->getDeclContext();
1454   while (!DC->isTranslationUnit()) {
1455     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1456       if (!RD->hasNameForLinkage())
1457         return true;
1458     }
1459     DC = DC->getParent();
1460   }
1461 
1462   return !D->isExternallyVisible();
1463 }
1464 
1465 // FIXME: This needs to be refactored; some other isInMainFile users want
1466 // these semantics.
1467 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1468   if (S.TUKind != TU_Complete)
1469     return false;
1470   return S.SourceMgr.isInMainFile(Loc);
1471 }
1472 
1473 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1474   assert(D);
1475 
1476   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1477     return false;
1478 
1479   // Ignore all entities declared within templates, and out-of-line definitions
1480   // of members of class templates.
1481   if (D->getDeclContext()->isDependentContext() ||
1482       D->getLexicalDeclContext()->isDependentContext())
1483     return false;
1484 
1485   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1486     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1487       return false;
1488 
1489     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1490       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1491         return false;
1492     } else {
1493       // 'static inline' functions are defined in headers; don't warn.
1494       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1495         return false;
1496     }
1497 
1498     if (FD->doesThisDeclarationHaveABody() &&
1499         Context.DeclMustBeEmitted(FD))
1500       return false;
1501   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1502     // Constants and utility variables are defined in headers with internal
1503     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1504     // like "inline".)
1505     if (!isMainFileLoc(*this, VD->getLocation()))
1506       return false;
1507 
1508     if (Context.DeclMustBeEmitted(VD))
1509       return false;
1510 
1511     if (VD->isStaticDataMember() &&
1512         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1513       return false;
1514 
1515     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1516       return false;
1517   } else {
1518     return false;
1519   }
1520 
1521   // Only warn for unused decls internal to the translation unit.
1522   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1523   // for inline functions defined in the main source file, for instance.
1524   return mightHaveNonExternalLinkage(D);
1525 }
1526 
1527 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1528   if (!D)
1529     return;
1530 
1531   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532     const FunctionDecl *First = FD->getFirstDecl();
1533     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1534       return; // First should already be in the vector.
1535   }
1536 
1537   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1538     const VarDecl *First = VD->getFirstDecl();
1539     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1540       return; // First should already be in the vector.
1541   }
1542 
1543   if (ShouldWarnIfUnusedFileScopedDecl(D))
1544     UnusedFileScopedDecls.push_back(D);
1545 }
1546 
1547 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1548   if (D->isInvalidDecl())
1549     return false;
1550 
1551   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1552       D->hasAttr<ObjCPreciseLifetimeAttr>())
1553     return false;
1554 
1555   if (isa<LabelDecl>(D))
1556     return true;
1557 
1558   // Except for labels, we only care about unused decls that are local to
1559   // functions.
1560   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1561   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1562     // For dependent types, the diagnostic is deferred.
1563     WithinFunction =
1564         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1565   if (!WithinFunction)
1566     return false;
1567 
1568   if (isa<TypedefNameDecl>(D))
1569     return true;
1570 
1571   // White-list anything that isn't a local variable.
1572   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1573     return false;
1574 
1575   // Types of valid local variables should be complete, so this should succeed.
1576   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1577 
1578     // White-list anything with an __attribute__((unused)) type.
1579     const auto *Ty = VD->getType().getTypePtr();
1580 
1581     // Only look at the outermost level of typedef.
1582     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1583       if (TT->getDecl()->hasAttr<UnusedAttr>())
1584         return false;
1585     }
1586 
1587     // If we failed to complete the type for some reason, or if the type is
1588     // dependent, don't diagnose the variable.
1589     if (Ty->isIncompleteType() || Ty->isDependentType())
1590       return false;
1591 
1592     // Look at the element type to ensure that the warning behaviour is
1593     // consistent for both scalars and arrays.
1594     Ty = Ty->getBaseElementTypeUnsafe();
1595 
1596     if (const TagType *TT = Ty->getAs<TagType>()) {
1597       const TagDecl *Tag = TT->getDecl();
1598       if (Tag->hasAttr<UnusedAttr>())
1599         return false;
1600 
1601       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1602         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1603           return false;
1604 
1605         if (const Expr *Init = VD->getInit()) {
1606           if (const ExprWithCleanups *Cleanups =
1607                   dyn_cast<ExprWithCleanups>(Init))
1608             Init = Cleanups->getSubExpr();
1609           const CXXConstructExpr *Construct =
1610             dyn_cast<CXXConstructExpr>(Init);
1611           if (Construct && !Construct->isElidable()) {
1612             CXXConstructorDecl *CD = Construct->getConstructor();
1613             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1614               return false;
1615           }
1616         }
1617       }
1618     }
1619 
1620     // TODO: __attribute__((unused)) templates?
1621   }
1622 
1623   return true;
1624 }
1625 
1626 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1627                                      FixItHint &Hint) {
1628   if (isa<LabelDecl>(D)) {
1629     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1630                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1631     if (AfterColon.isInvalid())
1632       return;
1633     Hint = FixItHint::CreateRemoval(CharSourceRange::
1634                                     getCharRange(D->getLocStart(), AfterColon));
1635   }
1636 }
1637 
1638 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1639   if (D->getTypeForDecl()->isDependentType())
1640     return;
1641 
1642   for (auto *TmpD : D->decls()) {
1643     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1644       DiagnoseUnusedDecl(T);
1645     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1646       DiagnoseUnusedNestedTypedefs(R);
1647   }
1648 }
1649 
1650 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1651 /// unless they are marked attr(unused).
1652 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1653   if (!ShouldDiagnoseUnusedDecl(D))
1654     return;
1655 
1656   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1657     // typedefs can be referenced later on, so the diagnostics are emitted
1658     // at end-of-translation-unit.
1659     UnusedLocalTypedefNameCandidates.insert(TD);
1660     return;
1661   }
1662 
1663   FixItHint Hint;
1664   GenerateFixForUnusedDecl(D, Context, Hint);
1665 
1666   unsigned DiagID;
1667   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1668     DiagID = diag::warn_unused_exception_param;
1669   else if (isa<LabelDecl>(D))
1670     DiagID = diag::warn_unused_label;
1671   else
1672     DiagID = diag::warn_unused_variable;
1673 
1674   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1675 }
1676 
1677 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1678   // Verify that we have no forward references left.  If so, there was a goto
1679   // or address of a label taken, but no definition of it.  Label fwd
1680   // definitions are indicated with a null substmt which is also not a resolved
1681   // MS inline assembly label name.
1682   bool Diagnose = false;
1683   if (L->isMSAsmLabel())
1684     Diagnose = !L->isResolvedMSAsmLabel();
1685   else
1686     Diagnose = L->getStmt() == nullptr;
1687   if (Diagnose)
1688     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1689 }
1690 
1691 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1692   S->mergeNRVOIntoParent();
1693 
1694   if (S->decl_empty()) return;
1695   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1696          "Scope shouldn't contain decls!");
1697 
1698   for (auto *TmpD : S->decls()) {
1699     assert(TmpD && "This decl didn't get pushed??");
1700 
1701     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1702     NamedDecl *D = cast<NamedDecl>(TmpD);
1703 
1704     if (!D->getDeclName()) continue;
1705 
1706     // Diagnose unused variables in this scope.
1707     if (!S->hasUnrecoverableErrorOccurred()) {
1708       DiagnoseUnusedDecl(D);
1709       if (const auto *RD = dyn_cast<RecordDecl>(D))
1710         DiagnoseUnusedNestedTypedefs(RD);
1711     }
1712 
1713     // If this was a forward reference to a label, verify it was defined.
1714     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1715       CheckPoppedLabel(LD, *this);
1716 
1717     // Remove this name from our lexical scope, and warn on it if we haven't
1718     // already.
1719     IdResolver.RemoveDecl(D);
1720     auto ShadowI = ShadowingDecls.find(D);
1721     if (ShadowI != ShadowingDecls.end()) {
1722       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1723         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1724             << D << FD << FD->getParent();
1725         Diag(FD->getLocation(), diag::note_previous_declaration);
1726       }
1727       ShadowingDecls.erase(ShadowI);
1728     }
1729   }
1730 }
1731 
1732 /// \brief Look for an Objective-C class in the translation unit.
1733 ///
1734 /// \param Id The name of the Objective-C class we're looking for. If
1735 /// typo-correction fixes this name, the Id will be updated
1736 /// to the fixed name.
1737 ///
1738 /// \param IdLoc The location of the name in the translation unit.
1739 ///
1740 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1741 /// if there is no class with the given name.
1742 ///
1743 /// \returns The declaration of the named Objective-C class, or NULL if the
1744 /// class could not be found.
1745 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1746                                               SourceLocation IdLoc,
1747                                               bool DoTypoCorrection) {
1748   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1749   // creation from this context.
1750   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1751 
1752   if (!IDecl && DoTypoCorrection) {
1753     // Perform typo correction at the given location, but only if we
1754     // find an Objective-C class name.
1755     if (TypoCorrection C = CorrectTypo(
1756             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1757             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1758             CTK_ErrorRecovery)) {
1759       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1760       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1761       Id = IDecl->getIdentifier();
1762     }
1763   }
1764   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1765   // This routine must always return a class definition, if any.
1766   if (Def && Def->getDefinition())
1767       Def = Def->getDefinition();
1768   return Def;
1769 }
1770 
1771 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1772 /// from S, where a non-field would be declared. This routine copes
1773 /// with the difference between C and C++ scoping rules in structs and
1774 /// unions. For example, the following code is well-formed in C but
1775 /// ill-formed in C++:
1776 /// @code
1777 /// struct S6 {
1778 ///   enum { BAR } e;
1779 /// };
1780 ///
1781 /// void test_S6() {
1782 ///   struct S6 a;
1783 ///   a.e = BAR;
1784 /// }
1785 /// @endcode
1786 /// For the declaration of BAR, this routine will return a different
1787 /// scope. The scope S will be the scope of the unnamed enumeration
1788 /// within S6. In C++, this routine will return the scope associated
1789 /// with S6, because the enumeration's scope is a transparent
1790 /// context but structures can contain non-field names. In C, this
1791 /// routine will return the translation unit scope, since the
1792 /// enumeration's scope is a transparent context and structures cannot
1793 /// contain non-field names.
1794 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1795   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1796          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1797          (S->isClassScope() && !getLangOpts().CPlusPlus))
1798     S = S->getParent();
1799   return S;
1800 }
1801 
1802 /// \brief Looks up the declaration of "struct objc_super" and
1803 /// saves it for later use in building builtin declaration of
1804 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1805 /// pre-existing declaration exists no action takes place.
1806 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1807                                         IdentifierInfo *II) {
1808   if (!II->isStr("objc_msgSendSuper"))
1809     return;
1810   ASTContext &Context = ThisSema.Context;
1811 
1812   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1813                       SourceLocation(), Sema::LookupTagName);
1814   ThisSema.LookupName(Result, S);
1815   if (Result.getResultKind() == LookupResult::Found)
1816     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1817       Context.setObjCSuperType(Context.getTagDeclType(TD));
1818 }
1819 
1820 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1821   switch (Error) {
1822   case ASTContext::GE_None:
1823     return "";
1824   case ASTContext::GE_Missing_stdio:
1825     return "stdio.h";
1826   case ASTContext::GE_Missing_setjmp:
1827     return "setjmp.h";
1828   case ASTContext::GE_Missing_ucontext:
1829     return "ucontext.h";
1830   }
1831   llvm_unreachable("unhandled error kind");
1832 }
1833 
1834 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1835 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1836 /// if we're creating this built-in in anticipation of redeclaring the
1837 /// built-in.
1838 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1839                                      Scope *S, bool ForRedeclaration,
1840                                      SourceLocation Loc) {
1841   LookupPredefedObjCSuperType(*this, S, II);
1842 
1843   ASTContext::GetBuiltinTypeError Error;
1844   QualType R = Context.GetBuiltinType(ID, Error);
1845   if (Error) {
1846     if (ForRedeclaration)
1847       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1848           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1849     return nullptr;
1850   }
1851 
1852   if (!ForRedeclaration &&
1853       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1854        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1855     Diag(Loc, diag::ext_implicit_lib_function_decl)
1856         << Context.BuiltinInfo.getName(ID) << R;
1857     if (Context.BuiltinInfo.getHeaderName(ID) &&
1858         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1859       Diag(Loc, diag::note_include_header_or_declare)
1860           << Context.BuiltinInfo.getHeaderName(ID)
1861           << Context.BuiltinInfo.getName(ID);
1862   }
1863 
1864   if (R.isNull())
1865     return nullptr;
1866 
1867   DeclContext *Parent = Context.getTranslationUnitDecl();
1868   if (getLangOpts().CPlusPlus) {
1869     LinkageSpecDecl *CLinkageDecl =
1870         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1871                                 LinkageSpecDecl::lang_c, false);
1872     CLinkageDecl->setImplicit();
1873     Parent->addDecl(CLinkageDecl);
1874     Parent = CLinkageDecl;
1875   }
1876 
1877   FunctionDecl *New = FunctionDecl::Create(Context,
1878                                            Parent,
1879                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1880                                            SC_Extern,
1881                                            false,
1882                                            R->isFunctionProtoType());
1883   New->setImplicit();
1884 
1885   // Create Decl objects for each parameter, adding them to the
1886   // FunctionDecl.
1887   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1888     SmallVector<ParmVarDecl*, 16> Params;
1889     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1890       ParmVarDecl *parm =
1891           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1892                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1893                               SC_None, nullptr);
1894       parm->setScopeInfo(0, i);
1895       Params.push_back(parm);
1896     }
1897     New->setParams(Params);
1898   }
1899 
1900   AddKnownFunctionAttributes(New);
1901   RegisterLocallyScopedExternCDecl(New, S);
1902 
1903   // TUScope is the translation-unit scope to insert this function into.
1904   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1905   // relate Scopes to DeclContexts, and probably eliminate CurContext
1906   // entirely, but we're not there yet.
1907   DeclContext *SavedContext = CurContext;
1908   CurContext = Parent;
1909   PushOnScopeChains(New, TUScope);
1910   CurContext = SavedContext;
1911   return New;
1912 }
1913 
1914 /// Typedef declarations don't have linkage, but they still denote the same
1915 /// entity if their types are the same.
1916 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1917 /// isSameEntity.
1918 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1919                                                      TypedefNameDecl *Decl,
1920                                                      LookupResult &Previous) {
1921   // This is only interesting when modules are enabled.
1922   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1923     return;
1924 
1925   // Empty sets are uninteresting.
1926   if (Previous.empty())
1927     return;
1928 
1929   LookupResult::Filter Filter = Previous.makeFilter();
1930   while (Filter.hasNext()) {
1931     NamedDecl *Old = Filter.next();
1932 
1933     // Non-hidden declarations are never ignored.
1934     if (S.isVisible(Old))
1935       continue;
1936 
1937     // Declarations of the same entity are not ignored, even if they have
1938     // different linkages.
1939     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1940       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1941                                 Decl->getUnderlyingType()))
1942         continue;
1943 
1944       // If both declarations give a tag declaration a typedef name for linkage
1945       // purposes, then they declare the same entity.
1946       if (S.getLangOpts().CPlusPlus &&
1947           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1948           Decl->getAnonDeclWithTypedefName())
1949         continue;
1950     }
1951 
1952     Filter.erase();
1953   }
1954 
1955   Filter.done();
1956 }
1957 
1958 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1959   QualType OldType;
1960   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1961     OldType = OldTypedef->getUnderlyingType();
1962   else
1963     OldType = Context.getTypeDeclType(Old);
1964   QualType NewType = New->getUnderlyingType();
1965 
1966   if (NewType->isVariablyModifiedType()) {
1967     // Must not redefine a typedef with a variably-modified type.
1968     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1969     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1970       << Kind << NewType;
1971     if (Old->getLocation().isValid())
1972       Diag(Old->getLocation(), diag::note_previous_definition);
1973     New->setInvalidDecl();
1974     return true;
1975   }
1976 
1977   if (OldType != NewType &&
1978       !OldType->isDependentType() &&
1979       !NewType->isDependentType() &&
1980       !Context.hasSameType(OldType, NewType)) {
1981     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1982     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1983       << Kind << NewType << OldType;
1984     if (Old->getLocation().isValid())
1985       Diag(Old->getLocation(), diag::note_previous_definition);
1986     New->setInvalidDecl();
1987     return true;
1988   }
1989   return false;
1990 }
1991 
1992 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1993 /// same name and scope as a previous declaration 'Old'.  Figure out
1994 /// how to resolve this situation, merging decls or emitting
1995 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1996 ///
1997 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1998                                 LookupResult &OldDecls) {
1999   // If the new decl is known invalid already, don't bother doing any
2000   // merging checks.
2001   if (New->isInvalidDecl()) return;
2002 
2003   // Allow multiple definitions for ObjC built-in typedefs.
2004   // FIXME: Verify the underlying types are equivalent!
2005   if (getLangOpts().ObjC1) {
2006     const IdentifierInfo *TypeID = New->getIdentifier();
2007     switch (TypeID->getLength()) {
2008     default: break;
2009     case 2:
2010       {
2011         if (!TypeID->isStr("id"))
2012           break;
2013         QualType T = New->getUnderlyingType();
2014         if (!T->isPointerType())
2015           break;
2016         if (!T->isVoidPointerType()) {
2017           QualType PT = T->getAs<PointerType>()->getPointeeType();
2018           if (!PT->isStructureType())
2019             break;
2020         }
2021         Context.setObjCIdRedefinitionType(T);
2022         // Install the built-in type for 'id', ignoring the current definition.
2023         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2024         return;
2025       }
2026     case 5:
2027       if (!TypeID->isStr("Class"))
2028         break;
2029       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2030       // Install the built-in type for 'Class', ignoring the current definition.
2031       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2032       return;
2033     case 3:
2034       if (!TypeID->isStr("SEL"))
2035         break;
2036       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2037       // Install the built-in type for 'SEL', ignoring the current definition.
2038       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2039       return;
2040     }
2041     // Fall through - the typedef name was not a builtin type.
2042   }
2043 
2044   // Verify the old decl was also a type.
2045   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2046   if (!Old) {
2047     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2048       << New->getDeclName();
2049 
2050     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2051     if (OldD->getLocation().isValid())
2052       Diag(OldD->getLocation(), diag::note_previous_definition);
2053 
2054     return New->setInvalidDecl();
2055   }
2056 
2057   // If the old declaration is invalid, just give up here.
2058   if (Old->isInvalidDecl())
2059     return New->setInvalidDecl();
2060 
2061   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2062     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2063     auto *NewTag = New->getAnonDeclWithTypedefName();
2064     NamedDecl *Hidden = nullptr;
2065     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2066         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2067         !hasVisibleDefinition(OldTag, &Hidden)) {
2068       // There is a definition of this tag, but it is not visible. Use it
2069       // instead of our tag.
2070       New->setTypeForDecl(OldTD->getTypeForDecl());
2071       if (OldTD->isModed())
2072         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2073                                     OldTD->getUnderlyingType());
2074       else
2075         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2076 
2077       // Make the old tag definition visible.
2078       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2079 
2080       // If this was an unscoped enumeration, yank all of its enumerators
2081       // out of the scope.
2082       if (isa<EnumDecl>(NewTag)) {
2083         Scope *EnumScope = getNonFieldDeclScope(S);
2084         for (auto *D : NewTag->decls()) {
2085           auto *ED = cast<EnumConstantDecl>(D);
2086           assert(EnumScope->isDeclScope(ED));
2087           EnumScope->RemoveDecl(ED);
2088           IdResolver.RemoveDecl(ED);
2089           ED->getLexicalDeclContext()->removeDecl(ED);
2090         }
2091       }
2092     }
2093   }
2094 
2095   // If the typedef types are not identical, reject them in all languages and
2096   // with any extensions enabled.
2097   if (isIncompatibleTypedef(Old, New))
2098     return;
2099 
2100   // The types match.  Link up the redeclaration chain and merge attributes if
2101   // the old declaration was a typedef.
2102   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2103     New->setPreviousDecl(Typedef);
2104     mergeDeclAttributes(New, Old);
2105   }
2106 
2107   if (getLangOpts().MicrosoftExt)
2108     return;
2109 
2110   if (getLangOpts().CPlusPlus) {
2111     // C++ [dcl.typedef]p2:
2112     //   In a given non-class scope, a typedef specifier can be used to
2113     //   redefine the name of any type declared in that scope to refer
2114     //   to the type to which it already refers.
2115     if (!isa<CXXRecordDecl>(CurContext))
2116       return;
2117 
2118     // C++0x [dcl.typedef]p4:
2119     //   In a given class scope, a typedef specifier can be used to redefine
2120     //   any class-name declared in that scope that is not also a typedef-name
2121     //   to refer to the type to which it already refers.
2122     //
2123     // This wording came in via DR424, which was a correction to the
2124     // wording in DR56, which accidentally banned code like:
2125     //
2126     //   struct S {
2127     //     typedef struct A { } A;
2128     //   };
2129     //
2130     // in the C++03 standard. We implement the C++0x semantics, which
2131     // allow the above but disallow
2132     //
2133     //   struct S {
2134     //     typedef int I;
2135     //     typedef int I;
2136     //   };
2137     //
2138     // since that was the intent of DR56.
2139     if (!isa<TypedefNameDecl>(Old))
2140       return;
2141 
2142     Diag(New->getLocation(), diag::err_redefinition)
2143       << New->getDeclName();
2144     Diag(Old->getLocation(), diag::note_previous_definition);
2145     return New->setInvalidDecl();
2146   }
2147 
2148   // Modules always permit redefinition of typedefs, as does C11.
2149   if (getLangOpts().Modules || getLangOpts().C11)
2150     return;
2151 
2152   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2153   // is normally mapped to an error, but can be controlled with
2154   // -Wtypedef-redefinition.  If either the original or the redefinition is
2155   // in a system header, don't emit this for compatibility with GCC.
2156   if (getDiagnostics().getSuppressSystemWarnings() &&
2157       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2158        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2159     return;
2160 
2161   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2162     << New->getDeclName();
2163   Diag(Old->getLocation(), diag::note_previous_definition);
2164 }
2165 
2166 /// DeclhasAttr - returns true if decl Declaration already has the target
2167 /// attribute.
2168 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2169   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2170   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2171   for (const auto *i : D->attrs())
2172     if (i->getKind() == A->getKind()) {
2173       if (Ann) {
2174         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2175           return true;
2176         continue;
2177       }
2178       // FIXME: Don't hardcode this check
2179       if (OA && isa<OwnershipAttr>(i))
2180         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2181       return true;
2182     }
2183 
2184   return false;
2185 }
2186 
2187 static bool isAttributeTargetADefinition(Decl *D) {
2188   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2189     return VD->isThisDeclarationADefinition();
2190   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2191     return TD->isCompleteDefinition() || TD->isBeingDefined();
2192   return true;
2193 }
2194 
2195 /// Merge alignment attributes from \p Old to \p New, taking into account the
2196 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2197 ///
2198 /// \return \c true if any attributes were added to \p New.
2199 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2200   // Look for alignas attributes on Old, and pick out whichever attribute
2201   // specifies the strictest alignment requirement.
2202   AlignedAttr *OldAlignasAttr = nullptr;
2203   AlignedAttr *OldStrictestAlignAttr = nullptr;
2204   unsigned OldAlign = 0;
2205   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2206     // FIXME: We have no way of representing inherited dependent alignments
2207     // in a case like:
2208     //   template<int A, int B> struct alignas(A) X;
2209     //   template<int A, int B> struct alignas(B) X {};
2210     // For now, we just ignore any alignas attributes which are not on the
2211     // definition in such a case.
2212     if (I->isAlignmentDependent())
2213       return false;
2214 
2215     if (I->isAlignas())
2216       OldAlignasAttr = I;
2217 
2218     unsigned Align = I->getAlignment(S.Context);
2219     if (Align > OldAlign) {
2220       OldAlign = Align;
2221       OldStrictestAlignAttr = I;
2222     }
2223   }
2224 
2225   // Look for alignas attributes on New.
2226   AlignedAttr *NewAlignasAttr = nullptr;
2227   unsigned NewAlign = 0;
2228   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2229     if (I->isAlignmentDependent())
2230       return false;
2231 
2232     if (I->isAlignas())
2233       NewAlignasAttr = I;
2234 
2235     unsigned Align = I->getAlignment(S.Context);
2236     if (Align > NewAlign)
2237       NewAlign = Align;
2238   }
2239 
2240   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2241     // Both declarations have 'alignas' attributes. We require them to match.
2242     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2243     // fall short. (If two declarations both have alignas, they must both match
2244     // every definition, and so must match each other if there is a definition.)
2245 
2246     // If either declaration only contains 'alignas(0)' specifiers, then it
2247     // specifies the natural alignment for the type.
2248     if (OldAlign == 0 || NewAlign == 0) {
2249       QualType Ty;
2250       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2251         Ty = VD->getType();
2252       else
2253         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2254 
2255       if (OldAlign == 0)
2256         OldAlign = S.Context.getTypeAlign(Ty);
2257       if (NewAlign == 0)
2258         NewAlign = S.Context.getTypeAlign(Ty);
2259     }
2260 
2261     if (OldAlign != NewAlign) {
2262       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2263         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2264         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2265       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2266     }
2267   }
2268 
2269   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2270     // C++11 [dcl.align]p6:
2271     //   if any declaration of an entity has an alignment-specifier,
2272     //   every defining declaration of that entity shall specify an
2273     //   equivalent alignment.
2274     // C11 6.7.5/7:
2275     //   If the definition of an object does not have an alignment
2276     //   specifier, any other declaration of that object shall also
2277     //   have no alignment specifier.
2278     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2279       << OldAlignasAttr;
2280     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2281       << OldAlignasAttr;
2282   }
2283 
2284   bool AnyAdded = false;
2285 
2286   // Ensure we have an attribute representing the strictest alignment.
2287   if (OldAlign > NewAlign) {
2288     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2289     Clone->setInherited(true);
2290     New->addAttr(Clone);
2291     AnyAdded = true;
2292   }
2293 
2294   // Ensure we have an alignas attribute if the old declaration had one.
2295   if (OldAlignasAttr && !NewAlignasAttr &&
2296       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2297     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2298     Clone->setInherited(true);
2299     New->addAttr(Clone);
2300     AnyAdded = true;
2301   }
2302 
2303   return AnyAdded;
2304 }
2305 
2306 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2307                                const InheritableAttr *Attr,
2308                                Sema::AvailabilityMergeKind AMK) {
2309   // This function copies an attribute Attr from a previous declaration to the
2310   // new declaration D if the new declaration doesn't itself have that attribute
2311   // yet or if that attribute allows duplicates.
2312   // If you're adding a new attribute that requires logic different from
2313   // "use explicit attribute on decl if present, else use attribute from
2314   // previous decl", for example if the attribute needs to be consistent
2315   // between redeclarations, you need to call a custom merge function here.
2316   InheritableAttr *NewAttr = nullptr;
2317   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2318   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2319     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2320                                       AA->isImplicit(), AA->getIntroduced(),
2321                                       AA->getDeprecated(),
2322                                       AA->getObsoleted(), AA->getUnavailable(),
2323                                       AA->getMessage(), AA->getStrict(),
2324                                       AA->getReplacement(), AMK,
2325                                       AttrSpellingListIndex);
2326   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2327     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2328                                     AttrSpellingListIndex);
2329   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2330     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2331                                         AttrSpellingListIndex);
2332   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2333     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2334                                    AttrSpellingListIndex);
2335   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2336     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2337                                    AttrSpellingListIndex);
2338   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2339     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2340                                 FA->getFormatIdx(), FA->getFirstArg(),
2341                                 AttrSpellingListIndex);
2342   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2343     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2344                                  AttrSpellingListIndex);
2345   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2346     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2347                                        AttrSpellingListIndex,
2348                                        IA->getSemanticSpelling());
2349   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2350     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2351                                       &S.Context.Idents.get(AA->getSpelling()),
2352                                       AttrSpellingListIndex);
2353   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2354            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2355             isa<CUDAGlobalAttr>(Attr))) {
2356     // CUDA target attributes are part of function signature for
2357     // overloading purposes and must not be merged.
2358     return false;
2359   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2360     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2361   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2362     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2363   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2364     NewAttr = S.mergeInternalLinkageAttr(
2365         D, InternalLinkageA->getRange(),
2366         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2367         AttrSpellingListIndex);
2368   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2369     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2370                                 &S.Context.Idents.get(CommonA->getSpelling()),
2371                                 AttrSpellingListIndex);
2372   else if (isa<AlignedAttr>(Attr))
2373     // AlignedAttrs are handled separately, because we need to handle all
2374     // such attributes on a declaration at the same time.
2375     NewAttr = nullptr;
2376   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2377            (AMK == Sema::AMK_Override ||
2378             AMK == Sema::AMK_ProtocolImplementation))
2379     NewAttr = nullptr;
2380   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2381     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2382                               UA->getGuid());
2383   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2384     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2385 
2386   if (NewAttr) {
2387     NewAttr->setInherited(true);
2388     D->addAttr(NewAttr);
2389     if (isa<MSInheritanceAttr>(NewAttr))
2390       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2391     return true;
2392   }
2393 
2394   return false;
2395 }
2396 
2397 static const Decl *getDefinition(const Decl *D) {
2398   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2399     return TD->getDefinition();
2400   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2401     const VarDecl *Def = VD->getDefinition();
2402     if (Def)
2403       return Def;
2404     return VD->getActingDefinition();
2405   }
2406   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2407     return FD->getDefinition();
2408   return nullptr;
2409 }
2410 
2411 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2412   for (const auto *Attribute : D->attrs())
2413     if (Attribute->getKind() == Kind)
2414       return true;
2415   return false;
2416 }
2417 
2418 /// checkNewAttributesAfterDef - If we already have a definition, check that
2419 /// there are no new attributes in this declaration.
2420 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2421   if (!New->hasAttrs())
2422     return;
2423 
2424   const Decl *Def = getDefinition(Old);
2425   if (!Def || Def == New)
2426     return;
2427 
2428   AttrVec &NewAttributes = New->getAttrs();
2429   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2430     const Attr *NewAttribute = NewAttributes[I];
2431 
2432     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2433       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2434         Sema::SkipBodyInfo SkipBody;
2435         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2436 
2437         // If we're skipping this definition, drop the "alias" attribute.
2438         if (SkipBody.ShouldSkip) {
2439           NewAttributes.erase(NewAttributes.begin() + I);
2440           --E;
2441           continue;
2442         }
2443       } else {
2444         VarDecl *VD = cast<VarDecl>(New);
2445         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2446                                 VarDecl::TentativeDefinition
2447                             ? diag::err_alias_after_tentative
2448                             : diag::err_redefinition;
2449         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2450         S.Diag(Def->getLocation(), diag::note_previous_definition);
2451         VD->setInvalidDecl();
2452       }
2453       ++I;
2454       continue;
2455     }
2456 
2457     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2458       // Tentative definitions are only interesting for the alias check above.
2459       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2460         ++I;
2461         continue;
2462       }
2463     }
2464 
2465     if (hasAttribute(Def, NewAttribute->getKind())) {
2466       ++I;
2467       continue; // regular attr merging will take care of validating this.
2468     }
2469 
2470     if (isa<C11NoReturnAttr>(NewAttribute)) {
2471       // C's _Noreturn is allowed to be added to a function after it is defined.
2472       ++I;
2473       continue;
2474     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2475       if (AA->isAlignas()) {
2476         // C++11 [dcl.align]p6:
2477         //   if any declaration of an entity has an alignment-specifier,
2478         //   every defining declaration of that entity shall specify an
2479         //   equivalent alignment.
2480         // C11 6.7.5/7:
2481         //   If the definition of an object does not have an alignment
2482         //   specifier, any other declaration of that object shall also
2483         //   have no alignment specifier.
2484         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2485           << AA;
2486         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2487           << AA;
2488         NewAttributes.erase(NewAttributes.begin() + I);
2489         --E;
2490         continue;
2491       }
2492     }
2493 
2494     S.Diag(NewAttribute->getLocation(),
2495            diag::warn_attribute_precede_definition);
2496     S.Diag(Def->getLocation(), diag::note_previous_definition);
2497     NewAttributes.erase(NewAttributes.begin() + I);
2498     --E;
2499   }
2500 }
2501 
2502 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2503 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2504                                AvailabilityMergeKind AMK) {
2505   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2506     UsedAttr *NewAttr = OldAttr->clone(Context);
2507     NewAttr->setInherited(true);
2508     New->addAttr(NewAttr);
2509   }
2510 
2511   if (!Old->hasAttrs() && !New->hasAttrs())
2512     return;
2513 
2514   // Attributes declared post-definition are currently ignored.
2515   checkNewAttributesAfterDef(*this, New, Old);
2516 
2517   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2518     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2519       if (OldA->getLabel() != NewA->getLabel()) {
2520         // This redeclaration changes __asm__ label.
2521         Diag(New->getLocation(), diag::err_different_asm_label);
2522         Diag(OldA->getLocation(), diag::note_previous_declaration);
2523       }
2524     } else if (Old->isUsed()) {
2525       // This redeclaration adds an __asm__ label to a declaration that has
2526       // already been ODR-used.
2527       Diag(New->getLocation(), diag::err_late_asm_label_name)
2528         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2529     }
2530   }
2531 
2532   // Re-declaration cannot add abi_tag's.
2533   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2534     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2535       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2536         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2537                       NewTag) == OldAbiTagAttr->tags_end()) {
2538           Diag(NewAbiTagAttr->getLocation(),
2539                diag::err_new_abi_tag_on_redeclaration)
2540               << NewTag;
2541           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2542         }
2543       }
2544     } else {
2545       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2546       Diag(Old->getLocation(), diag::note_previous_declaration);
2547     }
2548   }
2549 
2550   if (!Old->hasAttrs())
2551     return;
2552 
2553   bool foundAny = New->hasAttrs();
2554 
2555   // Ensure that any moving of objects within the allocated map is done before
2556   // we process them.
2557   if (!foundAny) New->setAttrs(AttrVec());
2558 
2559   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2560     // Ignore deprecated/unavailable/availability attributes if requested.
2561     AvailabilityMergeKind LocalAMK = AMK_None;
2562     if (isa<DeprecatedAttr>(I) ||
2563         isa<UnavailableAttr>(I) ||
2564         isa<AvailabilityAttr>(I)) {
2565       switch (AMK) {
2566       case AMK_None:
2567         continue;
2568 
2569       case AMK_Redeclaration:
2570       case AMK_Override:
2571       case AMK_ProtocolImplementation:
2572         LocalAMK = AMK;
2573         break;
2574       }
2575     }
2576 
2577     // Already handled.
2578     if (isa<UsedAttr>(I))
2579       continue;
2580 
2581     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2582       foundAny = true;
2583   }
2584 
2585   if (mergeAlignedAttrs(*this, New, Old))
2586     foundAny = true;
2587 
2588   if (!foundAny) New->dropAttrs();
2589 }
2590 
2591 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2592 /// to the new one.
2593 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2594                                      const ParmVarDecl *oldDecl,
2595                                      Sema &S) {
2596   // C++11 [dcl.attr.depend]p2:
2597   //   The first declaration of a function shall specify the
2598   //   carries_dependency attribute for its declarator-id if any declaration
2599   //   of the function specifies the carries_dependency attribute.
2600   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2601   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2602     S.Diag(CDA->getLocation(),
2603            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2604     // Find the first declaration of the parameter.
2605     // FIXME: Should we build redeclaration chains for function parameters?
2606     const FunctionDecl *FirstFD =
2607       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2608     const ParmVarDecl *FirstVD =
2609       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2610     S.Diag(FirstVD->getLocation(),
2611            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2612   }
2613 
2614   if (!oldDecl->hasAttrs())
2615     return;
2616 
2617   bool foundAny = newDecl->hasAttrs();
2618 
2619   // Ensure that any moving of objects within the allocated map is
2620   // done before we process them.
2621   if (!foundAny) newDecl->setAttrs(AttrVec());
2622 
2623   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2624     if (!DeclHasAttr(newDecl, I)) {
2625       InheritableAttr *newAttr =
2626         cast<InheritableParamAttr>(I->clone(S.Context));
2627       newAttr->setInherited(true);
2628       newDecl->addAttr(newAttr);
2629       foundAny = true;
2630     }
2631   }
2632 
2633   if (!foundAny) newDecl->dropAttrs();
2634 }
2635 
2636 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2637                                 const ParmVarDecl *OldParam,
2638                                 Sema &S) {
2639   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2640     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2641       if (*Oldnullability != *Newnullability) {
2642         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2643           << DiagNullabilityKind(
2644                *Newnullability,
2645                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2646                 != 0))
2647           << DiagNullabilityKind(
2648                *Oldnullability,
2649                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2650                 != 0));
2651         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2652       }
2653     } else {
2654       QualType NewT = NewParam->getType();
2655       NewT = S.Context.getAttributedType(
2656                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2657                          NewT, NewT);
2658       NewParam->setType(NewT);
2659     }
2660   }
2661 }
2662 
2663 namespace {
2664 
2665 /// Used in MergeFunctionDecl to keep track of function parameters in
2666 /// C.
2667 struct GNUCompatibleParamWarning {
2668   ParmVarDecl *OldParm;
2669   ParmVarDecl *NewParm;
2670   QualType PromotedType;
2671 };
2672 
2673 } // end anonymous namespace
2674 
2675 /// getSpecialMember - get the special member enum for a method.
2676 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2677   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2678     if (Ctor->isDefaultConstructor())
2679       return Sema::CXXDefaultConstructor;
2680 
2681     if (Ctor->isCopyConstructor())
2682       return Sema::CXXCopyConstructor;
2683 
2684     if (Ctor->isMoveConstructor())
2685       return Sema::CXXMoveConstructor;
2686   } else if (isa<CXXDestructorDecl>(MD)) {
2687     return Sema::CXXDestructor;
2688   } else if (MD->isCopyAssignmentOperator()) {
2689     return Sema::CXXCopyAssignment;
2690   } else if (MD->isMoveAssignmentOperator()) {
2691     return Sema::CXXMoveAssignment;
2692   }
2693 
2694   return Sema::CXXInvalid;
2695 }
2696 
2697 // Determine whether the previous declaration was a definition, implicit
2698 // declaration, or a declaration.
2699 template <typename T>
2700 static std::pair<diag::kind, SourceLocation>
2701 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2702   diag::kind PrevDiag;
2703   SourceLocation OldLocation = Old->getLocation();
2704   if (Old->isThisDeclarationADefinition())
2705     PrevDiag = diag::note_previous_definition;
2706   else if (Old->isImplicit()) {
2707     PrevDiag = diag::note_previous_implicit_declaration;
2708     if (OldLocation.isInvalid())
2709       OldLocation = New->getLocation();
2710   } else
2711     PrevDiag = diag::note_previous_declaration;
2712   return std::make_pair(PrevDiag, OldLocation);
2713 }
2714 
2715 /// canRedefineFunction - checks if a function can be redefined. Currently,
2716 /// only extern inline functions can be redefined, and even then only in
2717 /// GNU89 mode.
2718 static bool canRedefineFunction(const FunctionDecl *FD,
2719                                 const LangOptions& LangOpts) {
2720   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2721           !LangOpts.CPlusPlus &&
2722           FD->isInlineSpecified() &&
2723           FD->getStorageClass() == SC_Extern);
2724 }
2725 
2726 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2727   const AttributedType *AT = T->getAs<AttributedType>();
2728   while (AT && !AT->isCallingConv())
2729     AT = AT->getModifiedType()->getAs<AttributedType>();
2730   return AT;
2731 }
2732 
2733 template <typename T>
2734 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2735   const DeclContext *DC = Old->getDeclContext();
2736   if (DC->isRecord())
2737     return false;
2738 
2739   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2740   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2741     return true;
2742   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2743     return true;
2744   return false;
2745 }
2746 
2747 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2748 static bool isExternC(VarTemplateDecl *) { return false; }
2749 
2750 /// \brief Check whether a redeclaration of an entity introduced by a
2751 /// using-declaration is valid, given that we know it's not an overload
2752 /// (nor a hidden tag declaration).
2753 template<typename ExpectedDecl>
2754 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2755                                    ExpectedDecl *New) {
2756   // C++11 [basic.scope.declarative]p4:
2757   //   Given a set of declarations in a single declarative region, each of
2758   //   which specifies the same unqualified name,
2759   //   -- they shall all refer to the same entity, or all refer to functions
2760   //      and function templates; or
2761   //   -- exactly one declaration shall declare a class name or enumeration
2762   //      name that is not a typedef name and the other declarations shall all
2763   //      refer to the same variable or enumerator, or all refer to functions
2764   //      and function templates; in this case the class name or enumeration
2765   //      name is hidden (3.3.10).
2766 
2767   // C++11 [namespace.udecl]p14:
2768   //   If a function declaration in namespace scope or block scope has the
2769   //   same name and the same parameter-type-list as a function introduced
2770   //   by a using-declaration, and the declarations do not declare the same
2771   //   function, the program is ill-formed.
2772 
2773   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2774   if (Old &&
2775       !Old->getDeclContext()->getRedeclContext()->Equals(
2776           New->getDeclContext()->getRedeclContext()) &&
2777       !(isExternC(Old) && isExternC(New)))
2778     Old = nullptr;
2779 
2780   if (!Old) {
2781     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2782     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2783     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2784     return true;
2785   }
2786   return false;
2787 }
2788 
2789 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2790                                             const FunctionDecl *B) {
2791   assert(A->getNumParams() == B->getNumParams());
2792 
2793   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2794     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2795     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2796     if (AttrA == AttrB)
2797       return true;
2798     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2799   };
2800 
2801   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2802 }
2803 
2804 /// MergeFunctionDecl - We just parsed a function 'New' from
2805 /// declarator D which has the same name and scope as a previous
2806 /// declaration 'Old'.  Figure out how to resolve this situation,
2807 /// merging decls or emitting diagnostics as appropriate.
2808 ///
2809 /// In C++, New and Old must be declarations that are not
2810 /// overloaded. Use IsOverload to determine whether New and Old are
2811 /// overloaded, and to select the Old declaration that New should be
2812 /// merged with.
2813 ///
2814 /// Returns true if there was an error, false otherwise.
2815 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2816                              Scope *S, bool MergeTypeWithOld) {
2817   // Verify the old decl was also a function.
2818   FunctionDecl *Old = OldD->getAsFunction();
2819   if (!Old) {
2820     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2821       if (New->getFriendObjectKind()) {
2822         Diag(New->getLocation(), diag::err_using_decl_friend);
2823         Diag(Shadow->getTargetDecl()->getLocation(),
2824              diag::note_using_decl_target);
2825         Diag(Shadow->getUsingDecl()->getLocation(),
2826              diag::note_using_decl) << 0;
2827         return true;
2828       }
2829 
2830       // Check whether the two declarations might declare the same function.
2831       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2832         return true;
2833       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2834     } else {
2835       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2836         << New->getDeclName();
2837       Diag(OldD->getLocation(), diag::note_previous_definition);
2838       return true;
2839     }
2840   }
2841 
2842   // If the old declaration is invalid, just give up here.
2843   if (Old->isInvalidDecl())
2844     return true;
2845 
2846   diag::kind PrevDiag;
2847   SourceLocation OldLocation;
2848   std::tie(PrevDiag, OldLocation) =
2849       getNoteDiagForInvalidRedeclaration(Old, New);
2850 
2851   // Don't complain about this if we're in GNU89 mode and the old function
2852   // is an extern inline function.
2853   // Don't complain about specializations. They are not supposed to have
2854   // storage classes.
2855   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2856       New->getStorageClass() == SC_Static &&
2857       Old->hasExternalFormalLinkage() &&
2858       !New->getTemplateSpecializationInfo() &&
2859       !canRedefineFunction(Old, getLangOpts())) {
2860     if (getLangOpts().MicrosoftExt) {
2861       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2862       Diag(OldLocation, PrevDiag);
2863     } else {
2864       Diag(New->getLocation(), diag::err_static_non_static) << New;
2865       Diag(OldLocation, PrevDiag);
2866       return true;
2867     }
2868   }
2869 
2870   if (New->hasAttr<InternalLinkageAttr>() &&
2871       !Old->hasAttr<InternalLinkageAttr>()) {
2872     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2873         << New->getDeclName();
2874     Diag(Old->getLocation(), diag::note_previous_definition);
2875     New->dropAttr<InternalLinkageAttr>();
2876   }
2877 
2878   // If a function is first declared with a calling convention, but is later
2879   // declared or defined without one, all following decls assume the calling
2880   // convention of the first.
2881   //
2882   // It's OK if a function is first declared without a calling convention,
2883   // but is later declared or defined with the default calling convention.
2884   //
2885   // To test if either decl has an explicit calling convention, we look for
2886   // AttributedType sugar nodes on the type as written.  If they are missing or
2887   // were canonicalized away, we assume the calling convention was implicit.
2888   //
2889   // Note also that we DO NOT return at this point, because we still have
2890   // other tests to run.
2891   QualType OldQType = Context.getCanonicalType(Old->getType());
2892   QualType NewQType = Context.getCanonicalType(New->getType());
2893   const FunctionType *OldType = cast<FunctionType>(OldQType);
2894   const FunctionType *NewType = cast<FunctionType>(NewQType);
2895   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2896   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2897   bool RequiresAdjustment = false;
2898 
2899   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2900     FunctionDecl *First = Old->getFirstDecl();
2901     const FunctionType *FT =
2902         First->getType().getCanonicalType()->castAs<FunctionType>();
2903     FunctionType::ExtInfo FI = FT->getExtInfo();
2904     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2905     if (!NewCCExplicit) {
2906       // Inherit the CC from the previous declaration if it was specified
2907       // there but not here.
2908       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2909       RequiresAdjustment = true;
2910     } else {
2911       // Calling conventions aren't compatible, so complain.
2912       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2913       Diag(New->getLocation(), diag::err_cconv_change)
2914         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2915         << !FirstCCExplicit
2916         << (!FirstCCExplicit ? "" :
2917             FunctionType::getNameForCallConv(FI.getCC()));
2918 
2919       // Put the note on the first decl, since it is the one that matters.
2920       Diag(First->getLocation(), diag::note_previous_declaration);
2921       return true;
2922     }
2923   }
2924 
2925   // FIXME: diagnose the other way around?
2926   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2927     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2928     RequiresAdjustment = true;
2929   }
2930 
2931   // Merge regparm attribute.
2932   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2933       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2934     if (NewTypeInfo.getHasRegParm()) {
2935       Diag(New->getLocation(), diag::err_regparm_mismatch)
2936         << NewType->getRegParmType()
2937         << OldType->getRegParmType();
2938       Diag(OldLocation, diag::note_previous_declaration);
2939       return true;
2940     }
2941 
2942     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2943     RequiresAdjustment = true;
2944   }
2945 
2946   // Merge ns_returns_retained attribute.
2947   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2948     if (NewTypeInfo.getProducesResult()) {
2949       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2950       Diag(OldLocation, diag::note_previous_declaration);
2951       return true;
2952     }
2953 
2954     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2955     RequiresAdjustment = true;
2956   }
2957 
2958   if (RequiresAdjustment) {
2959     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2960     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2961     New->setType(QualType(AdjustedType, 0));
2962     NewQType = Context.getCanonicalType(New->getType());
2963     NewType = cast<FunctionType>(NewQType);
2964   }
2965 
2966   // If this redeclaration makes the function inline, we may need to add it to
2967   // UndefinedButUsed.
2968   if (!Old->isInlined() && New->isInlined() &&
2969       !New->hasAttr<GNUInlineAttr>() &&
2970       !getLangOpts().GNUInline &&
2971       Old->isUsed(false) &&
2972       !Old->isDefined() && !New->isThisDeclarationADefinition())
2973     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2974                                            SourceLocation()));
2975 
2976   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2977   // about it.
2978   if (New->hasAttr<GNUInlineAttr>() &&
2979       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2980     UndefinedButUsed.erase(Old->getCanonicalDecl());
2981   }
2982 
2983   // If pass_object_size params don't match up perfectly, this isn't a valid
2984   // redeclaration.
2985   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2986       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2987     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2988         << New->getDeclName();
2989     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2990     return true;
2991   }
2992 
2993   if (getLangOpts().CPlusPlus) {
2994     // C++1z [over.load]p2
2995     //   Certain function declarations cannot be overloaded:
2996     //     -- Function declarations that differ only in the return type,
2997     //        the exception specification, or both cannot be overloaded.
2998 
2999     // Check the exception specifications match. This may recompute the type of
3000     // both Old and New if it resolved exception specifications, so grab the
3001     // types again after this. Because this updates the type, we do this before
3002     // any of the other checks below, which may update the "de facto" NewQType
3003     // but do not necessarily update the type of New.
3004     if (CheckEquivalentExceptionSpec(Old, New))
3005       return true;
3006     OldQType = Context.getCanonicalType(Old->getType());
3007     NewQType = Context.getCanonicalType(New->getType());
3008 
3009     // Go back to the type source info to compare the declared return types,
3010     // per C++1y [dcl.type.auto]p13:
3011     //   Redeclarations or specializations of a function or function template
3012     //   with a declared return type that uses a placeholder type shall also
3013     //   use that placeholder, not a deduced type.
3014     QualType OldDeclaredReturnType =
3015         (Old->getTypeSourceInfo()
3016              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3017              : OldType)->getReturnType();
3018     QualType NewDeclaredReturnType =
3019         (New->getTypeSourceInfo()
3020              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3021              : NewType)->getReturnType();
3022     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3023         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3024           New->isLocalExternDecl())) {
3025       QualType ResQT;
3026       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3027           OldDeclaredReturnType->isObjCObjectPointerType())
3028         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3029       if (ResQT.isNull()) {
3030         if (New->isCXXClassMember() && New->isOutOfLine())
3031           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3032               << New << New->getReturnTypeSourceRange();
3033         else
3034           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3035               << New->getReturnTypeSourceRange();
3036         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3037                                     << Old->getReturnTypeSourceRange();
3038         return true;
3039       }
3040       else
3041         NewQType = ResQT;
3042     }
3043 
3044     QualType OldReturnType = OldType->getReturnType();
3045     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3046     if (OldReturnType != NewReturnType) {
3047       // If this function has a deduced return type and has already been
3048       // defined, copy the deduced value from the old declaration.
3049       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3050       if (OldAT && OldAT->isDeduced()) {
3051         New->setType(
3052             SubstAutoType(New->getType(),
3053                           OldAT->isDependentType() ? Context.DependentTy
3054                                                    : OldAT->getDeducedType()));
3055         NewQType = Context.getCanonicalType(
3056             SubstAutoType(NewQType,
3057                           OldAT->isDependentType() ? Context.DependentTy
3058                                                    : OldAT->getDeducedType()));
3059       }
3060     }
3061 
3062     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3063     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3064     if (OldMethod && NewMethod) {
3065       // Preserve triviality.
3066       NewMethod->setTrivial(OldMethod->isTrivial());
3067 
3068       // MSVC allows explicit template specialization at class scope:
3069       // 2 CXXMethodDecls referring to the same function will be injected.
3070       // We don't want a redeclaration error.
3071       bool IsClassScopeExplicitSpecialization =
3072                               OldMethod->isFunctionTemplateSpecialization() &&
3073                               NewMethod->isFunctionTemplateSpecialization();
3074       bool isFriend = NewMethod->getFriendObjectKind();
3075 
3076       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3077           !IsClassScopeExplicitSpecialization) {
3078         //    -- Member function declarations with the same name and the
3079         //       same parameter types cannot be overloaded if any of them
3080         //       is a static member function declaration.
3081         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3082           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3083           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3084           return true;
3085         }
3086 
3087         // C++ [class.mem]p1:
3088         //   [...] A member shall not be declared twice in the
3089         //   member-specification, except that a nested class or member
3090         //   class template can be declared and then later defined.
3091         if (ActiveTemplateInstantiations.empty()) {
3092           unsigned NewDiag;
3093           if (isa<CXXConstructorDecl>(OldMethod))
3094             NewDiag = diag::err_constructor_redeclared;
3095           else if (isa<CXXDestructorDecl>(NewMethod))
3096             NewDiag = diag::err_destructor_redeclared;
3097           else if (isa<CXXConversionDecl>(NewMethod))
3098             NewDiag = diag::err_conv_function_redeclared;
3099           else
3100             NewDiag = diag::err_member_redeclared;
3101 
3102           Diag(New->getLocation(), NewDiag);
3103         } else {
3104           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3105             << New << New->getType();
3106         }
3107         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3108         return true;
3109 
3110       // Complain if this is an explicit declaration of a special
3111       // member that was initially declared implicitly.
3112       //
3113       // As an exception, it's okay to befriend such methods in order
3114       // to permit the implicit constructor/destructor/operator calls.
3115       } else if (OldMethod->isImplicit()) {
3116         if (isFriend) {
3117           NewMethod->setImplicit();
3118         } else {
3119           Diag(NewMethod->getLocation(),
3120                diag::err_definition_of_implicitly_declared_member)
3121             << New << getSpecialMember(OldMethod);
3122           return true;
3123         }
3124       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3125         Diag(NewMethod->getLocation(),
3126              diag::err_definition_of_explicitly_defaulted_member)
3127           << getSpecialMember(OldMethod);
3128         return true;
3129       }
3130     }
3131 
3132     // C++11 [dcl.attr.noreturn]p1:
3133     //   The first declaration of a function shall specify the noreturn
3134     //   attribute if any declaration of that function specifies the noreturn
3135     //   attribute.
3136     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3137     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3138       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3139       Diag(Old->getFirstDecl()->getLocation(),
3140            diag::note_noreturn_missing_first_decl);
3141     }
3142 
3143     // C++11 [dcl.attr.depend]p2:
3144     //   The first declaration of a function shall specify the
3145     //   carries_dependency attribute for its declarator-id if any declaration
3146     //   of the function specifies the carries_dependency attribute.
3147     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3148     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3149       Diag(CDA->getLocation(),
3150            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3151       Diag(Old->getFirstDecl()->getLocation(),
3152            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3153     }
3154 
3155     // (C++98 8.3.5p3):
3156     //   All declarations for a function shall agree exactly in both the
3157     //   return type and the parameter-type-list.
3158     // We also want to respect all the extended bits except noreturn.
3159 
3160     // noreturn should now match unless the old type info didn't have it.
3161     QualType OldQTypeForComparison = OldQType;
3162     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3163       auto *OldType = OldQType->castAs<FunctionProtoType>();
3164       const FunctionType *OldTypeForComparison
3165         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3166       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3167       assert(OldQTypeForComparison.isCanonical());
3168     }
3169 
3170     if (haveIncompatibleLanguageLinkages(Old, New)) {
3171       // As a special case, retain the language linkage from previous
3172       // declarations of a friend function as an extension.
3173       //
3174       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3175       // and is useful because there's otherwise no way to specify language
3176       // linkage within class scope.
3177       //
3178       // Check cautiously as the friend object kind isn't yet complete.
3179       if (New->getFriendObjectKind() != Decl::FOK_None) {
3180         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3181         Diag(OldLocation, PrevDiag);
3182       } else {
3183         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3184         Diag(OldLocation, PrevDiag);
3185         return true;
3186       }
3187     }
3188 
3189     if (OldQTypeForComparison == NewQType)
3190       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3191 
3192     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3193         New->isLocalExternDecl()) {
3194       // It's OK if we couldn't merge types for a local function declaraton
3195       // if either the old or new type is dependent. We'll merge the types
3196       // when we instantiate the function.
3197       return false;
3198     }
3199 
3200     // Fall through for conflicting redeclarations and redefinitions.
3201   }
3202 
3203   // C: Function types need to be compatible, not identical. This handles
3204   // duplicate function decls like "void f(int); void f(enum X);" properly.
3205   if (!getLangOpts().CPlusPlus &&
3206       Context.typesAreCompatible(OldQType, NewQType)) {
3207     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3208     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3209     const FunctionProtoType *OldProto = nullptr;
3210     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3211         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3212       // The old declaration provided a function prototype, but the
3213       // new declaration does not. Merge in the prototype.
3214       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3215       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3216       NewQType =
3217           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3218                                   OldProto->getExtProtoInfo());
3219       New->setType(NewQType);
3220       New->setHasInheritedPrototype();
3221 
3222       // Synthesize parameters with the same types.
3223       SmallVector<ParmVarDecl*, 16> Params;
3224       for (const auto &ParamType : OldProto->param_types()) {
3225         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3226                                                  SourceLocation(), nullptr,
3227                                                  ParamType, /*TInfo=*/nullptr,
3228                                                  SC_None, nullptr);
3229         Param->setScopeInfo(0, Params.size());
3230         Param->setImplicit();
3231         Params.push_back(Param);
3232       }
3233 
3234       New->setParams(Params);
3235     }
3236 
3237     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3238   }
3239 
3240   // GNU C permits a K&R definition to follow a prototype declaration
3241   // if the declared types of the parameters in the K&R definition
3242   // match the types in the prototype declaration, even when the
3243   // promoted types of the parameters from the K&R definition differ
3244   // from the types in the prototype. GCC then keeps the types from
3245   // the prototype.
3246   //
3247   // If a variadic prototype is followed by a non-variadic K&R definition,
3248   // the K&R definition becomes variadic.  This is sort of an edge case, but
3249   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3250   // C99 6.9.1p8.
3251   if (!getLangOpts().CPlusPlus &&
3252       Old->hasPrototype() && !New->hasPrototype() &&
3253       New->getType()->getAs<FunctionProtoType>() &&
3254       Old->getNumParams() == New->getNumParams()) {
3255     SmallVector<QualType, 16> ArgTypes;
3256     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3257     const FunctionProtoType *OldProto
3258       = Old->getType()->getAs<FunctionProtoType>();
3259     const FunctionProtoType *NewProto
3260       = New->getType()->getAs<FunctionProtoType>();
3261 
3262     // Determine whether this is the GNU C extension.
3263     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3264                                                NewProto->getReturnType());
3265     bool LooseCompatible = !MergedReturn.isNull();
3266     for (unsigned Idx = 0, End = Old->getNumParams();
3267          LooseCompatible && Idx != End; ++Idx) {
3268       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3269       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3270       if (Context.typesAreCompatible(OldParm->getType(),
3271                                      NewProto->getParamType(Idx))) {
3272         ArgTypes.push_back(NewParm->getType());
3273       } else if (Context.typesAreCompatible(OldParm->getType(),
3274                                             NewParm->getType(),
3275                                             /*CompareUnqualified=*/true)) {
3276         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3277                                            NewProto->getParamType(Idx) };
3278         Warnings.push_back(Warn);
3279         ArgTypes.push_back(NewParm->getType());
3280       } else
3281         LooseCompatible = false;
3282     }
3283 
3284     if (LooseCompatible) {
3285       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3286         Diag(Warnings[Warn].NewParm->getLocation(),
3287              diag::ext_param_promoted_not_compatible_with_prototype)
3288           << Warnings[Warn].PromotedType
3289           << Warnings[Warn].OldParm->getType();
3290         if (Warnings[Warn].OldParm->getLocation().isValid())
3291           Diag(Warnings[Warn].OldParm->getLocation(),
3292                diag::note_previous_declaration);
3293       }
3294 
3295       if (MergeTypeWithOld)
3296         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3297                                              OldProto->getExtProtoInfo()));
3298       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3299     }
3300 
3301     // Fall through to diagnose conflicting types.
3302   }
3303 
3304   // A function that has already been declared has been redeclared or
3305   // defined with a different type; show an appropriate diagnostic.
3306 
3307   // If the previous declaration was an implicitly-generated builtin
3308   // declaration, then at the very least we should use a specialized note.
3309   unsigned BuiltinID;
3310   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3311     // If it's actually a library-defined builtin function like 'malloc'
3312     // or 'printf', just warn about the incompatible redeclaration.
3313     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3314       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3315       Diag(OldLocation, diag::note_previous_builtin_declaration)
3316         << Old << Old->getType();
3317 
3318       // If this is a global redeclaration, just forget hereafter
3319       // about the "builtin-ness" of the function.
3320       //
3321       // Doing this for local extern declarations is problematic.  If
3322       // the builtin declaration remains visible, a second invalid
3323       // local declaration will produce a hard error; if it doesn't
3324       // remain visible, a single bogus local redeclaration (which is
3325       // actually only a warning) could break all the downstream code.
3326       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3327         New->getIdentifier()->revertBuiltin();
3328 
3329       return false;
3330     }
3331 
3332     PrevDiag = diag::note_previous_builtin_declaration;
3333   }
3334 
3335   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3336   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3337   return true;
3338 }
3339 
3340 /// \brief Completes the merge of two function declarations that are
3341 /// known to be compatible.
3342 ///
3343 /// This routine handles the merging of attributes and other
3344 /// properties of function declarations from the old declaration to
3345 /// the new declaration, once we know that New is in fact a
3346 /// redeclaration of Old.
3347 ///
3348 /// \returns false
3349 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3350                                         Scope *S, bool MergeTypeWithOld) {
3351   // Merge the attributes
3352   mergeDeclAttributes(New, Old);
3353 
3354   // Merge "pure" flag.
3355   if (Old->isPure())
3356     New->setPure();
3357 
3358   // Merge "used" flag.
3359   if (Old->getMostRecentDecl()->isUsed(false))
3360     New->setIsUsed();
3361 
3362   // Merge attributes from the parameters.  These can mismatch with K&R
3363   // declarations.
3364   if (New->getNumParams() == Old->getNumParams())
3365       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3366         ParmVarDecl *NewParam = New->getParamDecl(i);
3367         ParmVarDecl *OldParam = Old->getParamDecl(i);
3368         mergeParamDeclAttributes(NewParam, OldParam, *this);
3369         mergeParamDeclTypes(NewParam, OldParam, *this);
3370       }
3371 
3372   if (getLangOpts().CPlusPlus)
3373     return MergeCXXFunctionDecl(New, Old, S);
3374 
3375   // Merge the function types so the we get the composite types for the return
3376   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3377   // was visible.
3378   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3379   if (!Merged.isNull() && MergeTypeWithOld)
3380     New->setType(Merged);
3381 
3382   return false;
3383 }
3384 
3385 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3386                                 ObjCMethodDecl *oldMethod) {
3387   // Merge the attributes, including deprecated/unavailable
3388   AvailabilityMergeKind MergeKind =
3389     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3390       ? AMK_ProtocolImplementation
3391       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3392                                                        : AMK_Override;
3393 
3394   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3395 
3396   // Merge attributes from the parameters.
3397   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3398                                        oe = oldMethod->param_end();
3399   for (ObjCMethodDecl::param_iterator
3400          ni = newMethod->param_begin(), ne = newMethod->param_end();
3401        ni != ne && oi != oe; ++ni, ++oi)
3402     mergeParamDeclAttributes(*ni, *oi, *this);
3403 
3404   CheckObjCMethodOverride(newMethod, oldMethod);
3405 }
3406 
3407 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3408   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3409 
3410   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3411          ? diag::err_redefinition_different_type
3412          : diag::err_redeclaration_different_type)
3413     << New->getDeclName() << New->getType() << Old->getType();
3414 
3415   diag::kind PrevDiag;
3416   SourceLocation OldLocation;
3417   std::tie(PrevDiag, OldLocation)
3418     = getNoteDiagForInvalidRedeclaration(Old, New);
3419   S.Diag(OldLocation, PrevDiag);
3420   New->setInvalidDecl();
3421 }
3422 
3423 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3424 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3425 /// emitting diagnostics as appropriate.
3426 ///
3427 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3428 /// to here in AddInitializerToDecl. We can't check them before the initializer
3429 /// is attached.
3430 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3431                              bool MergeTypeWithOld) {
3432   if (New->isInvalidDecl() || Old->isInvalidDecl())
3433     return;
3434 
3435   QualType MergedT;
3436   if (getLangOpts().CPlusPlus) {
3437     if (New->getType()->isUndeducedType()) {
3438       // We don't know what the new type is until the initializer is attached.
3439       return;
3440     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3441       // These could still be something that needs exception specs checked.
3442       return MergeVarDeclExceptionSpecs(New, Old);
3443     }
3444     // C++ [basic.link]p10:
3445     //   [...] the types specified by all declarations referring to a given
3446     //   object or function shall be identical, except that declarations for an
3447     //   array object can specify array types that differ by the presence or
3448     //   absence of a major array bound (8.3.4).
3449     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3450       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3451       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3452 
3453       // We are merging a variable declaration New into Old. If it has an array
3454       // bound, and that bound differs from Old's bound, we should diagnose the
3455       // mismatch.
3456       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3457         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3458              PrevVD = PrevVD->getPreviousDecl()) {
3459           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3460           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3461             continue;
3462 
3463           if (!Context.hasSameType(NewArray, PrevVDTy))
3464             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3465         }
3466       }
3467 
3468       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3469         if (Context.hasSameType(OldArray->getElementType(),
3470                                 NewArray->getElementType()))
3471           MergedT = New->getType();
3472       }
3473       // FIXME: Check visibility. New is hidden but has a complete type. If New
3474       // has no array bound, it should not inherit one from Old, if Old is not
3475       // visible.
3476       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3477         if (Context.hasSameType(OldArray->getElementType(),
3478                                 NewArray->getElementType()))
3479           MergedT = Old->getType();
3480       }
3481     }
3482     else if (New->getType()->isObjCObjectPointerType() &&
3483                Old->getType()->isObjCObjectPointerType()) {
3484       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3485                                               Old->getType());
3486     }
3487   } else {
3488     // C 6.2.7p2:
3489     //   All declarations that refer to the same object or function shall have
3490     //   compatible type.
3491     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3492   }
3493   if (MergedT.isNull()) {
3494     // It's OK if we couldn't merge types if either type is dependent, for a
3495     // block-scope variable. In other cases (static data members of class
3496     // templates, variable templates, ...), we require the types to be
3497     // equivalent.
3498     // FIXME: The C++ standard doesn't say anything about this.
3499     if ((New->getType()->isDependentType() ||
3500          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3501       // If the old type was dependent, we can't merge with it, so the new type
3502       // becomes dependent for now. We'll reproduce the original type when we
3503       // instantiate the TypeSourceInfo for the variable.
3504       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3505         New->setType(Context.DependentTy);
3506       return;
3507     }
3508     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3509   }
3510 
3511   // Don't actually update the type on the new declaration if the old
3512   // declaration was an extern declaration in a different scope.
3513   if (MergeTypeWithOld)
3514     New->setType(MergedT);
3515 }
3516 
3517 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3518                                   LookupResult &Previous) {
3519   // C11 6.2.7p4:
3520   //   For an identifier with internal or external linkage declared
3521   //   in a scope in which a prior declaration of that identifier is
3522   //   visible, if the prior declaration specifies internal or
3523   //   external linkage, the type of the identifier at the later
3524   //   declaration becomes the composite type.
3525   //
3526   // If the variable isn't visible, we do not merge with its type.
3527   if (Previous.isShadowed())
3528     return false;
3529 
3530   if (S.getLangOpts().CPlusPlus) {
3531     // C++11 [dcl.array]p3:
3532     //   If there is a preceding declaration of the entity in the same
3533     //   scope in which the bound was specified, an omitted array bound
3534     //   is taken to be the same as in that earlier declaration.
3535     return NewVD->isPreviousDeclInSameBlockScope() ||
3536            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3537             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3538   } else {
3539     // If the old declaration was function-local, don't merge with its
3540     // type unless we're in the same function.
3541     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3542            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3543   }
3544 }
3545 
3546 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3547 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3548 /// situation, merging decls or emitting diagnostics as appropriate.
3549 ///
3550 /// Tentative definition rules (C99 6.9.2p2) are checked by
3551 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3552 /// definitions here, since the initializer hasn't been attached.
3553 ///
3554 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3555   // If the new decl is already invalid, don't do any other checking.
3556   if (New->isInvalidDecl())
3557     return;
3558 
3559   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3560     return;
3561 
3562   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3563 
3564   // Verify the old decl was also a variable or variable template.
3565   VarDecl *Old = nullptr;
3566   VarTemplateDecl *OldTemplate = nullptr;
3567   if (Previous.isSingleResult()) {
3568     if (NewTemplate) {
3569       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3570       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3571 
3572       if (auto *Shadow =
3573               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3574         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3575           return New->setInvalidDecl();
3576     } else {
3577       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3578 
3579       if (auto *Shadow =
3580               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3581         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3582           return New->setInvalidDecl();
3583     }
3584   }
3585   if (!Old) {
3586     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3587       << New->getDeclName();
3588     Diag(Previous.getRepresentativeDecl()->getLocation(),
3589          diag::note_previous_definition);
3590     return New->setInvalidDecl();
3591   }
3592 
3593   // Ensure the template parameters are compatible.
3594   if (NewTemplate &&
3595       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3596                                       OldTemplate->getTemplateParameters(),
3597                                       /*Complain=*/true, TPL_TemplateMatch))
3598     return New->setInvalidDecl();
3599 
3600   // C++ [class.mem]p1:
3601   //   A member shall not be declared twice in the member-specification [...]
3602   //
3603   // Here, we need only consider static data members.
3604   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3605     Diag(New->getLocation(), diag::err_duplicate_member)
3606       << New->getIdentifier();
3607     Diag(Old->getLocation(), diag::note_previous_declaration);
3608     New->setInvalidDecl();
3609   }
3610 
3611   mergeDeclAttributes(New, Old);
3612   // Warn if an already-declared variable is made a weak_import in a subsequent
3613   // declaration
3614   if (New->hasAttr<WeakImportAttr>() &&
3615       Old->getStorageClass() == SC_None &&
3616       !Old->hasAttr<WeakImportAttr>()) {
3617     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3618     Diag(Old->getLocation(), diag::note_previous_definition);
3619     // Remove weak_import attribute on new declaration.
3620     New->dropAttr<WeakImportAttr>();
3621   }
3622 
3623   if (New->hasAttr<InternalLinkageAttr>() &&
3624       !Old->hasAttr<InternalLinkageAttr>()) {
3625     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3626         << New->getDeclName();
3627     Diag(Old->getLocation(), diag::note_previous_definition);
3628     New->dropAttr<InternalLinkageAttr>();
3629   }
3630 
3631   // Merge the types.
3632   VarDecl *MostRecent = Old->getMostRecentDecl();
3633   if (MostRecent != Old) {
3634     MergeVarDeclTypes(New, MostRecent,
3635                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3636     if (New->isInvalidDecl())
3637       return;
3638   }
3639 
3640   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3641   if (New->isInvalidDecl())
3642     return;
3643 
3644   diag::kind PrevDiag;
3645   SourceLocation OldLocation;
3646   std::tie(PrevDiag, OldLocation) =
3647       getNoteDiagForInvalidRedeclaration(Old, New);
3648 
3649   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3650   if (New->getStorageClass() == SC_Static &&
3651       !New->isStaticDataMember() &&
3652       Old->hasExternalFormalLinkage()) {
3653     if (getLangOpts().MicrosoftExt) {
3654       Diag(New->getLocation(), diag::ext_static_non_static)
3655           << New->getDeclName();
3656       Diag(OldLocation, PrevDiag);
3657     } else {
3658       Diag(New->getLocation(), diag::err_static_non_static)
3659           << New->getDeclName();
3660       Diag(OldLocation, PrevDiag);
3661       return New->setInvalidDecl();
3662     }
3663   }
3664   // C99 6.2.2p4:
3665   //   For an identifier declared with the storage-class specifier
3666   //   extern in a scope in which a prior declaration of that
3667   //   identifier is visible,23) if the prior declaration specifies
3668   //   internal or external linkage, the linkage of the identifier at
3669   //   the later declaration is the same as the linkage specified at
3670   //   the prior declaration. If no prior declaration is visible, or
3671   //   if the prior declaration specifies no linkage, then the
3672   //   identifier has external linkage.
3673   if (New->hasExternalStorage() && Old->hasLinkage())
3674     /* Okay */;
3675   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3676            !New->isStaticDataMember() &&
3677            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3678     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3679     Diag(OldLocation, PrevDiag);
3680     return New->setInvalidDecl();
3681   }
3682 
3683   // Check if extern is followed by non-extern and vice-versa.
3684   if (New->hasExternalStorage() &&
3685       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3686     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3687     Diag(OldLocation, PrevDiag);
3688     return New->setInvalidDecl();
3689   }
3690   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3691       !New->hasExternalStorage()) {
3692     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3693     Diag(OldLocation, PrevDiag);
3694     return New->setInvalidDecl();
3695   }
3696 
3697   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3698 
3699   // FIXME: The test for external storage here seems wrong? We still
3700   // need to check for mismatches.
3701   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3702       // Don't complain about out-of-line definitions of static members.
3703       !(Old->getLexicalDeclContext()->isRecord() &&
3704         !New->getLexicalDeclContext()->isRecord())) {
3705     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3706     Diag(OldLocation, PrevDiag);
3707     return New->setInvalidDecl();
3708   }
3709 
3710   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3711     if (VarDecl *Def = Old->getDefinition()) {
3712       // C++1z [dcl.fcn.spec]p4:
3713       //   If the definition of a variable appears in a translation unit before
3714       //   its first declaration as inline, the program is ill-formed.
3715       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3716       Diag(Def->getLocation(), diag::note_previous_definition);
3717     }
3718   }
3719 
3720   // If this redeclaration makes the function inline, we may need to add it to
3721   // UndefinedButUsed.
3722   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3723       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3724     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3725                                            SourceLocation()));
3726 
3727   if (New->getTLSKind() != Old->getTLSKind()) {
3728     if (!Old->getTLSKind()) {
3729       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3730       Diag(OldLocation, PrevDiag);
3731     } else if (!New->getTLSKind()) {
3732       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3733       Diag(OldLocation, PrevDiag);
3734     } else {
3735       // Do not allow redeclaration to change the variable between requiring
3736       // static and dynamic initialization.
3737       // FIXME: GCC allows this, but uses the TLS keyword on the first
3738       // declaration to determine the kind. Do we need to be compatible here?
3739       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3740         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3741       Diag(OldLocation, PrevDiag);
3742     }
3743   }
3744 
3745   // C++ doesn't have tentative definitions, so go right ahead and check here.
3746   if (getLangOpts().CPlusPlus &&
3747       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3748     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3749         Old->getCanonicalDecl()->isConstexpr()) {
3750       // This definition won't be a definition any more once it's been merged.
3751       Diag(New->getLocation(),
3752            diag::warn_deprecated_redundant_constexpr_static_def);
3753     } else if (VarDecl *Def = Old->getDefinition()) {
3754       if (checkVarDeclRedefinition(Def, New))
3755         return;
3756     }
3757   }
3758 
3759   if (haveIncompatibleLanguageLinkages(Old, New)) {
3760     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3761     Diag(OldLocation, PrevDiag);
3762     New->setInvalidDecl();
3763     return;
3764   }
3765 
3766   // Merge "used" flag.
3767   if (Old->getMostRecentDecl()->isUsed(false))
3768     New->setIsUsed();
3769 
3770   // Keep a chain of previous declarations.
3771   New->setPreviousDecl(Old);
3772   if (NewTemplate)
3773     NewTemplate->setPreviousDecl(OldTemplate);
3774 
3775   // Inherit access appropriately.
3776   New->setAccess(Old->getAccess());
3777   if (NewTemplate)
3778     NewTemplate->setAccess(New->getAccess());
3779 
3780   if (Old->isInline())
3781     New->setImplicitlyInline();
3782 }
3783 
3784 /// We've just determined that \p Old and \p New both appear to be definitions
3785 /// of the same variable. Either diagnose or fix the problem.
3786 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3787   if (!hasVisibleDefinition(Old) &&
3788       (New->getFormalLinkage() == InternalLinkage ||
3789        New->isInline() ||
3790        New->getDescribedVarTemplate() ||
3791        New->getNumTemplateParameterLists() ||
3792        New->getDeclContext()->isDependentContext())) {
3793     // The previous definition is hidden, and multiple definitions are
3794     // permitted (in separate TUs). Demote this to a declaration.
3795     New->demoteThisDefinitionToDeclaration();
3796 
3797     // Make the canonical definition visible.
3798     if (auto *OldTD = Old->getDescribedVarTemplate())
3799       makeMergedDefinitionVisible(OldTD, New->getLocation());
3800     makeMergedDefinitionVisible(Old, New->getLocation());
3801     return false;
3802   } else {
3803     Diag(New->getLocation(), diag::err_redefinition) << New;
3804     Diag(Old->getLocation(), diag::note_previous_definition);
3805     New->setInvalidDecl();
3806     return true;
3807   }
3808 }
3809 
3810 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3811 /// no declarator (e.g. "struct foo;") is parsed.
3812 Decl *
3813 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3814                                  RecordDecl *&AnonRecord) {
3815   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3816                                     AnonRecord);
3817 }
3818 
3819 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3820 // disambiguate entities defined in different scopes.
3821 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3822 // compatibility.
3823 // We will pick our mangling number depending on which version of MSVC is being
3824 // targeted.
3825 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3826   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3827              ? S->getMSCurManglingNumber()
3828              : S->getMSLastManglingNumber();
3829 }
3830 
3831 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3832   if (!Context.getLangOpts().CPlusPlus)
3833     return;
3834 
3835   if (isa<CXXRecordDecl>(Tag->getParent())) {
3836     // If this tag is the direct child of a class, number it if
3837     // it is anonymous.
3838     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3839       return;
3840     MangleNumberingContext &MCtx =
3841         Context.getManglingNumberContext(Tag->getParent());
3842     Context.setManglingNumber(
3843         Tag, MCtx.getManglingNumber(
3844                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3845     return;
3846   }
3847 
3848   // If this tag isn't a direct child of a class, number it if it is local.
3849   Decl *ManglingContextDecl;
3850   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3851           Tag->getDeclContext(), ManglingContextDecl)) {
3852     Context.setManglingNumber(
3853         Tag, MCtx->getManglingNumber(
3854                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3855   }
3856 }
3857 
3858 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3859                                         TypedefNameDecl *NewTD) {
3860   if (TagFromDeclSpec->isInvalidDecl())
3861     return;
3862 
3863   // Do nothing if the tag already has a name for linkage purposes.
3864   if (TagFromDeclSpec->hasNameForLinkage())
3865     return;
3866 
3867   // A well-formed anonymous tag must always be a TUK_Definition.
3868   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3869 
3870   // The type must match the tag exactly;  no qualifiers allowed.
3871   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3872                            Context.getTagDeclType(TagFromDeclSpec))) {
3873     if (getLangOpts().CPlusPlus)
3874       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3875     return;
3876   }
3877 
3878   // If we've already computed linkage for the anonymous tag, then
3879   // adding a typedef name for the anonymous decl can change that
3880   // linkage, which might be a serious problem.  Diagnose this as
3881   // unsupported and ignore the typedef name.  TODO: we should
3882   // pursue this as a language defect and establish a formal rule
3883   // for how to handle it.
3884   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3885     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3886 
3887     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3888     tagLoc = getLocForEndOfToken(tagLoc);
3889 
3890     llvm::SmallString<40> textToInsert;
3891     textToInsert += ' ';
3892     textToInsert += NewTD->getIdentifier()->getName();
3893     Diag(tagLoc, diag::note_typedef_changes_linkage)
3894         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3895     return;
3896   }
3897 
3898   // Otherwise, set this is the anon-decl typedef for the tag.
3899   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3900 }
3901 
3902 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3903   switch (T) {
3904   case DeclSpec::TST_class:
3905     return 0;
3906   case DeclSpec::TST_struct:
3907     return 1;
3908   case DeclSpec::TST_interface:
3909     return 2;
3910   case DeclSpec::TST_union:
3911     return 3;
3912   case DeclSpec::TST_enum:
3913     return 4;
3914   default:
3915     llvm_unreachable("unexpected type specifier");
3916   }
3917 }
3918 
3919 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3920 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3921 /// parameters to cope with template friend declarations.
3922 Decl *
3923 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3924                                  MultiTemplateParamsArg TemplateParams,
3925                                  bool IsExplicitInstantiation,
3926                                  RecordDecl *&AnonRecord) {
3927   Decl *TagD = nullptr;
3928   TagDecl *Tag = nullptr;
3929   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3930       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3931       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3932       DS.getTypeSpecType() == DeclSpec::TST_union ||
3933       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3934     TagD = DS.getRepAsDecl();
3935 
3936     if (!TagD) // We probably had an error
3937       return nullptr;
3938 
3939     // Note that the above type specs guarantee that the
3940     // type rep is a Decl, whereas in many of the others
3941     // it's a Type.
3942     if (isa<TagDecl>(TagD))
3943       Tag = cast<TagDecl>(TagD);
3944     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3945       Tag = CTD->getTemplatedDecl();
3946   }
3947 
3948   if (Tag) {
3949     handleTagNumbering(Tag, S);
3950     Tag->setFreeStanding();
3951     if (Tag->isInvalidDecl())
3952       return Tag;
3953   }
3954 
3955   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3956     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3957     // or incomplete types shall not be restrict-qualified."
3958     if (TypeQuals & DeclSpec::TQ_restrict)
3959       Diag(DS.getRestrictSpecLoc(),
3960            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3961            << DS.getSourceRange();
3962   }
3963 
3964   if (DS.isInlineSpecified())
3965     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3966         << getLangOpts().CPlusPlus1z;
3967 
3968   if (DS.isConstexprSpecified()) {
3969     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3970     // and definitions of functions and variables.
3971     if (Tag)
3972       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3973           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3974     else
3975       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3976     // Don't emit warnings after this error.
3977     return TagD;
3978   }
3979 
3980   if (DS.isConceptSpecified()) {
3981     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3982     // either a function concept and its definition or a variable concept and
3983     // its initializer.
3984     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3985     return TagD;
3986   }
3987 
3988   DiagnoseFunctionSpecifiers(DS);
3989 
3990   if (DS.isFriendSpecified()) {
3991     // If we're dealing with a decl but not a TagDecl, assume that
3992     // whatever routines created it handled the friendship aspect.
3993     if (TagD && !Tag)
3994       return nullptr;
3995     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3996   }
3997 
3998   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3999   bool IsExplicitSpecialization =
4000     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4001   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4002       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4003       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4004     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4005     // nested-name-specifier unless it is an explicit instantiation
4006     // or an explicit specialization.
4007     //
4008     // FIXME: We allow class template partial specializations here too, per the
4009     // obvious intent of DR1819.
4010     //
4011     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4012     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4013         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4014     return nullptr;
4015   }
4016 
4017   // Track whether this decl-specifier declares anything.
4018   bool DeclaresAnything = true;
4019 
4020   // Handle anonymous struct definitions.
4021   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4022     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4023         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4024       if (getLangOpts().CPlusPlus ||
4025           Record->getDeclContext()->isRecord()) {
4026         // If CurContext is a DeclContext that can contain statements,
4027         // RecursiveASTVisitor won't visit the decls that
4028         // BuildAnonymousStructOrUnion() will put into CurContext.
4029         // Also store them here so that they can be part of the
4030         // DeclStmt that gets created in this case.
4031         // FIXME: Also return the IndirectFieldDecls created by
4032         // BuildAnonymousStructOr union, for the same reason?
4033         if (CurContext->isFunctionOrMethod())
4034           AnonRecord = Record;
4035         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4036                                            Context.getPrintingPolicy());
4037       }
4038 
4039       DeclaresAnything = false;
4040     }
4041   }
4042 
4043   // C11 6.7.2.1p2:
4044   //   A struct-declaration that does not declare an anonymous structure or
4045   //   anonymous union shall contain a struct-declarator-list.
4046   //
4047   // This rule also existed in C89 and C99; the grammar for struct-declaration
4048   // did not permit a struct-declaration without a struct-declarator-list.
4049   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4050       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4051     // Check for Microsoft C extension: anonymous struct/union member.
4052     // Handle 2 kinds of anonymous struct/union:
4053     //   struct STRUCT;
4054     //   union UNION;
4055     // and
4056     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4057     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4058     if ((Tag && Tag->getDeclName()) ||
4059         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4060       RecordDecl *Record = nullptr;
4061       if (Tag)
4062         Record = dyn_cast<RecordDecl>(Tag);
4063       else if (const RecordType *RT =
4064                    DS.getRepAsType().get()->getAsStructureType())
4065         Record = RT->getDecl();
4066       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4067         Record = UT->getDecl();
4068 
4069       if (Record && getLangOpts().MicrosoftExt) {
4070         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4071           << Record->isUnion() << DS.getSourceRange();
4072         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4073       }
4074 
4075       DeclaresAnything = false;
4076     }
4077   }
4078 
4079   // Skip all the checks below if we have a type error.
4080   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4081       (TagD && TagD->isInvalidDecl()))
4082     return TagD;
4083 
4084   if (getLangOpts().CPlusPlus &&
4085       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4086     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4087       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4088           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4089         DeclaresAnything = false;
4090 
4091   if (!DS.isMissingDeclaratorOk()) {
4092     // Customize diagnostic for a typedef missing a name.
4093     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4094       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4095         << DS.getSourceRange();
4096     else
4097       DeclaresAnything = false;
4098   }
4099 
4100   if (DS.isModulePrivateSpecified() &&
4101       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4102     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4103       << Tag->getTagKind()
4104       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4105 
4106   ActOnDocumentableDecl(TagD);
4107 
4108   // C 6.7/2:
4109   //   A declaration [...] shall declare at least a declarator [...], a tag,
4110   //   or the members of an enumeration.
4111   // C++ [dcl.dcl]p3:
4112   //   [If there are no declarators], and except for the declaration of an
4113   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4114   //   names into the program, or shall redeclare a name introduced by a
4115   //   previous declaration.
4116   if (!DeclaresAnything) {
4117     // In C, we allow this as a (popular) extension / bug. Don't bother
4118     // producing further diagnostics for redundant qualifiers after this.
4119     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4120     return TagD;
4121   }
4122 
4123   // C++ [dcl.stc]p1:
4124   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4125   //   init-declarator-list of the declaration shall not be empty.
4126   // C++ [dcl.fct.spec]p1:
4127   //   If a cv-qualifier appears in a decl-specifier-seq, the
4128   //   init-declarator-list of the declaration shall not be empty.
4129   //
4130   // Spurious qualifiers here appear to be valid in C.
4131   unsigned DiagID = diag::warn_standalone_specifier;
4132   if (getLangOpts().CPlusPlus)
4133     DiagID = diag::ext_standalone_specifier;
4134 
4135   // Note that a linkage-specification sets a storage class, but
4136   // 'extern "C" struct foo;' is actually valid and not theoretically
4137   // useless.
4138   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4139     if (SCS == DeclSpec::SCS_mutable)
4140       // Since mutable is not a viable storage class specifier in C, there is
4141       // no reason to treat it as an extension. Instead, diagnose as an error.
4142       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4143     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4144       Diag(DS.getStorageClassSpecLoc(), DiagID)
4145         << DeclSpec::getSpecifierName(SCS);
4146   }
4147 
4148   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4149     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4150       << DeclSpec::getSpecifierName(TSCS);
4151   if (DS.getTypeQualifiers()) {
4152     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4153       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4154     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4155       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4156     // Restrict is covered above.
4157     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4158       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4159     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4160       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4161   }
4162 
4163   // Warn about ignored type attributes, for example:
4164   // __attribute__((aligned)) struct A;
4165   // Attributes should be placed after tag to apply to type declaration.
4166   if (!DS.getAttributes().empty()) {
4167     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4168     if (TypeSpecType == DeclSpec::TST_class ||
4169         TypeSpecType == DeclSpec::TST_struct ||
4170         TypeSpecType == DeclSpec::TST_interface ||
4171         TypeSpecType == DeclSpec::TST_union ||
4172         TypeSpecType == DeclSpec::TST_enum) {
4173       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4174            attrs = attrs->getNext())
4175         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4176             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4177     }
4178   }
4179 
4180   return TagD;
4181 }
4182 
4183 /// We are trying to inject an anonymous member into the given scope;
4184 /// check if there's an existing declaration that can't be overloaded.
4185 ///
4186 /// \return true if this is a forbidden redeclaration
4187 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4188                                          Scope *S,
4189                                          DeclContext *Owner,
4190                                          DeclarationName Name,
4191                                          SourceLocation NameLoc,
4192                                          bool IsUnion) {
4193   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4194                  Sema::ForRedeclaration);
4195   if (!SemaRef.LookupName(R, S)) return false;
4196 
4197   // Pick a representative declaration.
4198   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4199   assert(PrevDecl && "Expected a non-null Decl");
4200 
4201   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4202     return false;
4203 
4204   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4205     << IsUnion << Name;
4206   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4207 
4208   return true;
4209 }
4210 
4211 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4212 /// anonymous struct or union AnonRecord into the owning context Owner
4213 /// and scope S. This routine will be invoked just after we realize
4214 /// that an unnamed union or struct is actually an anonymous union or
4215 /// struct, e.g.,
4216 ///
4217 /// @code
4218 /// union {
4219 ///   int i;
4220 ///   float f;
4221 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4222 ///    // f into the surrounding scope.x
4223 /// @endcode
4224 ///
4225 /// This routine is recursive, injecting the names of nested anonymous
4226 /// structs/unions into the owning context and scope as well.
4227 static bool
4228 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4229                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4230                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4231   bool Invalid = false;
4232 
4233   // Look every FieldDecl and IndirectFieldDecl with a name.
4234   for (auto *D : AnonRecord->decls()) {
4235     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4236         cast<NamedDecl>(D)->getDeclName()) {
4237       ValueDecl *VD = cast<ValueDecl>(D);
4238       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4239                                        VD->getLocation(),
4240                                        AnonRecord->isUnion())) {
4241         // C++ [class.union]p2:
4242         //   The names of the members of an anonymous union shall be
4243         //   distinct from the names of any other entity in the
4244         //   scope in which the anonymous union is declared.
4245         Invalid = true;
4246       } else {
4247         // C++ [class.union]p2:
4248         //   For the purpose of name lookup, after the anonymous union
4249         //   definition, the members of the anonymous union are
4250         //   considered to have been defined in the scope in which the
4251         //   anonymous union is declared.
4252         unsigned OldChainingSize = Chaining.size();
4253         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4254           Chaining.append(IF->chain_begin(), IF->chain_end());
4255         else
4256           Chaining.push_back(VD);
4257 
4258         assert(Chaining.size() >= 2);
4259         NamedDecl **NamedChain =
4260           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4261         for (unsigned i = 0; i < Chaining.size(); i++)
4262           NamedChain[i] = Chaining[i];
4263 
4264         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4265             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4266             VD->getType(), {NamedChain, Chaining.size()});
4267 
4268         for (const auto *Attr : VD->attrs())
4269           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4270 
4271         IndirectField->setAccess(AS);
4272         IndirectField->setImplicit();
4273         SemaRef.PushOnScopeChains(IndirectField, S);
4274 
4275         // That includes picking up the appropriate access specifier.
4276         if (AS != AS_none) IndirectField->setAccess(AS);
4277 
4278         Chaining.resize(OldChainingSize);
4279       }
4280     }
4281   }
4282 
4283   return Invalid;
4284 }
4285 
4286 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4287 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4288 /// illegal input values are mapped to SC_None.
4289 static StorageClass
4290 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4291   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4292   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4293          "Parser allowed 'typedef' as storage class VarDecl.");
4294   switch (StorageClassSpec) {
4295   case DeclSpec::SCS_unspecified:    return SC_None;
4296   case DeclSpec::SCS_extern:
4297     if (DS.isExternInLinkageSpec())
4298       return SC_None;
4299     return SC_Extern;
4300   case DeclSpec::SCS_static:         return SC_Static;
4301   case DeclSpec::SCS_auto:           return SC_Auto;
4302   case DeclSpec::SCS_register:       return SC_Register;
4303   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4304     // Illegal SCSs map to None: error reporting is up to the caller.
4305   case DeclSpec::SCS_mutable:        // Fall through.
4306   case DeclSpec::SCS_typedef:        return SC_None;
4307   }
4308   llvm_unreachable("unknown storage class specifier");
4309 }
4310 
4311 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4312   assert(Record->hasInClassInitializer());
4313 
4314   for (const auto *I : Record->decls()) {
4315     const auto *FD = dyn_cast<FieldDecl>(I);
4316     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4317       FD = IFD->getAnonField();
4318     if (FD && FD->hasInClassInitializer())
4319       return FD->getLocation();
4320   }
4321 
4322   llvm_unreachable("couldn't find in-class initializer");
4323 }
4324 
4325 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4326                                       SourceLocation DefaultInitLoc) {
4327   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4328     return;
4329 
4330   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4331   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4332 }
4333 
4334 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4335                                       CXXRecordDecl *AnonUnion) {
4336   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4337     return;
4338 
4339   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4340 }
4341 
4342 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4343 /// anonymous structure or union. Anonymous unions are a C++ feature
4344 /// (C++ [class.union]) and a C11 feature; anonymous structures
4345 /// are a C11 feature and GNU C++ extension.
4346 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4347                                         AccessSpecifier AS,
4348                                         RecordDecl *Record,
4349                                         const PrintingPolicy &Policy) {
4350   DeclContext *Owner = Record->getDeclContext();
4351 
4352   // Diagnose whether this anonymous struct/union is an extension.
4353   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4354     Diag(Record->getLocation(), diag::ext_anonymous_union);
4355   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4356     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4357   else if (!Record->isUnion() && !getLangOpts().C11)
4358     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4359 
4360   // C and C++ require different kinds of checks for anonymous
4361   // structs/unions.
4362   bool Invalid = false;
4363   if (getLangOpts().CPlusPlus) {
4364     const char *PrevSpec = nullptr;
4365     unsigned DiagID;
4366     if (Record->isUnion()) {
4367       // C++ [class.union]p6:
4368       //   Anonymous unions declared in a named namespace or in the
4369       //   global namespace shall be declared static.
4370       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4371           (isa<TranslationUnitDecl>(Owner) ||
4372            (isa<NamespaceDecl>(Owner) &&
4373             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4374         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4375           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4376 
4377         // Recover by adding 'static'.
4378         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4379                                PrevSpec, DiagID, Policy);
4380       }
4381       // C++ [class.union]p6:
4382       //   A storage class is not allowed in a declaration of an
4383       //   anonymous union in a class scope.
4384       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4385                isa<RecordDecl>(Owner)) {
4386         Diag(DS.getStorageClassSpecLoc(),
4387              diag::err_anonymous_union_with_storage_spec)
4388           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4389 
4390         // Recover by removing the storage specifier.
4391         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4392                                SourceLocation(),
4393                                PrevSpec, DiagID, Context.getPrintingPolicy());
4394       }
4395     }
4396 
4397     // Ignore const/volatile/restrict qualifiers.
4398     if (DS.getTypeQualifiers()) {
4399       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4400         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4401           << Record->isUnion() << "const"
4402           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4403       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4404         Diag(DS.getVolatileSpecLoc(),
4405              diag::ext_anonymous_struct_union_qualified)
4406           << Record->isUnion() << "volatile"
4407           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4408       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4409         Diag(DS.getRestrictSpecLoc(),
4410              diag::ext_anonymous_struct_union_qualified)
4411           << Record->isUnion() << "restrict"
4412           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4413       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4414         Diag(DS.getAtomicSpecLoc(),
4415              diag::ext_anonymous_struct_union_qualified)
4416           << Record->isUnion() << "_Atomic"
4417           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4418       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4419         Diag(DS.getUnalignedSpecLoc(),
4420              diag::ext_anonymous_struct_union_qualified)
4421           << Record->isUnion() << "__unaligned"
4422           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4423 
4424       DS.ClearTypeQualifiers();
4425     }
4426 
4427     // C++ [class.union]p2:
4428     //   The member-specification of an anonymous union shall only
4429     //   define non-static data members. [Note: nested types and
4430     //   functions cannot be declared within an anonymous union. ]
4431     for (auto *Mem : Record->decls()) {
4432       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4433         // C++ [class.union]p3:
4434         //   An anonymous union shall not have private or protected
4435         //   members (clause 11).
4436         assert(FD->getAccess() != AS_none);
4437         if (FD->getAccess() != AS_public) {
4438           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4439             << Record->isUnion() << (FD->getAccess() == AS_protected);
4440           Invalid = true;
4441         }
4442 
4443         // C++ [class.union]p1
4444         //   An object of a class with a non-trivial constructor, a non-trivial
4445         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4446         //   assignment operator cannot be a member of a union, nor can an
4447         //   array of such objects.
4448         if (CheckNontrivialField(FD))
4449           Invalid = true;
4450       } else if (Mem->isImplicit()) {
4451         // Any implicit members are fine.
4452       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4453         // This is a type that showed up in an
4454         // elaborated-type-specifier inside the anonymous struct or
4455         // union, but which actually declares a type outside of the
4456         // anonymous struct or union. It's okay.
4457       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4458         if (!MemRecord->isAnonymousStructOrUnion() &&
4459             MemRecord->getDeclName()) {
4460           // Visual C++ allows type definition in anonymous struct or union.
4461           if (getLangOpts().MicrosoftExt)
4462             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4463               << Record->isUnion();
4464           else {
4465             // This is a nested type declaration.
4466             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4467               << Record->isUnion();
4468             Invalid = true;
4469           }
4470         } else {
4471           // This is an anonymous type definition within another anonymous type.
4472           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4473           // not part of standard C++.
4474           Diag(MemRecord->getLocation(),
4475                diag::ext_anonymous_record_with_anonymous_type)
4476             << Record->isUnion();
4477         }
4478       } else if (isa<AccessSpecDecl>(Mem)) {
4479         // Any access specifier is fine.
4480       } else if (isa<StaticAssertDecl>(Mem)) {
4481         // In C++1z, static_assert declarations are also fine.
4482       } else {
4483         // We have something that isn't a non-static data
4484         // member. Complain about it.
4485         unsigned DK = diag::err_anonymous_record_bad_member;
4486         if (isa<TypeDecl>(Mem))
4487           DK = diag::err_anonymous_record_with_type;
4488         else if (isa<FunctionDecl>(Mem))
4489           DK = diag::err_anonymous_record_with_function;
4490         else if (isa<VarDecl>(Mem))
4491           DK = diag::err_anonymous_record_with_static;
4492 
4493         // Visual C++ allows type definition in anonymous struct or union.
4494         if (getLangOpts().MicrosoftExt &&
4495             DK == diag::err_anonymous_record_with_type)
4496           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4497             << Record->isUnion();
4498         else {
4499           Diag(Mem->getLocation(), DK) << Record->isUnion();
4500           Invalid = true;
4501         }
4502       }
4503     }
4504 
4505     // C++11 [class.union]p8 (DR1460):
4506     //   At most one variant member of a union may have a
4507     //   brace-or-equal-initializer.
4508     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4509         Owner->isRecord())
4510       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4511                                 cast<CXXRecordDecl>(Record));
4512   }
4513 
4514   if (!Record->isUnion() && !Owner->isRecord()) {
4515     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4516       << getLangOpts().CPlusPlus;
4517     Invalid = true;
4518   }
4519 
4520   // Mock up a declarator.
4521   Declarator Dc(DS, Declarator::MemberContext);
4522   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4523   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4524 
4525   // Create a declaration for this anonymous struct/union.
4526   NamedDecl *Anon = nullptr;
4527   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4528     Anon = FieldDecl::Create(Context, OwningClass,
4529                              DS.getLocStart(),
4530                              Record->getLocation(),
4531                              /*IdentifierInfo=*/nullptr,
4532                              Context.getTypeDeclType(Record),
4533                              TInfo,
4534                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4535                              /*InitStyle=*/ICIS_NoInit);
4536     Anon->setAccess(AS);
4537     if (getLangOpts().CPlusPlus)
4538       FieldCollector->Add(cast<FieldDecl>(Anon));
4539   } else {
4540     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4541     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4542     if (SCSpec == DeclSpec::SCS_mutable) {
4543       // mutable can only appear on non-static class members, so it's always
4544       // an error here
4545       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4546       Invalid = true;
4547       SC = SC_None;
4548     }
4549 
4550     Anon = VarDecl::Create(Context, Owner,
4551                            DS.getLocStart(),
4552                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4553                            Context.getTypeDeclType(Record),
4554                            TInfo, SC);
4555 
4556     // Default-initialize the implicit variable. This initialization will be
4557     // trivial in almost all cases, except if a union member has an in-class
4558     // initializer:
4559     //   union { int n = 0; };
4560     ActOnUninitializedDecl(Anon);
4561   }
4562   Anon->setImplicit();
4563 
4564   // Mark this as an anonymous struct/union type.
4565   Record->setAnonymousStructOrUnion(true);
4566 
4567   // Add the anonymous struct/union object to the current
4568   // context. We'll be referencing this object when we refer to one of
4569   // its members.
4570   Owner->addDecl(Anon);
4571 
4572   // Inject the members of the anonymous struct/union into the owning
4573   // context and into the identifier resolver chain for name lookup
4574   // purposes.
4575   SmallVector<NamedDecl*, 2> Chain;
4576   Chain.push_back(Anon);
4577 
4578   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4579     Invalid = true;
4580 
4581   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4582     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4583       Decl *ManglingContextDecl;
4584       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4585               NewVD->getDeclContext(), ManglingContextDecl)) {
4586         Context.setManglingNumber(
4587             NewVD, MCtx->getManglingNumber(
4588                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4589         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4590       }
4591     }
4592   }
4593 
4594   if (Invalid)
4595     Anon->setInvalidDecl();
4596 
4597   return Anon;
4598 }
4599 
4600 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4601 /// Microsoft C anonymous structure.
4602 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4603 /// Example:
4604 ///
4605 /// struct A { int a; };
4606 /// struct B { struct A; int b; };
4607 ///
4608 /// void foo() {
4609 ///   B var;
4610 ///   var.a = 3;
4611 /// }
4612 ///
4613 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4614                                            RecordDecl *Record) {
4615   assert(Record && "expected a record!");
4616 
4617   // Mock up a declarator.
4618   Declarator Dc(DS, Declarator::TypeNameContext);
4619   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4620   assert(TInfo && "couldn't build declarator info for anonymous struct");
4621 
4622   auto *ParentDecl = cast<RecordDecl>(CurContext);
4623   QualType RecTy = Context.getTypeDeclType(Record);
4624 
4625   // Create a declaration for this anonymous struct.
4626   NamedDecl *Anon = FieldDecl::Create(Context,
4627                              ParentDecl,
4628                              DS.getLocStart(),
4629                              DS.getLocStart(),
4630                              /*IdentifierInfo=*/nullptr,
4631                              RecTy,
4632                              TInfo,
4633                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4634                              /*InitStyle=*/ICIS_NoInit);
4635   Anon->setImplicit();
4636 
4637   // Add the anonymous struct object to the current context.
4638   CurContext->addDecl(Anon);
4639 
4640   // Inject the members of the anonymous struct into the current
4641   // context and into the identifier resolver chain for name lookup
4642   // purposes.
4643   SmallVector<NamedDecl*, 2> Chain;
4644   Chain.push_back(Anon);
4645 
4646   RecordDecl *RecordDef = Record->getDefinition();
4647   if (RequireCompleteType(Anon->getLocation(), RecTy,
4648                           diag::err_field_incomplete) ||
4649       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4650                                           AS_none, Chain)) {
4651     Anon->setInvalidDecl();
4652     ParentDecl->setInvalidDecl();
4653   }
4654 
4655   return Anon;
4656 }
4657 
4658 /// GetNameForDeclarator - Determine the full declaration name for the
4659 /// given Declarator.
4660 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4661   return GetNameFromUnqualifiedId(D.getName());
4662 }
4663 
4664 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4665 DeclarationNameInfo
4666 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4667   DeclarationNameInfo NameInfo;
4668   NameInfo.setLoc(Name.StartLocation);
4669 
4670   switch (Name.getKind()) {
4671 
4672   case UnqualifiedId::IK_ImplicitSelfParam:
4673   case UnqualifiedId::IK_Identifier:
4674     NameInfo.setName(Name.Identifier);
4675     NameInfo.setLoc(Name.StartLocation);
4676     return NameInfo;
4677 
4678   case UnqualifiedId::IK_DeductionGuideName: {
4679     // C++ [temp.deduct.guide]p3:
4680     //   The simple-template-id shall name a class template specialization.
4681     //   The template-name shall be the same identifier as the template-name
4682     //   of the simple-template-id.
4683     // These together intend to imply that the template-name shall name a
4684     // class template.
4685     // FIXME: template<typename T> struct X {};
4686     //        template<typename T> using Y = X<T>;
4687     //        Y(int) -> Y<int>;
4688     //   satisfies these rules but does not name a class template.
4689     TemplateName TN = Name.TemplateName.get().get();
4690     auto *Template = TN.getAsTemplateDecl();
4691     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4692       Diag(Name.StartLocation,
4693            diag::err_deduction_guide_name_not_class_template)
4694         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4695       if (Template)
4696         Diag(Template->getLocation(), diag::note_template_decl_here);
4697       return DeclarationNameInfo();
4698     }
4699 
4700     NameInfo.setName(
4701         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4702     NameInfo.setLoc(Name.StartLocation);
4703     return NameInfo;
4704   }
4705 
4706   case UnqualifiedId::IK_OperatorFunctionId:
4707     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4708                                            Name.OperatorFunctionId.Operator));
4709     NameInfo.setLoc(Name.StartLocation);
4710     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4711       = Name.OperatorFunctionId.SymbolLocations[0];
4712     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4713       = Name.EndLocation.getRawEncoding();
4714     return NameInfo;
4715 
4716   case UnqualifiedId::IK_LiteralOperatorId:
4717     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4718                                                            Name.Identifier));
4719     NameInfo.setLoc(Name.StartLocation);
4720     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4721     return NameInfo;
4722 
4723   case UnqualifiedId::IK_ConversionFunctionId: {
4724     TypeSourceInfo *TInfo;
4725     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4726     if (Ty.isNull())
4727       return DeclarationNameInfo();
4728     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4729                                                Context.getCanonicalType(Ty)));
4730     NameInfo.setLoc(Name.StartLocation);
4731     NameInfo.setNamedTypeInfo(TInfo);
4732     return NameInfo;
4733   }
4734 
4735   case UnqualifiedId::IK_ConstructorName: {
4736     TypeSourceInfo *TInfo;
4737     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4738     if (Ty.isNull())
4739       return DeclarationNameInfo();
4740     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4741                                               Context.getCanonicalType(Ty)));
4742     NameInfo.setLoc(Name.StartLocation);
4743     NameInfo.setNamedTypeInfo(TInfo);
4744     return NameInfo;
4745   }
4746 
4747   case UnqualifiedId::IK_ConstructorTemplateId: {
4748     // In well-formed code, we can only have a constructor
4749     // template-id that refers to the current context, so go there
4750     // to find the actual type being constructed.
4751     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4752     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4753       return DeclarationNameInfo();
4754 
4755     // Determine the type of the class being constructed.
4756     QualType CurClassType = Context.getTypeDeclType(CurClass);
4757 
4758     // FIXME: Check two things: that the template-id names the same type as
4759     // CurClassType, and that the template-id does not occur when the name
4760     // was qualified.
4761 
4762     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4763                                     Context.getCanonicalType(CurClassType)));
4764     NameInfo.setLoc(Name.StartLocation);
4765     // FIXME: should we retrieve TypeSourceInfo?
4766     NameInfo.setNamedTypeInfo(nullptr);
4767     return NameInfo;
4768   }
4769 
4770   case UnqualifiedId::IK_DestructorName: {
4771     TypeSourceInfo *TInfo;
4772     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4773     if (Ty.isNull())
4774       return DeclarationNameInfo();
4775     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4776                                               Context.getCanonicalType(Ty)));
4777     NameInfo.setLoc(Name.StartLocation);
4778     NameInfo.setNamedTypeInfo(TInfo);
4779     return NameInfo;
4780   }
4781 
4782   case UnqualifiedId::IK_TemplateId: {
4783     TemplateName TName = Name.TemplateId->Template.get();
4784     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4785     return Context.getNameForTemplate(TName, TNameLoc);
4786   }
4787 
4788   } // switch (Name.getKind())
4789 
4790   llvm_unreachable("Unknown name kind");
4791 }
4792 
4793 static QualType getCoreType(QualType Ty) {
4794   do {
4795     if (Ty->isPointerType() || Ty->isReferenceType())
4796       Ty = Ty->getPointeeType();
4797     else if (Ty->isArrayType())
4798       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4799     else
4800       return Ty.withoutLocalFastQualifiers();
4801   } while (true);
4802 }
4803 
4804 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4805 /// and Definition have "nearly" matching parameters. This heuristic is
4806 /// used to improve diagnostics in the case where an out-of-line function
4807 /// definition doesn't match any declaration within the class or namespace.
4808 /// Also sets Params to the list of indices to the parameters that differ
4809 /// between the declaration and the definition. If hasSimilarParameters
4810 /// returns true and Params is empty, then all of the parameters match.
4811 static bool hasSimilarParameters(ASTContext &Context,
4812                                      FunctionDecl *Declaration,
4813                                      FunctionDecl *Definition,
4814                                      SmallVectorImpl<unsigned> &Params) {
4815   Params.clear();
4816   if (Declaration->param_size() != Definition->param_size())
4817     return false;
4818   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4819     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4820     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4821 
4822     // The parameter types are identical
4823     if (Context.hasSameType(DefParamTy, DeclParamTy))
4824       continue;
4825 
4826     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4827     QualType DefParamBaseTy = getCoreType(DefParamTy);
4828     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4829     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4830 
4831     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4832         (DeclTyName && DeclTyName == DefTyName))
4833       Params.push_back(Idx);
4834     else  // The two parameters aren't even close
4835       return false;
4836   }
4837 
4838   return true;
4839 }
4840 
4841 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4842 /// declarator needs to be rebuilt in the current instantiation.
4843 /// Any bits of declarator which appear before the name are valid for
4844 /// consideration here.  That's specifically the type in the decl spec
4845 /// and the base type in any member-pointer chunks.
4846 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4847                                                     DeclarationName Name) {
4848   // The types we specifically need to rebuild are:
4849   //   - typenames, typeofs, and decltypes
4850   //   - types which will become injected class names
4851   // Of course, we also need to rebuild any type referencing such a
4852   // type.  It's safest to just say "dependent", but we call out a
4853   // few cases here.
4854 
4855   DeclSpec &DS = D.getMutableDeclSpec();
4856   switch (DS.getTypeSpecType()) {
4857   case DeclSpec::TST_typename:
4858   case DeclSpec::TST_typeofType:
4859   case DeclSpec::TST_underlyingType:
4860   case DeclSpec::TST_atomic: {
4861     // Grab the type from the parser.
4862     TypeSourceInfo *TSI = nullptr;
4863     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4864     if (T.isNull() || !T->isDependentType()) break;
4865 
4866     // Make sure there's a type source info.  This isn't really much
4867     // of a waste; most dependent types should have type source info
4868     // attached already.
4869     if (!TSI)
4870       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4871 
4872     // Rebuild the type in the current instantiation.
4873     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4874     if (!TSI) return true;
4875 
4876     // Store the new type back in the decl spec.
4877     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4878     DS.UpdateTypeRep(LocType);
4879     break;
4880   }
4881 
4882   case DeclSpec::TST_decltype:
4883   case DeclSpec::TST_typeofExpr: {
4884     Expr *E = DS.getRepAsExpr();
4885     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4886     if (Result.isInvalid()) return true;
4887     DS.UpdateExprRep(Result.get());
4888     break;
4889   }
4890 
4891   default:
4892     // Nothing to do for these decl specs.
4893     break;
4894   }
4895 
4896   // It doesn't matter what order we do this in.
4897   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4898     DeclaratorChunk &Chunk = D.getTypeObject(I);
4899 
4900     // The only type information in the declarator which can come
4901     // before the declaration name is the base type of a member
4902     // pointer.
4903     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4904       continue;
4905 
4906     // Rebuild the scope specifier in-place.
4907     CXXScopeSpec &SS = Chunk.Mem.Scope();
4908     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4909       return true;
4910   }
4911 
4912   return false;
4913 }
4914 
4915 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4916   D.setFunctionDefinitionKind(FDK_Declaration);
4917   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4918 
4919   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4920       Dcl && Dcl->getDeclContext()->isFileContext())
4921     Dcl->setTopLevelDeclInObjCContainer();
4922 
4923   if (getLangOpts().OpenCL)
4924     setCurrentOpenCLExtensionForDecl(Dcl);
4925 
4926   return Dcl;
4927 }
4928 
4929 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4930 ///   If T is the name of a class, then each of the following shall have a
4931 ///   name different from T:
4932 ///     - every static data member of class T;
4933 ///     - every member function of class T
4934 ///     - every member of class T that is itself a type;
4935 /// \returns true if the declaration name violates these rules.
4936 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4937                                    DeclarationNameInfo NameInfo) {
4938   DeclarationName Name = NameInfo.getName();
4939 
4940   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4941   while (Record && Record->isAnonymousStructOrUnion())
4942     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4943   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4944     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4945     return true;
4946   }
4947 
4948   return false;
4949 }
4950 
4951 /// \brief Diagnose a declaration whose declarator-id has the given
4952 /// nested-name-specifier.
4953 ///
4954 /// \param SS The nested-name-specifier of the declarator-id.
4955 ///
4956 /// \param DC The declaration context to which the nested-name-specifier
4957 /// resolves.
4958 ///
4959 /// \param Name The name of the entity being declared.
4960 ///
4961 /// \param Loc The location of the name of the entity being declared.
4962 ///
4963 /// \returns true if we cannot safely recover from this error, false otherwise.
4964 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4965                                         DeclarationName Name,
4966                                         SourceLocation Loc) {
4967   DeclContext *Cur = CurContext;
4968   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4969     Cur = Cur->getParent();
4970 
4971   // If the user provided a superfluous scope specifier that refers back to the
4972   // class in which the entity is already declared, diagnose and ignore it.
4973   //
4974   // class X {
4975   //   void X::f();
4976   // };
4977   //
4978   // Note, it was once ill-formed to give redundant qualification in all
4979   // contexts, but that rule was removed by DR482.
4980   if (Cur->Equals(DC)) {
4981     if (Cur->isRecord()) {
4982       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4983                                       : diag::err_member_extra_qualification)
4984         << Name << FixItHint::CreateRemoval(SS.getRange());
4985       SS.clear();
4986     } else {
4987       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4988     }
4989     return false;
4990   }
4991 
4992   // Check whether the qualifying scope encloses the scope of the original
4993   // declaration.
4994   if (!Cur->Encloses(DC)) {
4995     if (Cur->isRecord())
4996       Diag(Loc, diag::err_member_qualification)
4997         << Name << SS.getRange();
4998     else if (isa<TranslationUnitDecl>(DC))
4999       Diag(Loc, diag::err_invalid_declarator_global_scope)
5000         << Name << SS.getRange();
5001     else if (isa<FunctionDecl>(Cur))
5002       Diag(Loc, diag::err_invalid_declarator_in_function)
5003         << Name << SS.getRange();
5004     else if (isa<BlockDecl>(Cur))
5005       Diag(Loc, diag::err_invalid_declarator_in_block)
5006         << Name << SS.getRange();
5007     else
5008       Diag(Loc, diag::err_invalid_declarator_scope)
5009       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5010 
5011     return true;
5012   }
5013 
5014   if (Cur->isRecord()) {
5015     // Cannot qualify members within a class.
5016     Diag(Loc, diag::err_member_qualification)
5017       << Name << SS.getRange();
5018     SS.clear();
5019 
5020     // C++ constructors and destructors with incorrect scopes can break
5021     // our AST invariants by having the wrong underlying types. If
5022     // that's the case, then drop this declaration entirely.
5023     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5024          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5025         !Context.hasSameType(Name.getCXXNameType(),
5026                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5027       return true;
5028 
5029     return false;
5030   }
5031 
5032   // C++11 [dcl.meaning]p1:
5033   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5034   //   not begin with a decltype-specifer"
5035   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5036   while (SpecLoc.getPrefix())
5037     SpecLoc = SpecLoc.getPrefix();
5038   if (dyn_cast_or_null<DecltypeType>(
5039         SpecLoc.getNestedNameSpecifier()->getAsType()))
5040     Diag(Loc, diag::err_decltype_in_declarator)
5041       << SpecLoc.getTypeLoc().getSourceRange();
5042 
5043   return false;
5044 }
5045 
5046 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5047                                   MultiTemplateParamsArg TemplateParamLists) {
5048   // TODO: consider using NameInfo for diagnostic.
5049   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5050   DeclarationName Name = NameInfo.getName();
5051 
5052   // All of these full declarators require an identifier.  If it doesn't have
5053   // one, the ParsedFreeStandingDeclSpec action should be used.
5054   if (D.isDecompositionDeclarator()) {
5055     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5056   } else if (!Name) {
5057     if (!D.isInvalidType())  // Reject this if we think it is valid.
5058       Diag(D.getDeclSpec().getLocStart(),
5059            diag::err_declarator_need_ident)
5060         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5061     return nullptr;
5062   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5063     return nullptr;
5064 
5065   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5066   // we find one that is.
5067   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5068          (S->getFlags() & Scope::TemplateParamScope) != 0)
5069     S = S->getParent();
5070 
5071   DeclContext *DC = CurContext;
5072   if (D.getCXXScopeSpec().isInvalid())
5073     D.setInvalidType();
5074   else if (D.getCXXScopeSpec().isSet()) {
5075     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5076                                         UPPC_DeclarationQualifier))
5077       return nullptr;
5078 
5079     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5080     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5081     if (!DC || isa<EnumDecl>(DC)) {
5082       // If we could not compute the declaration context, it's because the
5083       // declaration context is dependent but does not refer to a class,
5084       // class template, or class template partial specialization. Complain
5085       // and return early, to avoid the coming semantic disaster.
5086       Diag(D.getIdentifierLoc(),
5087            diag::err_template_qualified_declarator_no_match)
5088         << D.getCXXScopeSpec().getScopeRep()
5089         << D.getCXXScopeSpec().getRange();
5090       return nullptr;
5091     }
5092     bool IsDependentContext = DC->isDependentContext();
5093 
5094     if (!IsDependentContext &&
5095         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5096       return nullptr;
5097 
5098     // If a class is incomplete, do not parse entities inside it.
5099     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5100       Diag(D.getIdentifierLoc(),
5101            diag::err_member_def_undefined_record)
5102         << Name << DC << D.getCXXScopeSpec().getRange();
5103       return nullptr;
5104     }
5105     if (!D.getDeclSpec().isFriendSpecified()) {
5106       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5107                                       Name, D.getIdentifierLoc())) {
5108         if (DC->isRecord())
5109           return nullptr;
5110 
5111         D.setInvalidType();
5112       }
5113     }
5114 
5115     // Check whether we need to rebuild the type of the given
5116     // declaration in the current instantiation.
5117     if (EnteringContext && IsDependentContext &&
5118         TemplateParamLists.size() != 0) {
5119       ContextRAII SavedContext(*this, DC);
5120       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5121         D.setInvalidType();
5122     }
5123   }
5124 
5125   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5126   QualType R = TInfo->getType();
5127 
5128   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5129     // If this is a typedef, we'll end up spewing multiple diagnostics.
5130     // Just return early; it's safer. If this is a function, let the
5131     // "constructor cannot have a return type" diagnostic handle it.
5132     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5133       return nullptr;
5134 
5135   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5136                                       UPPC_DeclarationType))
5137     D.setInvalidType();
5138 
5139   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5140                         ForRedeclaration);
5141 
5142   // See if this is a redefinition of a variable in the same scope.
5143   if (!D.getCXXScopeSpec().isSet()) {
5144     bool IsLinkageLookup = false;
5145     bool CreateBuiltins = false;
5146 
5147     // If the declaration we're planning to build will be a function
5148     // or object with linkage, then look for another declaration with
5149     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5150     //
5151     // If the declaration we're planning to build will be declared with
5152     // external linkage in the translation unit, create any builtin with
5153     // the same name.
5154     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5155       /* Do nothing*/;
5156     else if (CurContext->isFunctionOrMethod() &&
5157              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5158               R->isFunctionType())) {
5159       IsLinkageLookup = true;
5160       CreateBuiltins =
5161           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5162     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5163                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5164       CreateBuiltins = true;
5165 
5166     if (IsLinkageLookup)
5167       Previous.clear(LookupRedeclarationWithLinkage);
5168 
5169     LookupName(Previous, S, CreateBuiltins);
5170   } else { // Something like "int foo::x;"
5171     LookupQualifiedName(Previous, DC);
5172 
5173     // C++ [dcl.meaning]p1:
5174     //   When the declarator-id is qualified, the declaration shall refer to a
5175     //  previously declared member of the class or namespace to which the
5176     //  qualifier refers (or, in the case of a namespace, of an element of the
5177     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5178     //  thereof; [...]
5179     //
5180     // Note that we already checked the context above, and that we do not have
5181     // enough information to make sure that Previous contains the declaration
5182     // we want to match. For example, given:
5183     //
5184     //   class X {
5185     //     void f();
5186     //     void f(float);
5187     //   };
5188     //
5189     //   void X::f(int) { } // ill-formed
5190     //
5191     // In this case, Previous will point to the overload set
5192     // containing the two f's declared in X, but neither of them
5193     // matches.
5194 
5195     // C++ [dcl.meaning]p1:
5196     //   [...] the member shall not merely have been introduced by a
5197     //   using-declaration in the scope of the class or namespace nominated by
5198     //   the nested-name-specifier of the declarator-id.
5199     RemoveUsingDecls(Previous);
5200   }
5201 
5202   if (Previous.isSingleResult() &&
5203       Previous.getFoundDecl()->isTemplateParameter()) {
5204     // Maybe we will complain about the shadowed template parameter.
5205     if (!D.isInvalidType())
5206       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5207                                       Previous.getFoundDecl());
5208 
5209     // Just pretend that we didn't see the previous declaration.
5210     Previous.clear();
5211   }
5212 
5213   // In C++, the previous declaration we find might be a tag type
5214   // (class or enum). In this case, the new declaration will hide the
5215   // tag type. Note that this does does not apply if we're declaring a
5216   // typedef (C++ [dcl.typedef]p4).
5217   if (Previous.isSingleTagDecl() &&
5218       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5219     Previous.clear();
5220 
5221   // Check that there are no default arguments other than in the parameters
5222   // of a function declaration (C++ only).
5223   if (getLangOpts().CPlusPlus)
5224     CheckExtraCXXDefaultArguments(D);
5225 
5226   if (D.getDeclSpec().isConceptSpecified()) {
5227     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5228     // applied only to the definition of a function template or variable
5229     // template, declared in namespace scope
5230     if (!TemplateParamLists.size()) {
5231       Diag(D.getDeclSpec().getConceptSpecLoc(),
5232            diag:: err_concept_wrong_decl_kind);
5233       return nullptr;
5234     }
5235 
5236     if (!DC->getRedeclContext()->isFileContext()) {
5237       Diag(D.getIdentifierLoc(),
5238            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5239       return nullptr;
5240     }
5241   }
5242 
5243   NamedDecl *New;
5244 
5245   bool AddToScope = true;
5246   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5247     if (TemplateParamLists.size()) {
5248       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5249       return nullptr;
5250     }
5251 
5252     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5253   } else if (R->isFunctionType()) {
5254     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5255                                   TemplateParamLists,
5256                                   AddToScope);
5257   } else {
5258     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5259                                   AddToScope);
5260   }
5261 
5262   if (!New)
5263     return nullptr;
5264 
5265   // If this has an identifier and is not a function template specialization,
5266   // add it to the scope stack.
5267   if (New->getDeclName() && AddToScope) {
5268     // Only make a locally-scoped extern declaration visible if it is the first
5269     // declaration of this entity. Qualified lookup for such an entity should
5270     // only find this declaration if there is no visible declaration of it.
5271     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5272     PushOnScopeChains(New, S, AddToContext);
5273     if (!AddToContext)
5274       CurContext->addHiddenDecl(New);
5275   }
5276 
5277   if (isInOpenMPDeclareTargetContext())
5278     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5279 
5280   return New;
5281 }
5282 
5283 /// Helper method to turn variable array types into constant array
5284 /// types in certain situations which would otherwise be errors (for
5285 /// GCC compatibility).
5286 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5287                                                     ASTContext &Context,
5288                                                     bool &SizeIsNegative,
5289                                                     llvm::APSInt &Oversized) {
5290   // This method tries to turn a variable array into a constant
5291   // array even when the size isn't an ICE.  This is necessary
5292   // for compatibility with code that depends on gcc's buggy
5293   // constant expression folding, like struct {char x[(int)(char*)2];}
5294   SizeIsNegative = false;
5295   Oversized = 0;
5296 
5297   if (T->isDependentType())
5298     return QualType();
5299 
5300   QualifierCollector Qs;
5301   const Type *Ty = Qs.strip(T);
5302 
5303   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5304     QualType Pointee = PTy->getPointeeType();
5305     QualType FixedType =
5306         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5307                                             Oversized);
5308     if (FixedType.isNull()) return FixedType;
5309     FixedType = Context.getPointerType(FixedType);
5310     return Qs.apply(Context, FixedType);
5311   }
5312   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5313     QualType Inner = PTy->getInnerType();
5314     QualType FixedType =
5315         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5316                                             Oversized);
5317     if (FixedType.isNull()) return FixedType;
5318     FixedType = Context.getParenType(FixedType);
5319     return Qs.apply(Context, FixedType);
5320   }
5321 
5322   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5323   if (!VLATy)
5324     return QualType();
5325   // FIXME: We should probably handle this case
5326   if (VLATy->getElementType()->isVariablyModifiedType())
5327     return QualType();
5328 
5329   llvm::APSInt Res;
5330   if (!VLATy->getSizeExpr() ||
5331       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5332     return QualType();
5333 
5334   // Check whether the array size is negative.
5335   if (Res.isSigned() && Res.isNegative()) {
5336     SizeIsNegative = true;
5337     return QualType();
5338   }
5339 
5340   // Check whether the array is too large to be addressed.
5341   unsigned ActiveSizeBits
5342     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5343                                               Res);
5344   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5345     Oversized = Res;
5346     return QualType();
5347   }
5348 
5349   return Context.getConstantArrayType(VLATy->getElementType(),
5350                                       Res, ArrayType::Normal, 0);
5351 }
5352 
5353 static void
5354 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5355   SrcTL = SrcTL.getUnqualifiedLoc();
5356   DstTL = DstTL.getUnqualifiedLoc();
5357   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5358     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5359     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5360                                       DstPTL.getPointeeLoc());
5361     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5362     return;
5363   }
5364   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5365     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5366     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5367                                       DstPTL.getInnerLoc());
5368     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5369     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5370     return;
5371   }
5372   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5373   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5374   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5375   TypeLoc DstElemTL = DstATL.getElementLoc();
5376   DstElemTL.initializeFullCopy(SrcElemTL);
5377   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5378   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5379   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5380 }
5381 
5382 /// Helper method to turn variable array types into constant array
5383 /// types in certain situations which would otherwise be errors (for
5384 /// GCC compatibility).
5385 static TypeSourceInfo*
5386 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5387                                               ASTContext &Context,
5388                                               bool &SizeIsNegative,
5389                                               llvm::APSInt &Oversized) {
5390   QualType FixedTy
5391     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5392                                           SizeIsNegative, Oversized);
5393   if (FixedTy.isNull())
5394     return nullptr;
5395   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5396   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5397                                     FixedTInfo->getTypeLoc());
5398   return FixedTInfo;
5399 }
5400 
5401 /// \brief Register the given locally-scoped extern "C" declaration so
5402 /// that it can be found later for redeclarations. We include any extern "C"
5403 /// declaration that is not visible in the translation unit here, not just
5404 /// function-scope declarations.
5405 void
5406 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5407   if (!getLangOpts().CPlusPlus &&
5408       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5409     // Don't need to track declarations in the TU in C.
5410     return;
5411 
5412   // Note that we have a locally-scoped external with this name.
5413   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5414 }
5415 
5416 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5417   // FIXME: We can have multiple results via __attribute__((overloadable)).
5418   auto Result = Context.getExternCContextDecl()->lookup(Name);
5419   return Result.empty() ? nullptr : *Result.begin();
5420 }
5421 
5422 /// \brief Diagnose function specifiers on a declaration of an identifier that
5423 /// does not identify a function.
5424 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5425   // FIXME: We should probably indicate the identifier in question to avoid
5426   // confusion for constructs like "virtual int a(), b;"
5427   if (DS.isVirtualSpecified())
5428     Diag(DS.getVirtualSpecLoc(),
5429          diag::err_virtual_non_function);
5430 
5431   if (DS.isExplicitSpecified())
5432     Diag(DS.getExplicitSpecLoc(),
5433          diag::err_explicit_non_function);
5434 
5435   if (DS.isNoreturnSpecified())
5436     Diag(DS.getNoreturnSpecLoc(),
5437          diag::err_noreturn_non_function);
5438 }
5439 
5440 NamedDecl*
5441 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5442                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5443   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5444   if (D.getCXXScopeSpec().isSet()) {
5445     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5446       << D.getCXXScopeSpec().getRange();
5447     D.setInvalidType();
5448     // Pretend we didn't see the scope specifier.
5449     DC = CurContext;
5450     Previous.clear();
5451   }
5452 
5453   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5454 
5455   if (D.getDeclSpec().isInlineSpecified())
5456     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5457         << getLangOpts().CPlusPlus1z;
5458   if (D.getDeclSpec().isConstexprSpecified())
5459     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5460       << 1;
5461   if (D.getDeclSpec().isConceptSpecified())
5462     Diag(D.getDeclSpec().getConceptSpecLoc(),
5463          diag::err_concept_wrong_decl_kind);
5464 
5465   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5466     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5467       << D.getName().getSourceRange();
5468     return nullptr;
5469   }
5470 
5471   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5472   if (!NewTD) return nullptr;
5473 
5474   // Handle attributes prior to checking for duplicates in MergeVarDecl
5475   ProcessDeclAttributes(S, NewTD, D);
5476 
5477   CheckTypedefForVariablyModifiedType(S, NewTD);
5478 
5479   bool Redeclaration = D.isRedeclaration();
5480   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5481   D.setRedeclaration(Redeclaration);
5482   return ND;
5483 }
5484 
5485 void
5486 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5487   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5488   // then it shall have block scope.
5489   // Note that variably modified types must be fixed before merging the decl so
5490   // that redeclarations will match.
5491   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5492   QualType T = TInfo->getType();
5493   if (T->isVariablyModifiedType()) {
5494     getCurFunction()->setHasBranchProtectedScope();
5495 
5496     if (S->getFnParent() == nullptr) {
5497       bool SizeIsNegative;
5498       llvm::APSInt Oversized;
5499       TypeSourceInfo *FixedTInfo =
5500         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5501                                                       SizeIsNegative,
5502                                                       Oversized);
5503       if (FixedTInfo) {
5504         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5505         NewTD->setTypeSourceInfo(FixedTInfo);
5506       } else {
5507         if (SizeIsNegative)
5508           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5509         else if (T->isVariableArrayType())
5510           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5511         else if (Oversized.getBoolValue())
5512           Diag(NewTD->getLocation(), diag::err_array_too_large)
5513             << Oversized.toString(10);
5514         else
5515           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5516         NewTD->setInvalidDecl();
5517       }
5518     }
5519   }
5520 }
5521 
5522 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5523 /// declares a typedef-name, either using the 'typedef' type specifier or via
5524 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5525 NamedDecl*
5526 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5527                            LookupResult &Previous, bool &Redeclaration) {
5528   // Merge the decl with the existing one if appropriate. If the decl is
5529   // in an outer scope, it isn't the same thing.
5530   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5531                        /*AllowInlineNamespace*/false);
5532   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5533   if (!Previous.empty()) {
5534     Redeclaration = true;
5535     MergeTypedefNameDecl(S, NewTD, Previous);
5536   }
5537 
5538   // If this is the C FILE type, notify the AST context.
5539   if (IdentifierInfo *II = NewTD->getIdentifier())
5540     if (!NewTD->isInvalidDecl() &&
5541         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5542       if (II->isStr("FILE"))
5543         Context.setFILEDecl(NewTD);
5544       else if (II->isStr("jmp_buf"))
5545         Context.setjmp_bufDecl(NewTD);
5546       else if (II->isStr("sigjmp_buf"))
5547         Context.setsigjmp_bufDecl(NewTD);
5548       else if (II->isStr("ucontext_t"))
5549         Context.setucontext_tDecl(NewTD);
5550     }
5551 
5552   return NewTD;
5553 }
5554 
5555 /// \brief Determines whether the given declaration is an out-of-scope
5556 /// previous declaration.
5557 ///
5558 /// This routine should be invoked when name lookup has found a
5559 /// previous declaration (PrevDecl) that is not in the scope where a
5560 /// new declaration by the same name is being introduced. If the new
5561 /// declaration occurs in a local scope, previous declarations with
5562 /// linkage may still be considered previous declarations (C99
5563 /// 6.2.2p4-5, C++ [basic.link]p6).
5564 ///
5565 /// \param PrevDecl the previous declaration found by name
5566 /// lookup
5567 ///
5568 /// \param DC the context in which the new declaration is being
5569 /// declared.
5570 ///
5571 /// \returns true if PrevDecl is an out-of-scope previous declaration
5572 /// for a new delcaration with the same name.
5573 static bool
5574 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5575                                 ASTContext &Context) {
5576   if (!PrevDecl)
5577     return false;
5578 
5579   if (!PrevDecl->hasLinkage())
5580     return false;
5581 
5582   if (Context.getLangOpts().CPlusPlus) {
5583     // C++ [basic.link]p6:
5584     //   If there is a visible declaration of an entity with linkage
5585     //   having the same name and type, ignoring entities declared
5586     //   outside the innermost enclosing namespace scope, the block
5587     //   scope declaration declares that same entity and receives the
5588     //   linkage of the previous declaration.
5589     DeclContext *OuterContext = DC->getRedeclContext();
5590     if (!OuterContext->isFunctionOrMethod())
5591       // This rule only applies to block-scope declarations.
5592       return false;
5593 
5594     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5595     if (PrevOuterContext->isRecord())
5596       // We found a member function: ignore it.
5597       return false;
5598 
5599     // Find the innermost enclosing namespace for the new and
5600     // previous declarations.
5601     OuterContext = OuterContext->getEnclosingNamespaceContext();
5602     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5603 
5604     // The previous declaration is in a different namespace, so it
5605     // isn't the same function.
5606     if (!OuterContext->Equals(PrevOuterContext))
5607       return false;
5608   }
5609 
5610   return true;
5611 }
5612 
5613 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5614   CXXScopeSpec &SS = D.getCXXScopeSpec();
5615   if (!SS.isSet()) return;
5616   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5617 }
5618 
5619 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5620   QualType type = decl->getType();
5621   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5622   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5623     // Various kinds of declaration aren't allowed to be __autoreleasing.
5624     unsigned kind = -1U;
5625     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5626       if (var->hasAttr<BlocksAttr>())
5627         kind = 0; // __block
5628       else if (!var->hasLocalStorage())
5629         kind = 1; // global
5630     } else if (isa<ObjCIvarDecl>(decl)) {
5631       kind = 3; // ivar
5632     } else if (isa<FieldDecl>(decl)) {
5633       kind = 2; // field
5634     }
5635 
5636     if (kind != -1U) {
5637       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5638         << kind;
5639     }
5640   } else if (lifetime == Qualifiers::OCL_None) {
5641     // Try to infer lifetime.
5642     if (!type->isObjCLifetimeType())
5643       return false;
5644 
5645     lifetime = type->getObjCARCImplicitLifetime();
5646     type = Context.getLifetimeQualifiedType(type, lifetime);
5647     decl->setType(type);
5648   }
5649 
5650   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5651     // Thread-local variables cannot have lifetime.
5652     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5653         var->getTLSKind()) {
5654       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5655         << var->getType();
5656       return true;
5657     }
5658   }
5659 
5660   return false;
5661 }
5662 
5663 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5664   // Ensure that an auto decl is deduced otherwise the checks below might cache
5665   // the wrong linkage.
5666   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5667 
5668   // 'weak' only applies to declarations with external linkage.
5669   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5670     if (!ND.isExternallyVisible()) {
5671       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5672       ND.dropAttr<WeakAttr>();
5673     }
5674   }
5675   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5676     if (ND.isExternallyVisible()) {
5677       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5678       ND.dropAttr<WeakRefAttr>();
5679       ND.dropAttr<AliasAttr>();
5680     }
5681   }
5682 
5683   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5684     if (VD->hasInit()) {
5685       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5686         assert(VD->isThisDeclarationADefinition() &&
5687                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5688         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5689         VD->dropAttr<AliasAttr>();
5690       }
5691     }
5692   }
5693 
5694   // 'selectany' only applies to externally visible variable declarations.
5695   // It does not apply to functions.
5696   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5697     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5698       S.Diag(Attr->getLocation(),
5699              diag::err_attribute_selectany_non_extern_data);
5700       ND.dropAttr<SelectAnyAttr>();
5701     }
5702   }
5703 
5704   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5705     // dll attributes require external linkage. Static locals may have external
5706     // linkage but still cannot be explicitly imported or exported.
5707     auto *VD = dyn_cast<VarDecl>(&ND);
5708     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5709       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5710         << &ND << Attr;
5711       ND.setInvalidDecl();
5712     }
5713   }
5714 
5715   // Virtual functions cannot be marked as 'notail'.
5716   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5717     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5718       if (MD->isVirtual()) {
5719         S.Diag(ND.getLocation(),
5720                diag::err_invalid_attribute_on_virtual_function)
5721             << Attr;
5722         ND.dropAttr<NotTailCalledAttr>();
5723       }
5724 }
5725 
5726 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5727                                            NamedDecl *NewDecl,
5728                                            bool IsSpecialization,
5729                                            bool IsDefinition) {
5730   if (OldDecl->isInvalidDecl())
5731     return;
5732 
5733   bool IsTemplate = false;
5734   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5735     OldDecl = OldTD->getTemplatedDecl();
5736     IsTemplate = true;
5737     if (!IsSpecialization)
5738       IsDefinition = false;
5739   }
5740   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5741     NewDecl = NewTD->getTemplatedDecl();
5742     IsTemplate = true;
5743   }
5744 
5745   if (!OldDecl || !NewDecl)
5746     return;
5747 
5748   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5749   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5750   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5751   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5752 
5753   // dllimport and dllexport are inheritable attributes so we have to exclude
5754   // inherited attribute instances.
5755   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5756                     (NewExportAttr && !NewExportAttr->isInherited());
5757 
5758   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5759   // the only exception being explicit specializations.
5760   // Implicitly generated declarations are also excluded for now because there
5761   // is no other way to switch these to use dllimport or dllexport.
5762   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5763 
5764   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5765     // Allow with a warning for free functions and global variables.
5766     bool JustWarn = false;
5767     if (!OldDecl->isCXXClassMember()) {
5768       auto *VD = dyn_cast<VarDecl>(OldDecl);
5769       if (VD && !VD->getDescribedVarTemplate())
5770         JustWarn = true;
5771       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5772       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5773         JustWarn = true;
5774     }
5775 
5776     // We cannot change a declaration that's been used because IR has already
5777     // been emitted. Dllimported functions will still work though (modulo
5778     // address equality) as they can use the thunk.
5779     if (OldDecl->isUsed())
5780       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5781         JustWarn = false;
5782 
5783     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5784                                : diag::err_attribute_dll_redeclaration;
5785     S.Diag(NewDecl->getLocation(), DiagID)
5786         << NewDecl
5787         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5788     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5789     if (!JustWarn) {
5790       NewDecl->setInvalidDecl();
5791       return;
5792     }
5793   }
5794 
5795   // A redeclaration is not allowed to drop a dllimport attribute, the only
5796   // exceptions being inline function definitions (except for function
5797   // templates), local extern declarations, qualified friend declarations or
5798   // special MSVC extension: in the last case, the declaration is treated as if
5799   // it were marked dllexport.
5800   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5801   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5802   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5803     // Ignore static data because out-of-line definitions are diagnosed
5804     // separately.
5805     IsStaticDataMember = VD->isStaticDataMember();
5806     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5807                    VarDecl::DeclarationOnly;
5808   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5809     IsInline = FD->isInlined();
5810     IsQualifiedFriend = FD->getQualifier() &&
5811                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5812   }
5813 
5814   if (OldImportAttr && !HasNewAttr &&
5815       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5816       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5817     if (IsMicrosoft && IsDefinition) {
5818       S.Diag(NewDecl->getLocation(),
5819              diag::warn_redeclaration_without_import_attribute)
5820           << NewDecl;
5821       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5822       NewDecl->dropAttr<DLLImportAttr>();
5823       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5824           NewImportAttr->getRange(), S.Context,
5825           NewImportAttr->getSpellingListIndex()));
5826     } else {
5827       S.Diag(NewDecl->getLocation(),
5828              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5829           << NewDecl << OldImportAttr;
5830       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5831       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5832       OldDecl->dropAttr<DLLImportAttr>();
5833       NewDecl->dropAttr<DLLImportAttr>();
5834     }
5835   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5836     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5837     OldDecl->dropAttr<DLLImportAttr>();
5838     NewDecl->dropAttr<DLLImportAttr>();
5839     S.Diag(NewDecl->getLocation(),
5840            diag::warn_dllimport_dropped_from_inline_function)
5841         << NewDecl << OldImportAttr;
5842   }
5843 }
5844 
5845 /// Given that we are within the definition of the given function,
5846 /// will that definition behave like C99's 'inline', where the
5847 /// definition is discarded except for optimization purposes?
5848 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5849   // Try to avoid calling GetGVALinkageForFunction.
5850 
5851   // All cases of this require the 'inline' keyword.
5852   if (!FD->isInlined()) return false;
5853 
5854   // This is only possible in C++ with the gnu_inline attribute.
5855   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5856     return false;
5857 
5858   // Okay, go ahead and call the relatively-more-expensive function.
5859   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5860 }
5861 
5862 /// Determine whether a variable is extern "C" prior to attaching
5863 /// an initializer. We can't just call isExternC() here, because that
5864 /// will also compute and cache whether the declaration is externally
5865 /// visible, which might change when we attach the initializer.
5866 ///
5867 /// This can only be used if the declaration is known to not be a
5868 /// redeclaration of an internal linkage declaration.
5869 ///
5870 /// For instance:
5871 ///
5872 ///   auto x = []{};
5873 ///
5874 /// Attaching the initializer here makes this declaration not externally
5875 /// visible, because its type has internal linkage.
5876 ///
5877 /// FIXME: This is a hack.
5878 template<typename T>
5879 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5880   if (S.getLangOpts().CPlusPlus) {
5881     // In C++, the overloadable attribute negates the effects of extern "C".
5882     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5883       return false;
5884 
5885     // So do CUDA's host/device attributes.
5886     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5887                                  D->template hasAttr<CUDAHostAttr>()))
5888       return false;
5889   }
5890   return D->isExternC();
5891 }
5892 
5893 static bool shouldConsiderLinkage(const VarDecl *VD) {
5894   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5895   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5896     return VD->hasExternalStorage();
5897   if (DC->isFileContext())
5898     return true;
5899   if (DC->isRecord())
5900     return false;
5901   llvm_unreachable("Unexpected context");
5902 }
5903 
5904 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5905   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5906   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5907       isa<OMPDeclareReductionDecl>(DC))
5908     return true;
5909   if (DC->isRecord())
5910     return false;
5911   llvm_unreachable("Unexpected context");
5912 }
5913 
5914 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5915                           AttributeList::Kind Kind) {
5916   for (const AttributeList *L = AttrList; L; L = L->getNext())
5917     if (L->getKind() == Kind)
5918       return true;
5919   return false;
5920 }
5921 
5922 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5923                           AttributeList::Kind Kind) {
5924   // Check decl attributes on the DeclSpec.
5925   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5926     return true;
5927 
5928   // Walk the declarator structure, checking decl attributes that were in a type
5929   // position to the decl itself.
5930   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5931     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5932       return true;
5933   }
5934 
5935   // Finally, check attributes on the decl itself.
5936   return hasParsedAttr(S, PD.getAttributes(), Kind);
5937 }
5938 
5939 /// Adjust the \c DeclContext for a function or variable that might be a
5940 /// function-local external declaration.
5941 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5942   if (!DC->isFunctionOrMethod())
5943     return false;
5944 
5945   // If this is a local extern function or variable declared within a function
5946   // template, don't add it into the enclosing namespace scope until it is
5947   // instantiated; it might have a dependent type right now.
5948   if (DC->isDependentContext())
5949     return true;
5950 
5951   // C++11 [basic.link]p7:
5952   //   When a block scope declaration of an entity with linkage is not found to
5953   //   refer to some other declaration, then that entity is a member of the
5954   //   innermost enclosing namespace.
5955   //
5956   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5957   // semantically-enclosing namespace, not a lexically-enclosing one.
5958   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5959     DC = DC->getParent();
5960   return true;
5961 }
5962 
5963 /// \brief Returns true if given declaration has external C language linkage.
5964 static bool isDeclExternC(const Decl *D) {
5965   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5966     return FD->isExternC();
5967   if (const auto *VD = dyn_cast<VarDecl>(D))
5968     return VD->isExternC();
5969 
5970   llvm_unreachable("Unknown type of decl!");
5971 }
5972 
5973 NamedDecl *Sema::ActOnVariableDeclarator(
5974     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5975     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5976     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5977   QualType R = TInfo->getType();
5978   DeclarationName Name = GetNameForDeclarator(D).getName();
5979 
5980   IdentifierInfo *II = Name.getAsIdentifierInfo();
5981 
5982   if (D.isDecompositionDeclarator()) {
5983     AddToScope = false;
5984     // Take the name of the first declarator as our name for diagnostic
5985     // purposes.
5986     auto &Decomp = D.getDecompositionDeclarator();
5987     if (!Decomp.bindings().empty()) {
5988       II = Decomp.bindings()[0].Name;
5989       Name = II;
5990     }
5991   } else if (!II) {
5992     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5993       << Name;
5994     return nullptr;
5995   }
5996 
5997   if (getLangOpts().OpenCL) {
5998     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5999     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6000     // argument.
6001     if (R->isImageType() || R->isPipeType()) {
6002       Diag(D.getIdentifierLoc(),
6003            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6004           << R;
6005       D.setInvalidType();
6006       return nullptr;
6007     }
6008 
6009     // OpenCL v1.2 s6.9.r:
6010     // The event type cannot be used to declare a program scope variable.
6011     // OpenCL v2.0 s6.9.q:
6012     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6013     if (NULL == S->getParent()) {
6014       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6015         Diag(D.getIdentifierLoc(),
6016              diag::err_invalid_type_for_program_scope_var) << R;
6017         D.setInvalidType();
6018         return nullptr;
6019       }
6020     }
6021 
6022     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6023     QualType NR = R;
6024     while (NR->isPointerType()) {
6025       if (NR->isFunctionPointerType()) {
6026         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6027         D.setInvalidType();
6028         break;
6029       }
6030       NR = NR->getPointeeType();
6031     }
6032 
6033     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6034       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6035       // half array type (unless the cl_khr_fp16 extension is enabled).
6036       if (Context.getBaseElementType(R)->isHalfType()) {
6037         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6038         D.setInvalidType();
6039       }
6040     }
6041 
6042     // OpenCL v1.2 s6.9.b p4:
6043     // The sampler type cannot be used with the __local and __global address
6044     // space qualifiers.
6045     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6046       R.getAddressSpace() == LangAS::opencl_global)) {
6047       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6048     }
6049 
6050     // OpenCL v1.2 s6.9.r:
6051     // The event type cannot be used with the __local, __constant and __global
6052     // address space qualifiers.
6053     if (R->isEventT()) {
6054       if (R.getAddressSpace()) {
6055         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6056         D.setInvalidType();
6057       }
6058     }
6059   }
6060 
6061   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6062   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6063 
6064   // dllimport globals without explicit storage class are treated as extern. We
6065   // have to change the storage class this early to get the right DeclContext.
6066   if (SC == SC_None && !DC->isRecord() &&
6067       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6068       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6069     SC = SC_Extern;
6070 
6071   DeclContext *OriginalDC = DC;
6072   bool IsLocalExternDecl = SC == SC_Extern &&
6073                            adjustContextForLocalExternDecl(DC);
6074 
6075   if (SCSpec == DeclSpec::SCS_mutable) {
6076     // mutable can only appear on non-static class members, so it's always
6077     // an error here
6078     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6079     D.setInvalidType();
6080     SC = SC_None;
6081   }
6082 
6083   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6084       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6085                               D.getDeclSpec().getStorageClassSpecLoc())) {
6086     // In C++11, the 'register' storage class specifier is deprecated.
6087     // Suppress the warning in system macros, it's used in macros in some
6088     // popular C system headers, such as in glibc's htonl() macro.
6089     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6090          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6091                                    : diag::warn_deprecated_register)
6092       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6093   }
6094 
6095   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6096 
6097   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6098     // C99 6.9p2: The storage-class specifiers auto and register shall not
6099     // appear in the declaration specifiers in an external declaration.
6100     // Global Register+Asm is a GNU extension we support.
6101     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6102       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6103       D.setInvalidType();
6104     }
6105   }
6106 
6107   bool IsExplicitSpecialization = false;
6108   bool IsVariableTemplateSpecialization = false;
6109   bool IsPartialSpecialization = false;
6110   bool IsVariableTemplate = false;
6111   VarDecl *NewVD = nullptr;
6112   VarTemplateDecl *NewTemplate = nullptr;
6113   TemplateParameterList *TemplateParams = nullptr;
6114   if (!getLangOpts().CPlusPlus) {
6115     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6116                             D.getIdentifierLoc(), II,
6117                             R, TInfo, SC);
6118 
6119     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6120       ParsingInitForAutoVars.insert(NewVD);
6121 
6122     if (D.isInvalidType())
6123       NewVD->setInvalidDecl();
6124   } else {
6125     bool Invalid = false;
6126 
6127     if (DC->isRecord() && !CurContext->isRecord()) {
6128       // This is an out-of-line definition of a static data member.
6129       switch (SC) {
6130       case SC_None:
6131         break;
6132       case SC_Static:
6133         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6134              diag::err_static_out_of_line)
6135           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6136         break;
6137       case SC_Auto:
6138       case SC_Register:
6139       case SC_Extern:
6140         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6141         // to names of variables declared in a block or to function parameters.
6142         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6143         // of class members
6144 
6145         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6146              diag::err_storage_class_for_static_member)
6147           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6148         break;
6149       case SC_PrivateExtern:
6150         llvm_unreachable("C storage class in c++!");
6151       }
6152     }
6153 
6154     if (SC == SC_Static && CurContext->isRecord()) {
6155       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6156         if (RD->isLocalClass())
6157           Diag(D.getIdentifierLoc(),
6158                diag::err_static_data_member_not_allowed_in_local_class)
6159             << Name << RD->getDeclName();
6160 
6161         // C++98 [class.union]p1: If a union contains a static data member,
6162         // the program is ill-formed. C++11 drops this restriction.
6163         if (RD->isUnion())
6164           Diag(D.getIdentifierLoc(),
6165                getLangOpts().CPlusPlus11
6166                  ? diag::warn_cxx98_compat_static_data_member_in_union
6167                  : diag::ext_static_data_member_in_union) << Name;
6168         // We conservatively disallow static data members in anonymous structs.
6169         else if (!RD->getDeclName())
6170           Diag(D.getIdentifierLoc(),
6171                diag::err_static_data_member_not_allowed_in_anon_struct)
6172             << Name << RD->isUnion();
6173       }
6174     }
6175 
6176     // Match up the template parameter lists with the scope specifier, then
6177     // determine whether we have a template or a template specialization.
6178     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6179         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6180         D.getCXXScopeSpec(),
6181         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6182             ? D.getName().TemplateId
6183             : nullptr,
6184         TemplateParamLists,
6185         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6186 
6187     if (TemplateParams) {
6188       if (!TemplateParams->size() &&
6189           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6190         // There is an extraneous 'template<>' for this variable. Complain
6191         // about it, but allow the declaration of the variable.
6192         Diag(TemplateParams->getTemplateLoc(),
6193              diag::err_template_variable_noparams)
6194           << II
6195           << SourceRange(TemplateParams->getTemplateLoc(),
6196                          TemplateParams->getRAngleLoc());
6197         TemplateParams = nullptr;
6198       } else {
6199         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6200           // This is an explicit specialization or a partial specialization.
6201           // FIXME: Check that we can declare a specialization here.
6202           IsVariableTemplateSpecialization = true;
6203           IsPartialSpecialization = TemplateParams->size() > 0;
6204         } else { // if (TemplateParams->size() > 0)
6205           // This is a template declaration.
6206           IsVariableTemplate = true;
6207 
6208           // Check that we can declare a template here.
6209           if (CheckTemplateDeclScope(S, TemplateParams))
6210             return nullptr;
6211 
6212           // Only C++1y supports variable templates (N3651).
6213           Diag(D.getIdentifierLoc(),
6214                getLangOpts().CPlusPlus14
6215                    ? diag::warn_cxx11_compat_variable_template
6216                    : diag::ext_variable_template);
6217         }
6218       }
6219     } else {
6220       assert(
6221           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6222           "should have a 'template<>' for this decl");
6223     }
6224 
6225     if (IsVariableTemplateSpecialization) {
6226       SourceLocation TemplateKWLoc =
6227           TemplateParamLists.size() > 0
6228               ? TemplateParamLists[0]->getTemplateLoc()
6229               : SourceLocation();
6230       DeclResult Res = ActOnVarTemplateSpecialization(
6231           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6232           IsPartialSpecialization);
6233       if (Res.isInvalid())
6234         return nullptr;
6235       NewVD = cast<VarDecl>(Res.get());
6236       AddToScope = false;
6237     } else if (D.isDecompositionDeclarator()) {
6238       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6239                                         D.getIdentifierLoc(), R, TInfo, SC,
6240                                         Bindings);
6241     } else
6242       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6243                               D.getIdentifierLoc(), II, R, TInfo, SC);
6244 
6245     // If this is supposed to be a variable template, create it as such.
6246     if (IsVariableTemplate) {
6247       NewTemplate =
6248           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6249                                   TemplateParams, NewVD);
6250       NewVD->setDescribedVarTemplate(NewTemplate);
6251     }
6252 
6253     // If this decl has an auto type in need of deduction, make a note of the
6254     // Decl so we can diagnose uses of it in its own initializer.
6255     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6256       ParsingInitForAutoVars.insert(NewVD);
6257 
6258     if (D.isInvalidType() || Invalid) {
6259       NewVD->setInvalidDecl();
6260       if (NewTemplate)
6261         NewTemplate->setInvalidDecl();
6262     }
6263 
6264     SetNestedNameSpecifier(NewVD, D);
6265 
6266     // If we have any template parameter lists that don't directly belong to
6267     // the variable (matching the scope specifier), store them.
6268     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6269     if (TemplateParamLists.size() > VDTemplateParamLists)
6270       NewVD->setTemplateParameterListsInfo(
6271           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6272 
6273     if (D.getDeclSpec().isConstexprSpecified()) {
6274       NewVD->setConstexpr(true);
6275       // C++1z [dcl.spec.constexpr]p1:
6276       //   A static data member declared with the constexpr specifier is
6277       //   implicitly an inline variable.
6278       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6279         NewVD->setImplicitlyInline();
6280     }
6281 
6282     if (D.getDeclSpec().isConceptSpecified()) {
6283       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6284         VTD->setConcept();
6285 
6286       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6287       // be declared with the thread_local, inline, friend, or constexpr
6288       // specifiers, [...]
6289       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6290         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6291              diag::err_concept_decl_invalid_specifiers)
6292             << 0 << 0;
6293         NewVD->setInvalidDecl(true);
6294       }
6295 
6296       if (D.getDeclSpec().isConstexprSpecified()) {
6297         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6298              diag::err_concept_decl_invalid_specifiers)
6299             << 0 << 3;
6300         NewVD->setInvalidDecl(true);
6301       }
6302 
6303       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6304       // applied only to the definition of a function template or variable
6305       // template, declared in namespace scope.
6306       if (IsVariableTemplateSpecialization) {
6307         Diag(D.getDeclSpec().getConceptSpecLoc(),
6308              diag::err_concept_specified_specialization)
6309             << (IsPartialSpecialization ? 2 : 1);
6310       }
6311 
6312       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6313       // following restrictions:
6314       // - The declared type shall have the type bool.
6315       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6316           !NewVD->isInvalidDecl()) {
6317         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6318         NewVD->setInvalidDecl(true);
6319       }
6320     }
6321   }
6322 
6323   if (D.getDeclSpec().isInlineSpecified()) {
6324     if (!getLangOpts().CPlusPlus) {
6325       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6326           << 0;
6327     } else if (CurContext->isFunctionOrMethod()) {
6328       // 'inline' is not allowed on block scope variable declaration.
6329       Diag(D.getDeclSpec().getInlineSpecLoc(),
6330            diag::err_inline_declaration_block_scope) << Name
6331         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6332     } else {
6333       Diag(D.getDeclSpec().getInlineSpecLoc(),
6334            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6335                                      : diag::ext_inline_variable);
6336       NewVD->setInlineSpecified();
6337     }
6338   }
6339 
6340   // Set the lexical context. If the declarator has a C++ scope specifier, the
6341   // lexical context will be different from the semantic context.
6342   NewVD->setLexicalDeclContext(CurContext);
6343   if (NewTemplate)
6344     NewTemplate->setLexicalDeclContext(CurContext);
6345 
6346   if (IsLocalExternDecl) {
6347     if (D.isDecompositionDeclarator())
6348       for (auto *B : Bindings)
6349         B->setLocalExternDecl();
6350     else
6351       NewVD->setLocalExternDecl();
6352   }
6353 
6354   bool EmitTLSUnsupportedError = false;
6355   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6356     // C++11 [dcl.stc]p4:
6357     //   When thread_local is applied to a variable of block scope the
6358     //   storage-class-specifier static is implied if it does not appear
6359     //   explicitly.
6360     // Core issue: 'static' is not implied if the variable is declared
6361     //   'extern'.
6362     if (NewVD->hasLocalStorage() &&
6363         (SCSpec != DeclSpec::SCS_unspecified ||
6364          TSCS != DeclSpec::TSCS_thread_local ||
6365          !DC->isFunctionOrMethod()))
6366       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6367            diag::err_thread_non_global)
6368         << DeclSpec::getSpecifierName(TSCS);
6369     else if (!Context.getTargetInfo().isTLSSupported()) {
6370       if (getLangOpts().CUDA) {
6371         // Postpone error emission until we've collected attributes required to
6372         // figure out whether it's a host or device variable and whether the
6373         // error should be ignored.
6374         EmitTLSUnsupportedError = true;
6375         // We still need to mark the variable as TLS so it shows up in AST with
6376         // proper storage class for other tools to use even if we're not going
6377         // to emit any code for it.
6378         NewVD->setTSCSpec(TSCS);
6379       } else
6380         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6381              diag::err_thread_unsupported);
6382     } else
6383       NewVD->setTSCSpec(TSCS);
6384   }
6385 
6386   // C99 6.7.4p3
6387   //   An inline definition of a function with external linkage shall
6388   //   not contain a definition of a modifiable object with static or
6389   //   thread storage duration...
6390   // We only apply this when the function is required to be defined
6391   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6392   // that a local variable with thread storage duration still has to
6393   // be marked 'static'.  Also note that it's possible to get these
6394   // semantics in C++ using __attribute__((gnu_inline)).
6395   if (SC == SC_Static && S->getFnParent() != nullptr &&
6396       !NewVD->getType().isConstQualified()) {
6397     FunctionDecl *CurFD = getCurFunctionDecl();
6398     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6399       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6400            diag::warn_static_local_in_extern_inline);
6401       MaybeSuggestAddingStaticToDecl(CurFD);
6402     }
6403   }
6404 
6405   if (D.getDeclSpec().isModulePrivateSpecified()) {
6406     if (IsVariableTemplateSpecialization)
6407       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6408           << (IsPartialSpecialization ? 1 : 0)
6409           << FixItHint::CreateRemoval(
6410                  D.getDeclSpec().getModulePrivateSpecLoc());
6411     else if (IsExplicitSpecialization)
6412       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6413         << 2
6414         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6415     else if (NewVD->hasLocalStorage())
6416       Diag(NewVD->getLocation(), diag::err_module_private_local)
6417         << 0 << NewVD->getDeclName()
6418         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6419         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6420     else {
6421       NewVD->setModulePrivate();
6422       if (NewTemplate)
6423         NewTemplate->setModulePrivate();
6424       for (auto *B : Bindings)
6425         B->setModulePrivate();
6426     }
6427   }
6428 
6429   // Handle attributes prior to checking for duplicates in MergeVarDecl
6430   ProcessDeclAttributes(S, NewVD, D);
6431 
6432   if (getLangOpts().CUDA) {
6433     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6434       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6435            diag::err_thread_unsupported);
6436     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6437     // storage [duration]."
6438     if (SC == SC_None && S->getFnParent() != nullptr &&
6439         (NewVD->hasAttr<CUDASharedAttr>() ||
6440          NewVD->hasAttr<CUDAConstantAttr>())) {
6441       NewVD->setStorageClass(SC_Static);
6442     }
6443   }
6444 
6445   // Ensure that dllimport globals without explicit storage class are treated as
6446   // extern. The storage class is set above using parsed attributes. Now we can
6447   // check the VarDecl itself.
6448   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6449          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6450          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6451 
6452   // In auto-retain/release, infer strong retension for variables of
6453   // retainable type.
6454   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6455     NewVD->setInvalidDecl();
6456 
6457   // Handle GNU asm-label extension (encoded as an attribute).
6458   if (Expr *E = (Expr*)D.getAsmLabel()) {
6459     // The parser guarantees this is a string.
6460     StringLiteral *SE = cast<StringLiteral>(E);
6461     StringRef Label = SE->getString();
6462     if (S->getFnParent() != nullptr) {
6463       switch (SC) {
6464       case SC_None:
6465       case SC_Auto:
6466         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6467         break;
6468       case SC_Register:
6469         // Local Named register
6470         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6471             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6472           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6473         break;
6474       case SC_Static:
6475       case SC_Extern:
6476       case SC_PrivateExtern:
6477         break;
6478       }
6479     } else if (SC == SC_Register) {
6480       // Global Named register
6481       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6482         const auto &TI = Context.getTargetInfo();
6483         bool HasSizeMismatch;
6484 
6485         if (!TI.isValidGCCRegisterName(Label))
6486           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6487         else if (!TI.validateGlobalRegisterVariable(Label,
6488                                                     Context.getTypeSize(R),
6489                                                     HasSizeMismatch))
6490           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6491         else if (HasSizeMismatch)
6492           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6493       }
6494 
6495       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6496         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6497         NewVD->setInvalidDecl(true);
6498       }
6499     }
6500 
6501     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6502                                                 Context, Label, 0));
6503   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6504     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6505       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6506     if (I != ExtnameUndeclaredIdentifiers.end()) {
6507       if (isDeclExternC(NewVD)) {
6508         NewVD->addAttr(I->second);
6509         ExtnameUndeclaredIdentifiers.erase(I);
6510       } else
6511         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6512             << /*Variable*/1 << NewVD;
6513     }
6514   }
6515 
6516   // Find the shadowed declaration before filtering for scope.
6517   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6518                                 ? getShadowedDeclaration(NewVD, Previous)
6519                                 : nullptr;
6520 
6521   // Don't consider existing declarations that are in a different
6522   // scope and are out-of-semantic-context declarations (if the new
6523   // declaration has linkage).
6524   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6525                        D.getCXXScopeSpec().isNotEmpty() ||
6526                        IsExplicitSpecialization ||
6527                        IsVariableTemplateSpecialization);
6528 
6529   // Check whether the previous declaration is in the same block scope. This
6530   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6531   if (getLangOpts().CPlusPlus &&
6532       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6533     NewVD->setPreviousDeclInSameBlockScope(
6534         Previous.isSingleResult() && !Previous.isShadowed() &&
6535         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6536 
6537   if (!getLangOpts().CPlusPlus) {
6538     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6539   } else {
6540     // If this is an explicit specialization of a static data member, check it.
6541     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6542         CheckMemberSpecialization(NewVD, Previous))
6543       NewVD->setInvalidDecl();
6544 
6545     // Merge the decl with the existing one if appropriate.
6546     if (!Previous.empty()) {
6547       if (Previous.isSingleResult() &&
6548           isa<FieldDecl>(Previous.getFoundDecl()) &&
6549           D.getCXXScopeSpec().isSet()) {
6550         // The user tried to define a non-static data member
6551         // out-of-line (C++ [dcl.meaning]p1).
6552         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6553           << D.getCXXScopeSpec().getRange();
6554         Previous.clear();
6555         NewVD->setInvalidDecl();
6556       }
6557     } else if (D.getCXXScopeSpec().isSet()) {
6558       // No previous declaration in the qualifying scope.
6559       Diag(D.getIdentifierLoc(), diag::err_no_member)
6560         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6561         << D.getCXXScopeSpec().getRange();
6562       NewVD->setInvalidDecl();
6563     }
6564 
6565     if (!IsVariableTemplateSpecialization)
6566       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6567 
6568     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6569     // an explicit specialization (14.8.3) or a partial specialization of a
6570     // concept definition.
6571     if (IsVariableTemplateSpecialization &&
6572         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6573         Previous.isSingleResult()) {
6574       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6575       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6576         if (VarTmpl->isConcept()) {
6577           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6578               << 1                            /*variable*/
6579               << (IsPartialSpecialization ? 2 /*partially specialized*/
6580                                           : 1 /*explicitly specialized*/);
6581           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6582           NewVD->setInvalidDecl();
6583         }
6584       }
6585     }
6586 
6587     if (NewTemplate) {
6588       VarTemplateDecl *PrevVarTemplate =
6589           NewVD->getPreviousDecl()
6590               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6591               : nullptr;
6592 
6593       // Check the template parameter list of this declaration, possibly
6594       // merging in the template parameter list from the previous variable
6595       // template declaration.
6596       if (CheckTemplateParameterList(
6597               TemplateParams,
6598               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6599                               : nullptr,
6600               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6601                DC->isDependentContext())
6602                   ? TPC_ClassTemplateMember
6603                   : TPC_VarTemplate))
6604         NewVD->setInvalidDecl();
6605 
6606       // If we are providing an explicit specialization of a static variable
6607       // template, make a note of that.
6608       if (PrevVarTemplate &&
6609           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6610         PrevVarTemplate->setMemberSpecialization();
6611     }
6612   }
6613 
6614   // Diagnose shadowed variables iff this isn't a redeclaration.
6615   if (ShadowedDecl && !D.isRedeclaration())
6616     CheckShadow(NewVD, ShadowedDecl, Previous);
6617 
6618   ProcessPragmaWeak(S, NewVD);
6619 
6620   // If this is the first declaration of an extern C variable, update
6621   // the map of such variables.
6622   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6623       isIncompleteDeclExternC(*this, NewVD))
6624     RegisterLocallyScopedExternCDecl(NewVD, S);
6625 
6626   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6627     Decl *ManglingContextDecl;
6628     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6629             NewVD->getDeclContext(), ManglingContextDecl)) {
6630       Context.setManglingNumber(
6631           NewVD, MCtx->getManglingNumber(
6632                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6633       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6634     }
6635   }
6636 
6637   // Special handling of variable named 'main'.
6638   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6639       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6640       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6641 
6642     // C++ [basic.start.main]p3
6643     // A program that declares a variable main at global scope is ill-formed.
6644     if (getLangOpts().CPlusPlus)
6645       Diag(D.getLocStart(), diag::err_main_global_variable);
6646 
6647     // In C, and external-linkage variable named main results in undefined
6648     // behavior.
6649     else if (NewVD->hasExternalFormalLinkage())
6650       Diag(D.getLocStart(), diag::warn_main_redefined);
6651   }
6652 
6653   if (D.isRedeclaration() && !Previous.empty()) {
6654     checkDLLAttributeRedeclaration(
6655         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6656         IsExplicitSpecialization, D.isFunctionDefinition());
6657   }
6658 
6659   if (NewTemplate) {
6660     if (NewVD->isInvalidDecl())
6661       NewTemplate->setInvalidDecl();
6662     ActOnDocumentableDecl(NewTemplate);
6663     return NewTemplate;
6664   }
6665 
6666   return NewVD;
6667 }
6668 
6669 /// Enum describing the %select options in diag::warn_decl_shadow.
6670 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6671 
6672 /// Determine what kind of declaration we're shadowing.
6673 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6674                                                 const DeclContext *OldDC) {
6675   if (isa<RecordDecl>(OldDC))
6676     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6677   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6678 }
6679 
6680 /// Return the location of the capture if the given lambda captures the given
6681 /// variable \p VD, or an invalid source location otherwise.
6682 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6683                                          const VarDecl *VD) {
6684   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6685     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6686       return Capture.getLocation();
6687   }
6688   return SourceLocation();
6689 }
6690 
6691 /// \brief Return the declaration shadowed by the given variable \p D, or null
6692 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6693 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6694                                         const LookupResult &R) {
6695   // Return if warning is ignored.
6696   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6697     return nullptr;
6698 
6699   // Don't diagnose declarations at file scope.
6700   if (D->hasGlobalStorage())
6701     return nullptr;
6702 
6703   // Only diagnose if we're shadowing an unambiguous field or variable.
6704   if (R.getResultKind() != LookupResult::Found)
6705     return nullptr;
6706 
6707   NamedDecl *ShadowedDecl = R.getFoundDecl();
6708   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6709              ? ShadowedDecl
6710              : nullptr;
6711 }
6712 
6713 /// \brief Diagnose variable or built-in function shadowing.  Implements
6714 /// -Wshadow.
6715 ///
6716 /// This method is called whenever a VarDecl is added to a "useful"
6717 /// scope.
6718 ///
6719 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6720 /// \param R the lookup of the name
6721 ///
6722 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl,
6723                        const LookupResult &R) {
6724   DeclContext *NewDC = D->getDeclContext();
6725 
6726   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6727     // Fields are not shadowed by variables in C++ static methods.
6728     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6729       if (MD->isStatic())
6730         return;
6731 
6732     // Fields shadowed by constructor parameters are a special case. Usually
6733     // the constructor initializes the field with the parameter.
6734     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6735       // Remember that this was shadowed so we can either warn about its
6736       // modification or its existence depending on warning settings.
6737       D = D->getCanonicalDecl();
6738       ShadowingDecls.insert({D, FD});
6739       return;
6740     }
6741   }
6742 
6743   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6744     if (shadowedVar->isExternC()) {
6745       // For shadowing external vars, make sure that we point to the global
6746       // declaration, not a locally scoped extern declaration.
6747       for (auto I : shadowedVar->redecls())
6748         if (I->isFileVarDecl()) {
6749           ShadowedDecl = I;
6750           break;
6751         }
6752     }
6753 
6754   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6755 
6756   unsigned WarningDiag = diag::warn_decl_shadow;
6757   SourceLocation CaptureLoc;
6758   if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
6759     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6760       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6761         if (RD->getLambdaCaptureDefault() == LCD_None) {
6762           // Try to avoid warnings for lambdas with an explicit capture list.
6763           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6764           // Warn only when the lambda captures the shadowed decl explicitly.
6765           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6766           if (CaptureLoc.isInvalid())
6767             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6768         } else {
6769           // Remember that this was shadowed so we can avoid the warning if the
6770           // shadowed decl isn't captured and the warning settings allow it.
6771           cast<LambdaScopeInfo>(getCurFunction())
6772               ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
6773           return;
6774         }
6775       }
6776     }
6777   }
6778 
6779   // Only warn about certain kinds of shadowing for class members.
6780   if (NewDC && NewDC->isRecord()) {
6781     // In particular, don't warn about shadowing non-class members.
6782     if (!OldDC->isRecord())
6783       return;
6784 
6785     // TODO: should we warn about static data members shadowing
6786     // static data members from base classes?
6787 
6788     // TODO: don't diagnose for inaccessible shadowed members.
6789     // This is hard to do perfectly because we might friend the
6790     // shadowing context, but that's just a false negative.
6791   }
6792 
6793 
6794   DeclarationName Name = R.getLookupName();
6795 
6796   // Emit warning and note.
6797   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6798     return;
6799   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6800   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6801   if (!CaptureLoc.isInvalid())
6802     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6803         << Name << /*explicitly*/ 1;
6804   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6805 }
6806 
6807 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6808 /// when these variables are captured by the lambda.
6809 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6810   for (const auto &Shadow : LSI->ShadowingDecls) {
6811     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6812     // Try to avoid the warning when the shadowed decl isn't captured.
6813     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6814     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6815     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6816                                        ? diag::warn_decl_shadow_uncaptured_local
6817                                        : diag::warn_decl_shadow)
6818         << Shadow.VD->getDeclName()
6819         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6820     if (!CaptureLoc.isInvalid())
6821       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6822           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6823     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6824   }
6825 }
6826 
6827 /// \brief Check -Wshadow without the advantage of a previous lookup.
6828 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6829   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6830     return;
6831 
6832   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6833                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6834   LookupName(R, S);
6835   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6836     CheckShadow(D, ShadowedDecl, R);
6837 }
6838 
6839 /// Check if 'E', which is an expression that is about to be modified, refers
6840 /// to a constructor parameter that shadows a field.
6841 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6842   // Quickly ignore expressions that can't be shadowing ctor parameters.
6843   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6844     return;
6845   E = E->IgnoreParenImpCasts();
6846   auto *DRE = dyn_cast<DeclRefExpr>(E);
6847   if (!DRE)
6848     return;
6849   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6850   auto I = ShadowingDecls.find(D);
6851   if (I == ShadowingDecls.end())
6852     return;
6853   const NamedDecl *ShadowedDecl = I->second;
6854   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6855   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6856   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6857   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6858 
6859   // Avoid issuing multiple warnings about the same decl.
6860   ShadowingDecls.erase(I);
6861 }
6862 
6863 /// Check for conflict between this global or extern "C" declaration and
6864 /// previous global or extern "C" declarations. This is only used in C++.
6865 template<typename T>
6866 static bool checkGlobalOrExternCConflict(
6867     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6868   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6869   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6870 
6871   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6872     // The common case: this global doesn't conflict with any extern "C"
6873     // declaration.
6874     return false;
6875   }
6876 
6877   if (Prev) {
6878     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6879       // Both the old and new declarations have C language linkage. This is a
6880       // redeclaration.
6881       Previous.clear();
6882       Previous.addDecl(Prev);
6883       return true;
6884     }
6885 
6886     // This is a global, non-extern "C" declaration, and there is a previous
6887     // non-global extern "C" declaration. Diagnose if this is a variable
6888     // declaration.
6889     if (!isa<VarDecl>(ND))
6890       return false;
6891   } else {
6892     // The declaration is extern "C". Check for any declaration in the
6893     // translation unit which might conflict.
6894     if (IsGlobal) {
6895       // We have already performed the lookup into the translation unit.
6896       IsGlobal = false;
6897       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6898            I != E; ++I) {
6899         if (isa<VarDecl>(*I)) {
6900           Prev = *I;
6901           break;
6902         }
6903       }
6904     } else {
6905       DeclContext::lookup_result R =
6906           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6907       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6908            I != E; ++I) {
6909         if (isa<VarDecl>(*I)) {
6910           Prev = *I;
6911           break;
6912         }
6913         // FIXME: If we have any other entity with this name in global scope,
6914         // the declaration is ill-formed, but that is a defect: it breaks the
6915         // 'stat' hack, for instance. Only variables can have mangled name
6916         // clashes with extern "C" declarations, so only they deserve a
6917         // diagnostic.
6918       }
6919     }
6920 
6921     if (!Prev)
6922       return false;
6923   }
6924 
6925   // Use the first declaration's location to ensure we point at something which
6926   // is lexically inside an extern "C" linkage-spec.
6927   assert(Prev && "should have found a previous declaration to diagnose");
6928   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6929     Prev = FD->getFirstDecl();
6930   else
6931     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6932 
6933   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6934     << IsGlobal << ND;
6935   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6936     << IsGlobal;
6937   return false;
6938 }
6939 
6940 /// Apply special rules for handling extern "C" declarations. Returns \c true
6941 /// if we have found that this is a redeclaration of some prior entity.
6942 ///
6943 /// Per C++ [dcl.link]p6:
6944 ///   Two declarations [for a function or variable] with C language linkage
6945 ///   with the same name that appear in different scopes refer to the same
6946 ///   [entity]. An entity with C language linkage shall not be declared with
6947 ///   the same name as an entity in global scope.
6948 template<typename T>
6949 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6950                                                   LookupResult &Previous) {
6951   if (!S.getLangOpts().CPlusPlus) {
6952     // In C, when declaring a global variable, look for a corresponding 'extern'
6953     // variable declared in function scope. We don't need this in C++, because
6954     // we find local extern decls in the surrounding file-scope DeclContext.
6955     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6956       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6957         Previous.clear();
6958         Previous.addDecl(Prev);
6959         return true;
6960       }
6961     }
6962     return false;
6963   }
6964 
6965   // A declaration in the translation unit can conflict with an extern "C"
6966   // declaration.
6967   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6968     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6969 
6970   // An extern "C" declaration can conflict with a declaration in the
6971   // translation unit or can be a redeclaration of an extern "C" declaration
6972   // in another scope.
6973   if (isIncompleteDeclExternC(S,ND))
6974     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6975 
6976   // Neither global nor extern "C": nothing to do.
6977   return false;
6978 }
6979 
6980 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6981   // If the decl is already known invalid, don't check it.
6982   if (NewVD->isInvalidDecl())
6983     return;
6984 
6985   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6986   QualType T = TInfo->getType();
6987 
6988   // Defer checking an 'auto' type until its initializer is attached.
6989   if (T->isUndeducedType())
6990     return;
6991 
6992   if (NewVD->hasAttrs())
6993     CheckAlignasUnderalignment(NewVD);
6994 
6995   if (T->isObjCObjectType()) {
6996     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6997       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6998     T = Context.getObjCObjectPointerType(T);
6999     NewVD->setType(T);
7000   }
7001 
7002   // Emit an error if an address space was applied to decl with local storage.
7003   // This includes arrays of objects with address space qualifiers, but not
7004   // automatic variables that point to other address spaces.
7005   // ISO/IEC TR 18037 S5.1.2
7006   if (!getLangOpts().OpenCL
7007       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7008     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7009     NewVD->setInvalidDecl();
7010     return;
7011   }
7012 
7013   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7014   // scope.
7015   if (getLangOpts().OpenCLVersion == 120 &&
7016       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7017       NewVD->isStaticLocal()) {
7018     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7019     NewVD->setInvalidDecl();
7020     return;
7021   }
7022 
7023   if (getLangOpts().OpenCL) {
7024     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7025     if (NewVD->hasAttr<BlocksAttr>()) {
7026       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7027       return;
7028     }
7029 
7030     if (T->isBlockPointerType()) {
7031       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7032       // can't use 'extern' storage class.
7033       if (!T.isConstQualified()) {
7034         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7035             << 0 /*const*/;
7036         NewVD->setInvalidDecl();
7037         return;
7038       }
7039       if (NewVD->hasExternalStorage()) {
7040         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7041         NewVD->setInvalidDecl();
7042         return;
7043       }
7044     }
7045     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7046     // __constant address space.
7047     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7048     // variables inside a function can also be declared in the global
7049     // address space.
7050     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7051         NewVD->hasExternalStorage()) {
7052       if (!T->isSamplerT() &&
7053           !(T.getAddressSpace() == LangAS::opencl_constant ||
7054             (T.getAddressSpace() == LangAS::opencl_global &&
7055              getLangOpts().OpenCLVersion == 200))) {
7056         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7057         if (getLangOpts().OpenCLVersion == 200)
7058           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7059               << Scope << "global or constant";
7060         else
7061           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7062               << Scope << "constant";
7063         NewVD->setInvalidDecl();
7064         return;
7065       }
7066     } else {
7067       if (T.getAddressSpace() == LangAS::opencl_global) {
7068         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7069             << 1 /*is any function*/ << "global";
7070         NewVD->setInvalidDecl();
7071         return;
7072       }
7073       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7074       // in functions.
7075       if (T.getAddressSpace() == LangAS::opencl_constant ||
7076           T.getAddressSpace() == LangAS::opencl_local) {
7077         FunctionDecl *FD = getCurFunctionDecl();
7078         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7079           if (T.getAddressSpace() == LangAS::opencl_constant)
7080             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7081                 << 0 /*non-kernel only*/ << "constant";
7082           else
7083             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7084                 << 0 /*non-kernel only*/ << "local";
7085           NewVD->setInvalidDecl();
7086           return;
7087         }
7088       }
7089     }
7090   }
7091 
7092   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7093       && !NewVD->hasAttr<BlocksAttr>()) {
7094     if (getLangOpts().getGC() != LangOptions::NonGC)
7095       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7096     else {
7097       assert(!getLangOpts().ObjCAutoRefCount);
7098       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7099     }
7100   }
7101 
7102   bool isVM = T->isVariablyModifiedType();
7103   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7104       NewVD->hasAttr<BlocksAttr>())
7105     getCurFunction()->setHasBranchProtectedScope();
7106 
7107   if ((isVM && NewVD->hasLinkage()) ||
7108       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7109     bool SizeIsNegative;
7110     llvm::APSInt Oversized;
7111     TypeSourceInfo *FixedTInfo =
7112       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7113                                                     SizeIsNegative, Oversized);
7114     if (!FixedTInfo && T->isVariableArrayType()) {
7115       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7116       // FIXME: This won't give the correct result for
7117       // int a[10][n];
7118       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7119 
7120       if (NewVD->isFileVarDecl())
7121         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7122         << SizeRange;
7123       else if (NewVD->isStaticLocal())
7124         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7125         << SizeRange;
7126       else
7127         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7128         << SizeRange;
7129       NewVD->setInvalidDecl();
7130       return;
7131     }
7132 
7133     if (!FixedTInfo) {
7134       if (NewVD->isFileVarDecl())
7135         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7136       else
7137         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7138       NewVD->setInvalidDecl();
7139       return;
7140     }
7141 
7142     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7143     NewVD->setType(FixedTInfo->getType());
7144     NewVD->setTypeSourceInfo(FixedTInfo);
7145   }
7146 
7147   if (T->isVoidType()) {
7148     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7149     //                    of objects and functions.
7150     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7151       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7152         << T;
7153       NewVD->setInvalidDecl();
7154       return;
7155     }
7156   }
7157 
7158   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7159     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7160     NewVD->setInvalidDecl();
7161     return;
7162   }
7163 
7164   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7165     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7166     NewVD->setInvalidDecl();
7167     return;
7168   }
7169 
7170   if (NewVD->isConstexpr() && !T->isDependentType() &&
7171       RequireLiteralType(NewVD->getLocation(), T,
7172                          diag::err_constexpr_var_non_literal)) {
7173     NewVD->setInvalidDecl();
7174     return;
7175   }
7176 }
7177 
7178 /// \brief Perform semantic checking on a newly-created variable
7179 /// declaration.
7180 ///
7181 /// This routine performs all of the type-checking required for a
7182 /// variable declaration once it has been built. It is used both to
7183 /// check variables after they have been parsed and their declarators
7184 /// have been translated into a declaration, and to check variables
7185 /// that have been instantiated from a template.
7186 ///
7187 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7188 ///
7189 /// Returns true if the variable declaration is a redeclaration.
7190 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7191   CheckVariableDeclarationType(NewVD);
7192 
7193   // If the decl is already known invalid, don't check it.
7194   if (NewVD->isInvalidDecl())
7195     return false;
7196 
7197   // If we did not find anything by this name, look for a non-visible
7198   // extern "C" declaration with the same name.
7199   if (Previous.empty() &&
7200       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7201     Previous.setShadowed();
7202 
7203   if (!Previous.empty()) {
7204     MergeVarDecl(NewVD, Previous);
7205     return true;
7206   }
7207   return false;
7208 }
7209 
7210 namespace {
7211 struct FindOverriddenMethod {
7212   Sema *S;
7213   CXXMethodDecl *Method;
7214 
7215   /// Member lookup function that determines whether a given C++
7216   /// method overrides a method in a base class, to be used with
7217   /// CXXRecordDecl::lookupInBases().
7218   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7219     RecordDecl *BaseRecord =
7220         Specifier->getType()->getAs<RecordType>()->getDecl();
7221 
7222     DeclarationName Name = Method->getDeclName();
7223 
7224     // FIXME: Do we care about other names here too?
7225     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7226       // We really want to find the base class destructor here.
7227       QualType T = S->Context.getTypeDeclType(BaseRecord);
7228       CanQualType CT = S->Context.getCanonicalType(T);
7229 
7230       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7231     }
7232 
7233     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7234          Path.Decls = Path.Decls.slice(1)) {
7235       NamedDecl *D = Path.Decls.front();
7236       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7237         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7238           return true;
7239       }
7240     }
7241 
7242     return false;
7243   }
7244 };
7245 
7246 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7247 } // end anonymous namespace
7248 
7249 /// \brief Report an error regarding overriding, along with any relevant
7250 /// overriden methods.
7251 ///
7252 /// \param DiagID the primary error to report.
7253 /// \param MD the overriding method.
7254 /// \param OEK which overrides to include as notes.
7255 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7256                             OverrideErrorKind OEK = OEK_All) {
7257   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7258   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7259                                       E = MD->end_overridden_methods();
7260        I != E; ++I) {
7261     // This check (& the OEK parameter) could be replaced by a predicate, but
7262     // without lambdas that would be overkill. This is still nicer than writing
7263     // out the diag loop 3 times.
7264     if ((OEK == OEK_All) ||
7265         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7266         (OEK == OEK_Deleted && (*I)->isDeleted()))
7267       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7268   }
7269 }
7270 
7271 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7272 /// and if so, check that it's a valid override and remember it.
7273 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7274   // Look for methods in base classes that this method might override.
7275   CXXBasePaths Paths;
7276   FindOverriddenMethod FOM;
7277   FOM.Method = MD;
7278   FOM.S = this;
7279   bool hasDeletedOverridenMethods = false;
7280   bool hasNonDeletedOverridenMethods = false;
7281   bool AddedAny = false;
7282   if (DC->lookupInBases(FOM, Paths)) {
7283     for (auto *I : Paths.found_decls()) {
7284       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7285         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7286         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7287             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7288             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7289             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7290           hasDeletedOverridenMethods |= OldMD->isDeleted();
7291           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7292           AddedAny = true;
7293         }
7294       }
7295     }
7296   }
7297 
7298   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7299     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7300   }
7301   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7302     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7303   }
7304 
7305   return AddedAny;
7306 }
7307 
7308 namespace {
7309   // Struct for holding all of the extra arguments needed by
7310   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7311   struct ActOnFDArgs {
7312     Scope *S;
7313     Declarator &D;
7314     MultiTemplateParamsArg TemplateParamLists;
7315     bool AddToScope;
7316   };
7317 } // end anonymous namespace
7318 
7319 namespace {
7320 
7321 // Callback to only accept typo corrections that have a non-zero edit distance.
7322 // Also only accept corrections that have the same parent decl.
7323 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7324  public:
7325   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7326                             CXXRecordDecl *Parent)
7327       : Context(Context), OriginalFD(TypoFD),
7328         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7329 
7330   bool ValidateCandidate(const TypoCorrection &candidate) override {
7331     if (candidate.getEditDistance() == 0)
7332       return false;
7333 
7334     SmallVector<unsigned, 1> MismatchedParams;
7335     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7336                                           CDeclEnd = candidate.end();
7337          CDecl != CDeclEnd; ++CDecl) {
7338       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7339 
7340       if (FD && !FD->hasBody() &&
7341           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7342         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7343           CXXRecordDecl *Parent = MD->getParent();
7344           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7345             return true;
7346         } else if (!ExpectedParent) {
7347           return true;
7348         }
7349       }
7350     }
7351 
7352     return false;
7353   }
7354 
7355  private:
7356   ASTContext &Context;
7357   FunctionDecl *OriginalFD;
7358   CXXRecordDecl *ExpectedParent;
7359 };
7360 
7361 } // end anonymous namespace
7362 
7363 /// \brief Generate diagnostics for an invalid function redeclaration.
7364 ///
7365 /// This routine handles generating the diagnostic messages for an invalid
7366 /// function redeclaration, including finding possible similar declarations
7367 /// or performing typo correction if there are no previous declarations with
7368 /// the same name.
7369 ///
7370 /// Returns a NamedDecl iff typo correction was performed and substituting in
7371 /// the new declaration name does not cause new errors.
7372 static NamedDecl *DiagnoseInvalidRedeclaration(
7373     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7374     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7375   DeclarationName Name = NewFD->getDeclName();
7376   DeclContext *NewDC = NewFD->getDeclContext();
7377   SmallVector<unsigned, 1> MismatchedParams;
7378   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7379   TypoCorrection Correction;
7380   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7381   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7382                                    : diag::err_member_decl_does_not_match;
7383   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7384                     IsLocalFriend ? Sema::LookupLocalFriendName
7385                                   : Sema::LookupOrdinaryName,
7386                     Sema::ForRedeclaration);
7387 
7388   NewFD->setInvalidDecl();
7389   if (IsLocalFriend)
7390     SemaRef.LookupName(Prev, S);
7391   else
7392     SemaRef.LookupQualifiedName(Prev, NewDC);
7393   assert(!Prev.isAmbiguous() &&
7394          "Cannot have an ambiguity in previous-declaration lookup");
7395   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7396   if (!Prev.empty()) {
7397     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7398          Func != FuncEnd; ++Func) {
7399       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7400       if (FD &&
7401           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7402         // Add 1 to the index so that 0 can mean the mismatch didn't
7403         // involve a parameter
7404         unsigned ParamNum =
7405             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7406         NearMatches.push_back(std::make_pair(FD, ParamNum));
7407       }
7408     }
7409   // If the qualified name lookup yielded nothing, try typo correction
7410   } else if ((Correction = SemaRef.CorrectTypo(
7411                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7412                   &ExtraArgs.D.getCXXScopeSpec(),
7413                   llvm::make_unique<DifferentNameValidatorCCC>(
7414                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7415                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7416     // Set up everything for the call to ActOnFunctionDeclarator
7417     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7418                               ExtraArgs.D.getIdentifierLoc());
7419     Previous.clear();
7420     Previous.setLookupName(Correction.getCorrection());
7421     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7422                                     CDeclEnd = Correction.end();
7423          CDecl != CDeclEnd; ++CDecl) {
7424       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7425       if (FD && !FD->hasBody() &&
7426           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7427         Previous.addDecl(FD);
7428       }
7429     }
7430     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7431 
7432     NamedDecl *Result;
7433     // Retry building the function declaration with the new previous
7434     // declarations, and with errors suppressed.
7435     {
7436       // Trap errors.
7437       Sema::SFINAETrap Trap(SemaRef);
7438 
7439       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7440       // pieces need to verify the typo-corrected C++ declaration and hopefully
7441       // eliminate the need for the parameter pack ExtraArgs.
7442       Result = SemaRef.ActOnFunctionDeclarator(
7443           ExtraArgs.S, ExtraArgs.D,
7444           Correction.getCorrectionDecl()->getDeclContext(),
7445           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7446           ExtraArgs.AddToScope);
7447 
7448       if (Trap.hasErrorOccurred())
7449         Result = nullptr;
7450     }
7451 
7452     if (Result) {
7453       // Determine which correction we picked.
7454       Decl *Canonical = Result->getCanonicalDecl();
7455       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7456            I != E; ++I)
7457         if ((*I)->getCanonicalDecl() == Canonical)
7458           Correction.setCorrectionDecl(*I);
7459 
7460       SemaRef.diagnoseTypo(
7461           Correction,
7462           SemaRef.PDiag(IsLocalFriend
7463                           ? diag::err_no_matching_local_friend_suggest
7464                           : diag::err_member_decl_does_not_match_suggest)
7465             << Name << NewDC << IsDefinition);
7466       return Result;
7467     }
7468 
7469     // Pretend the typo correction never occurred
7470     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7471                               ExtraArgs.D.getIdentifierLoc());
7472     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7473     Previous.clear();
7474     Previous.setLookupName(Name);
7475   }
7476 
7477   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7478       << Name << NewDC << IsDefinition << NewFD->getLocation();
7479 
7480   bool NewFDisConst = false;
7481   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7482     NewFDisConst = NewMD->isConst();
7483 
7484   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7485        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7486        NearMatch != NearMatchEnd; ++NearMatch) {
7487     FunctionDecl *FD = NearMatch->first;
7488     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7489     bool FDisConst = MD && MD->isConst();
7490     bool IsMember = MD || !IsLocalFriend;
7491 
7492     // FIXME: These notes are poorly worded for the local friend case.
7493     if (unsigned Idx = NearMatch->second) {
7494       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7495       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7496       if (Loc.isInvalid()) Loc = FD->getLocation();
7497       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7498                                  : diag::note_local_decl_close_param_match)
7499         << Idx << FDParam->getType()
7500         << NewFD->getParamDecl(Idx - 1)->getType();
7501     } else if (FDisConst != NewFDisConst) {
7502       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7503           << NewFDisConst << FD->getSourceRange().getEnd();
7504     } else
7505       SemaRef.Diag(FD->getLocation(),
7506                    IsMember ? diag::note_member_def_close_match
7507                             : diag::note_local_decl_close_match);
7508   }
7509   return nullptr;
7510 }
7511 
7512 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7513   switch (D.getDeclSpec().getStorageClassSpec()) {
7514   default: llvm_unreachable("Unknown storage class!");
7515   case DeclSpec::SCS_auto:
7516   case DeclSpec::SCS_register:
7517   case DeclSpec::SCS_mutable:
7518     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7519                  diag::err_typecheck_sclass_func);
7520     D.setInvalidType();
7521     break;
7522   case DeclSpec::SCS_unspecified: break;
7523   case DeclSpec::SCS_extern:
7524     if (D.getDeclSpec().isExternInLinkageSpec())
7525       return SC_None;
7526     return SC_Extern;
7527   case DeclSpec::SCS_static: {
7528     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7529       // C99 6.7.1p5:
7530       //   The declaration of an identifier for a function that has
7531       //   block scope shall have no explicit storage-class specifier
7532       //   other than extern
7533       // See also (C++ [dcl.stc]p4).
7534       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7535                    diag::err_static_block_func);
7536       break;
7537     } else
7538       return SC_Static;
7539   }
7540   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7541   }
7542 
7543   // No explicit storage class has already been returned
7544   return SC_None;
7545 }
7546 
7547 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7548                                            DeclContext *DC, QualType &R,
7549                                            TypeSourceInfo *TInfo,
7550                                            StorageClass SC,
7551                                            bool &IsVirtualOkay) {
7552   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7553   DeclarationName Name = NameInfo.getName();
7554 
7555   FunctionDecl *NewFD = nullptr;
7556   bool isInline = D.getDeclSpec().isInlineSpecified();
7557 
7558   if (!SemaRef.getLangOpts().CPlusPlus) {
7559     // Determine whether the function was written with a
7560     // prototype. This true when:
7561     //   - there is a prototype in the declarator, or
7562     //   - the type R of the function is some kind of typedef or other reference
7563     //     to a type name (which eventually refers to a function type).
7564     bool HasPrototype =
7565       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7566       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7567 
7568     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7569                                  D.getLocStart(), NameInfo, R,
7570                                  TInfo, SC, isInline,
7571                                  HasPrototype, false);
7572     if (D.isInvalidType())
7573       NewFD->setInvalidDecl();
7574 
7575     return NewFD;
7576   }
7577 
7578   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7579   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7580 
7581   // Check that the return type is not an abstract class type.
7582   // For record types, this is done by the AbstractClassUsageDiagnoser once
7583   // the class has been completely parsed.
7584   if (!DC->isRecord() &&
7585       SemaRef.RequireNonAbstractType(
7586           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7587           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7588     D.setInvalidType();
7589 
7590   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7591     // This is a C++ constructor declaration.
7592     assert(DC->isRecord() &&
7593            "Constructors can only be declared in a member context");
7594 
7595     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7596     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7597                                       D.getLocStart(), NameInfo,
7598                                       R, TInfo, isExplicit, isInline,
7599                                       /*isImplicitlyDeclared=*/false,
7600                                       isConstexpr);
7601 
7602   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7603     // This is a C++ destructor declaration.
7604     if (DC->isRecord()) {
7605       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7606       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7607       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7608                                         SemaRef.Context, Record,
7609                                         D.getLocStart(),
7610                                         NameInfo, R, TInfo, isInline,
7611                                         /*isImplicitlyDeclared=*/false);
7612 
7613       // If the class is complete, then we now create the implicit exception
7614       // specification. If the class is incomplete or dependent, we can't do
7615       // it yet.
7616       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7617           Record->getDefinition() && !Record->isBeingDefined() &&
7618           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7619         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7620       }
7621 
7622       IsVirtualOkay = true;
7623       return NewDD;
7624 
7625     } else {
7626       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7627       D.setInvalidType();
7628 
7629       // Create a FunctionDecl to satisfy the function definition parsing
7630       // code path.
7631       return FunctionDecl::Create(SemaRef.Context, DC,
7632                                   D.getLocStart(),
7633                                   D.getIdentifierLoc(), Name, R, TInfo,
7634                                   SC, isInline,
7635                                   /*hasPrototype=*/true, isConstexpr);
7636     }
7637 
7638   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7639     if (!DC->isRecord()) {
7640       SemaRef.Diag(D.getIdentifierLoc(),
7641            diag::err_conv_function_not_member);
7642       return nullptr;
7643     }
7644 
7645     SemaRef.CheckConversionDeclarator(D, R, SC);
7646     IsVirtualOkay = true;
7647     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7648                                      D.getLocStart(), NameInfo,
7649                                      R, TInfo, isInline, isExplicit,
7650                                      isConstexpr, SourceLocation());
7651 
7652   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7653     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7654 
7655     // We don't need to store any extra information for a deduction guide, so
7656     // just model it as a plain FunctionDecl.
7657     return FunctionDecl::Create(SemaRef.Context, DC,
7658                                 D.getLocStart(),
7659                                 NameInfo, R, TInfo, SC, isInline,
7660                                 true/*HasPrototype*/, isConstexpr);
7661   } else if (DC->isRecord()) {
7662     // If the name of the function is the same as the name of the record,
7663     // then this must be an invalid constructor that has a return type.
7664     // (The parser checks for a return type and makes the declarator a
7665     // constructor if it has no return type).
7666     if (Name.getAsIdentifierInfo() &&
7667         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7668       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7669         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7670         << SourceRange(D.getIdentifierLoc());
7671       return nullptr;
7672     }
7673 
7674     // This is a C++ method declaration.
7675     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7676                                                cast<CXXRecordDecl>(DC),
7677                                                D.getLocStart(), NameInfo, R,
7678                                                TInfo, SC, isInline,
7679                                                isConstexpr, SourceLocation());
7680     IsVirtualOkay = !Ret->isStatic();
7681     return Ret;
7682   } else {
7683     bool isFriend =
7684         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7685     if (!isFriend && SemaRef.CurContext->isRecord())
7686       return nullptr;
7687 
7688     // Determine whether the function was written with a
7689     // prototype. This true when:
7690     //   - we're in C++ (where every function has a prototype),
7691     return FunctionDecl::Create(SemaRef.Context, DC,
7692                                 D.getLocStart(),
7693                                 NameInfo, R, TInfo, SC, isInline,
7694                                 true/*HasPrototype*/, isConstexpr);
7695   }
7696 }
7697 
7698 enum OpenCLParamType {
7699   ValidKernelParam,
7700   PtrPtrKernelParam,
7701   PtrKernelParam,
7702   InvalidAddrSpacePtrKernelParam,
7703   InvalidKernelParam,
7704   RecordKernelParam
7705 };
7706 
7707 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7708   if (PT->isPointerType()) {
7709     QualType PointeeType = PT->getPointeeType();
7710     if (PointeeType->isPointerType())
7711       return PtrPtrKernelParam;
7712     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7713         PointeeType.getAddressSpace() == 0)
7714       return InvalidAddrSpacePtrKernelParam;
7715     return PtrKernelParam;
7716   }
7717 
7718   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7719   // be used as builtin types.
7720 
7721   if (PT->isImageType())
7722     return PtrKernelParam;
7723 
7724   if (PT->isBooleanType())
7725     return InvalidKernelParam;
7726 
7727   if (PT->isEventT())
7728     return InvalidKernelParam;
7729 
7730   // OpenCL extension spec v1.2 s9.5:
7731   // This extension adds support for half scalar and vector types as built-in
7732   // types that can be used for arithmetic operations, conversions etc.
7733   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7734     return InvalidKernelParam;
7735 
7736   if (PT->isRecordType())
7737     return RecordKernelParam;
7738 
7739   return ValidKernelParam;
7740 }
7741 
7742 static void checkIsValidOpenCLKernelParameter(
7743   Sema &S,
7744   Declarator &D,
7745   ParmVarDecl *Param,
7746   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7747   QualType PT = Param->getType();
7748 
7749   // Cache the valid types we encounter to avoid rechecking structs that are
7750   // used again
7751   if (ValidTypes.count(PT.getTypePtr()))
7752     return;
7753 
7754   switch (getOpenCLKernelParameterType(S, PT)) {
7755   case PtrPtrKernelParam:
7756     // OpenCL v1.2 s6.9.a:
7757     // A kernel function argument cannot be declared as a
7758     // pointer to a pointer type.
7759     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7760     D.setInvalidType();
7761     return;
7762 
7763   case InvalidAddrSpacePtrKernelParam:
7764     // OpenCL v1.0 s6.5:
7765     // __kernel function arguments declared to be a pointer of a type can point
7766     // to one of the following address spaces only : __global, __local or
7767     // __constant.
7768     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7769     D.setInvalidType();
7770     return;
7771 
7772     // OpenCL v1.2 s6.9.k:
7773     // Arguments to kernel functions in a program cannot be declared with the
7774     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7775     // uintptr_t or a struct and/or union that contain fields declared to be
7776     // one of these built-in scalar types.
7777 
7778   case InvalidKernelParam:
7779     // OpenCL v1.2 s6.8 n:
7780     // A kernel function argument cannot be declared
7781     // of event_t type.
7782     // Do not diagnose half type since it is diagnosed as invalid argument
7783     // type for any function elsewhere.
7784     if (!PT->isHalfType())
7785       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7786     D.setInvalidType();
7787     return;
7788 
7789   case PtrKernelParam:
7790   case ValidKernelParam:
7791     ValidTypes.insert(PT.getTypePtr());
7792     return;
7793 
7794   case RecordKernelParam:
7795     break;
7796   }
7797 
7798   // Track nested structs we will inspect
7799   SmallVector<const Decl *, 4> VisitStack;
7800 
7801   // Track where we are in the nested structs. Items will migrate from
7802   // VisitStack to HistoryStack as we do the DFS for bad field.
7803   SmallVector<const FieldDecl *, 4> HistoryStack;
7804   HistoryStack.push_back(nullptr);
7805 
7806   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7807   VisitStack.push_back(PD);
7808 
7809   assert(VisitStack.back() && "First decl null?");
7810 
7811   do {
7812     const Decl *Next = VisitStack.pop_back_val();
7813     if (!Next) {
7814       assert(!HistoryStack.empty());
7815       // Found a marker, we have gone up a level
7816       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7817         ValidTypes.insert(Hist->getType().getTypePtr());
7818 
7819       continue;
7820     }
7821 
7822     // Adds everything except the original parameter declaration (which is not a
7823     // field itself) to the history stack.
7824     const RecordDecl *RD;
7825     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7826       HistoryStack.push_back(Field);
7827       RD = Field->getType()->castAs<RecordType>()->getDecl();
7828     } else {
7829       RD = cast<RecordDecl>(Next);
7830     }
7831 
7832     // Add a null marker so we know when we've gone back up a level
7833     VisitStack.push_back(nullptr);
7834 
7835     for (const auto *FD : RD->fields()) {
7836       QualType QT = FD->getType();
7837 
7838       if (ValidTypes.count(QT.getTypePtr()))
7839         continue;
7840 
7841       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7842       if (ParamType == ValidKernelParam)
7843         continue;
7844 
7845       if (ParamType == RecordKernelParam) {
7846         VisitStack.push_back(FD);
7847         continue;
7848       }
7849 
7850       // OpenCL v1.2 s6.9.p:
7851       // Arguments to kernel functions that are declared to be a struct or union
7852       // do not allow OpenCL objects to be passed as elements of the struct or
7853       // union.
7854       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7855           ParamType == InvalidAddrSpacePtrKernelParam) {
7856         S.Diag(Param->getLocation(),
7857                diag::err_record_with_pointers_kernel_param)
7858           << PT->isUnionType()
7859           << PT;
7860       } else {
7861         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7862       }
7863 
7864       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7865         << PD->getDeclName();
7866 
7867       // We have an error, now let's go back up through history and show where
7868       // the offending field came from
7869       for (ArrayRef<const FieldDecl *>::const_iterator
7870                I = HistoryStack.begin() + 1,
7871                E = HistoryStack.end();
7872            I != E; ++I) {
7873         const FieldDecl *OuterField = *I;
7874         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7875           << OuterField->getType();
7876       }
7877 
7878       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7879         << QT->isPointerType()
7880         << QT;
7881       D.setInvalidType();
7882       return;
7883     }
7884   } while (!VisitStack.empty());
7885 }
7886 
7887 /// Find the DeclContext in which a tag is implicitly declared if we see an
7888 /// elaborated type specifier in the specified context, and lookup finds
7889 /// nothing.
7890 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7891   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7892     DC = DC->getParent();
7893   return DC;
7894 }
7895 
7896 /// Find the Scope in which a tag is implicitly declared if we see an
7897 /// elaborated type specifier in the specified context, and lookup finds
7898 /// nothing.
7899 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7900   while (S->isClassScope() ||
7901          (LangOpts.CPlusPlus &&
7902           S->isFunctionPrototypeScope()) ||
7903          ((S->getFlags() & Scope::DeclScope) == 0) ||
7904          (S->getEntity() && S->getEntity()->isTransparentContext()))
7905     S = S->getParent();
7906   return S;
7907 }
7908 
7909 NamedDecl*
7910 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7911                               TypeSourceInfo *TInfo, LookupResult &Previous,
7912                               MultiTemplateParamsArg TemplateParamLists,
7913                               bool &AddToScope) {
7914   QualType R = TInfo->getType();
7915 
7916   assert(R.getTypePtr()->isFunctionType());
7917 
7918   // TODO: consider using NameInfo for diagnostic.
7919   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7920   DeclarationName Name = NameInfo.getName();
7921   StorageClass SC = getFunctionStorageClass(*this, D);
7922 
7923   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7924     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7925          diag::err_invalid_thread)
7926       << DeclSpec::getSpecifierName(TSCS);
7927 
7928   if (D.isFirstDeclarationOfMember())
7929     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7930                            D.getIdentifierLoc());
7931 
7932   bool isFriend = false;
7933   FunctionTemplateDecl *FunctionTemplate = nullptr;
7934   bool isExplicitSpecialization = false;
7935   bool isFunctionTemplateSpecialization = false;
7936 
7937   bool isDependentClassScopeExplicitSpecialization = false;
7938   bool HasExplicitTemplateArgs = false;
7939   TemplateArgumentListInfo TemplateArgs;
7940 
7941   bool isVirtualOkay = false;
7942 
7943   DeclContext *OriginalDC = DC;
7944   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7945 
7946   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7947                                               isVirtualOkay);
7948   if (!NewFD) return nullptr;
7949 
7950   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7951     NewFD->setTopLevelDeclInObjCContainer();
7952 
7953   // Set the lexical context. If this is a function-scope declaration, or has a
7954   // C++ scope specifier, or is the object of a friend declaration, the lexical
7955   // context will be different from the semantic context.
7956   NewFD->setLexicalDeclContext(CurContext);
7957 
7958   if (IsLocalExternDecl)
7959     NewFD->setLocalExternDecl();
7960 
7961   if (getLangOpts().CPlusPlus) {
7962     bool isInline = D.getDeclSpec().isInlineSpecified();
7963     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7964     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7965     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7966     bool isConcept = D.getDeclSpec().isConceptSpecified();
7967     isFriend = D.getDeclSpec().isFriendSpecified();
7968     if (isFriend && !isInline && D.isFunctionDefinition()) {
7969       // C++ [class.friend]p5
7970       //   A function can be defined in a friend declaration of a
7971       //   class . . . . Such a function is implicitly inline.
7972       NewFD->setImplicitlyInline();
7973     }
7974 
7975     // If this is a method defined in an __interface, and is not a constructor
7976     // or an overloaded operator, then set the pure flag (isVirtual will already
7977     // return true).
7978     if (const CXXRecordDecl *Parent =
7979           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7980       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7981         NewFD->setPure(true);
7982 
7983       // C++ [class.union]p2
7984       //   A union can have member functions, but not virtual functions.
7985       if (isVirtual && Parent->isUnion())
7986         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7987     }
7988 
7989     SetNestedNameSpecifier(NewFD, D);
7990     isExplicitSpecialization = false;
7991     isFunctionTemplateSpecialization = false;
7992     if (D.isInvalidType())
7993       NewFD->setInvalidDecl();
7994 
7995     // Match up the template parameter lists with the scope specifier, then
7996     // determine whether we have a template or a template specialization.
7997     bool Invalid = false;
7998     if (TemplateParameterList *TemplateParams =
7999             MatchTemplateParametersToScopeSpecifier(
8000                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8001                 D.getCXXScopeSpec(),
8002                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8003                     ? D.getName().TemplateId
8004                     : nullptr,
8005                 TemplateParamLists, isFriend, isExplicitSpecialization,
8006                 Invalid)) {
8007       if (TemplateParams->size() > 0) {
8008         // This is a function template
8009 
8010         // Check that we can declare a template here.
8011         if (CheckTemplateDeclScope(S, TemplateParams))
8012           NewFD->setInvalidDecl();
8013 
8014         // A destructor cannot be a template.
8015         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8016           Diag(NewFD->getLocation(), diag::err_destructor_template);
8017           NewFD->setInvalidDecl();
8018         }
8019 
8020         // If we're adding a template to a dependent context, we may need to
8021         // rebuilding some of the types used within the template parameter list,
8022         // now that we know what the current instantiation is.
8023         if (DC->isDependentContext()) {
8024           ContextRAII SavedContext(*this, DC);
8025           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8026             Invalid = true;
8027         }
8028 
8029         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8030                                                         NewFD->getLocation(),
8031                                                         Name, TemplateParams,
8032                                                         NewFD);
8033         FunctionTemplate->setLexicalDeclContext(CurContext);
8034         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8035 
8036         // For source fidelity, store the other template param lists.
8037         if (TemplateParamLists.size() > 1) {
8038           NewFD->setTemplateParameterListsInfo(Context,
8039                                                TemplateParamLists.drop_back(1));
8040         }
8041       } else {
8042         // This is a function template specialization.
8043         isFunctionTemplateSpecialization = true;
8044         // For source fidelity, store all the template param lists.
8045         if (TemplateParamLists.size() > 0)
8046           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8047 
8048         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8049         if (isFriend) {
8050           // We want to remove the "template<>", found here.
8051           SourceRange RemoveRange = TemplateParams->getSourceRange();
8052 
8053           // If we remove the template<> and the name is not a
8054           // template-id, we're actually silently creating a problem:
8055           // the friend declaration will refer to an untemplated decl,
8056           // and clearly the user wants a template specialization.  So
8057           // we need to insert '<>' after the name.
8058           SourceLocation InsertLoc;
8059           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8060             InsertLoc = D.getName().getSourceRange().getEnd();
8061             InsertLoc = getLocForEndOfToken(InsertLoc);
8062           }
8063 
8064           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8065             << Name << RemoveRange
8066             << FixItHint::CreateRemoval(RemoveRange)
8067             << FixItHint::CreateInsertion(InsertLoc, "<>");
8068         }
8069       }
8070     }
8071     else {
8072       // All template param lists were matched against the scope specifier:
8073       // this is NOT (an explicit specialization of) a template.
8074       if (TemplateParamLists.size() > 0)
8075         // For source fidelity, store all the template param lists.
8076         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8077     }
8078 
8079     if (Invalid) {
8080       NewFD->setInvalidDecl();
8081       if (FunctionTemplate)
8082         FunctionTemplate->setInvalidDecl();
8083     }
8084 
8085     // C++ [dcl.fct.spec]p5:
8086     //   The virtual specifier shall only be used in declarations of
8087     //   nonstatic class member functions that appear within a
8088     //   member-specification of a class declaration; see 10.3.
8089     //
8090     if (isVirtual && !NewFD->isInvalidDecl()) {
8091       if (!isVirtualOkay) {
8092         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8093              diag::err_virtual_non_function);
8094       } else if (!CurContext->isRecord()) {
8095         // 'virtual' was specified outside of the class.
8096         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8097              diag::err_virtual_out_of_class)
8098           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8099       } else if (NewFD->getDescribedFunctionTemplate()) {
8100         // C++ [temp.mem]p3:
8101         //  A member function template shall not be virtual.
8102         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8103              diag::err_virtual_member_function_template)
8104           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8105       } else {
8106         // Okay: Add virtual to the method.
8107         NewFD->setVirtualAsWritten(true);
8108       }
8109 
8110       if (getLangOpts().CPlusPlus14 &&
8111           NewFD->getReturnType()->isUndeducedType())
8112         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8113     }
8114 
8115     if (getLangOpts().CPlusPlus14 &&
8116         (NewFD->isDependentContext() ||
8117          (isFriend && CurContext->isDependentContext())) &&
8118         NewFD->getReturnType()->isUndeducedType()) {
8119       // If the function template is referenced directly (for instance, as a
8120       // member of the current instantiation), pretend it has a dependent type.
8121       // This is not really justified by the standard, but is the only sane
8122       // thing to do.
8123       // FIXME: For a friend function, we have not marked the function as being
8124       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8125       const FunctionProtoType *FPT =
8126           NewFD->getType()->castAs<FunctionProtoType>();
8127       QualType Result =
8128           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8129       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8130                                              FPT->getExtProtoInfo()));
8131     }
8132 
8133     // C++ [dcl.fct.spec]p3:
8134     //  The inline specifier shall not appear on a block scope function
8135     //  declaration.
8136     if (isInline && !NewFD->isInvalidDecl()) {
8137       if (CurContext->isFunctionOrMethod()) {
8138         // 'inline' is not allowed on block scope function declaration.
8139         Diag(D.getDeclSpec().getInlineSpecLoc(),
8140              diag::err_inline_declaration_block_scope) << Name
8141           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8142       }
8143     }
8144 
8145     // C++ [dcl.fct.spec]p6:
8146     //  The explicit specifier shall be used only in the declaration of a
8147     //  constructor or conversion function within its class definition;
8148     //  see 12.3.1 and 12.3.2.
8149     if (isExplicit && !NewFD->isInvalidDecl() && !NewFD->isDeductionGuide()) {
8150       if (!CurContext->isRecord()) {
8151         // 'explicit' was specified outside of the class.
8152         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8153              diag::err_explicit_out_of_class)
8154           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8155       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8156                  !isa<CXXConversionDecl>(NewFD)) {
8157         // 'explicit' was specified on a function that wasn't a constructor
8158         // or conversion function.
8159         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8160              diag::err_explicit_non_ctor_or_conv_function)
8161           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8162       }
8163     }
8164 
8165     if (isConstexpr) {
8166       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8167       // are implicitly inline.
8168       NewFD->setImplicitlyInline();
8169 
8170       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8171       // be either constructors or to return a literal type. Therefore,
8172       // destructors cannot be declared constexpr.
8173       if (isa<CXXDestructorDecl>(NewFD))
8174         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8175     }
8176 
8177     if (isConcept) {
8178       // This is a function concept.
8179       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8180         FTD->setConcept();
8181 
8182       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8183       // applied only to the definition of a function template [...]
8184       if (!D.isFunctionDefinition()) {
8185         Diag(D.getDeclSpec().getConceptSpecLoc(),
8186              diag::err_function_concept_not_defined);
8187         NewFD->setInvalidDecl();
8188       }
8189 
8190       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8191       // have no exception-specification and is treated as if it were specified
8192       // with noexcept(true) (15.4). [...]
8193       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8194         if (FPT->hasExceptionSpec()) {
8195           SourceRange Range;
8196           if (D.isFunctionDeclarator())
8197             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8198           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8199               << FixItHint::CreateRemoval(Range);
8200           NewFD->setInvalidDecl();
8201         } else {
8202           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8203         }
8204 
8205         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8206         // following restrictions:
8207         // - The declared return type shall have the type bool.
8208         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8209           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8210           NewFD->setInvalidDecl();
8211         }
8212 
8213         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8214         // following restrictions:
8215         // - The declaration's parameter list shall be equivalent to an empty
8216         //   parameter list.
8217         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8218           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8219       }
8220 
8221       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8222       // implicity defined to be a constexpr declaration (implicitly inline)
8223       NewFD->setImplicitlyInline();
8224 
8225       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8226       // be declared with the thread_local, inline, friend, or constexpr
8227       // specifiers, [...]
8228       if (isInline) {
8229         Diag(D.getDeclSpec().getInlineSpecLoc(),
8230              diag::err_concept_decl_invalid_specifiers)
8231             << 1 << 1;
8232         NewFD->setInvalidDecl(true);
8233       }
8234 
8235       if (isFriend) {
8236         Diag(D.getDeclSpec().getFriendSpecLoc(),
8237              diag::err_concept_decl_invalid_specifiers)
8238             << 1 << 2;
8239         NewFD->setInvalidDecl(true);
8240       }
8241 
8242       if (isConstexpr) {
8243         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8244              diag::err_concept_decl_invalid_specifiers)
8245             << 1 << 3;
8246         NewFD->setInvalidDecl(true);
8247       }
8248 
8249       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8250       // applied only to the definition of a function template or variable
8251       // template, declared in namespace scope.
8252       if (isFunctionTemplateSpecialization) {
8253         Diag(D.getDeclSpec().getConceptSpecLoc(),
8254              diag::err_concept_specified_specialization) << 1;
8255         NewFD->setInvalidDecl(true);
8256         return NewFD;
8257       }
8258     }
8259 
8260     // If __module_private__ was specified, mark the function accordingly.
8261     if (D.getDeclSpec().isModulePrivateSpecified()) {
8262       if (isFunctionTemplateSpecialization) {
8263         SourceLocation ModulePrivateLoc
8264           = D.getDeclSpec().getModulePrivateSpecLoc();
8265         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8266           << 0
8267           << FixItHint::CreateRemoval(ModulePrivateLoc);
8268       } else {
8269         NewFD->setModulePrivate();
8270         if (FunctionTemplate)
8271           FunctionTemplate->setModulePrivate();
8272       }
8273     }
8274 
8275     if (isFriend) {
8276       if (FunctionTemplate) {
8277         FunctionTemplate->setObjectOfFriendDecl();
8278         FunctionTemplate->setAccess(AS_public);
8279       }
8280       NewFD->setObjectOfFriendDecl();
8281       NewFD->setAccess(AS_public);
8282     }
8283 
8284     // If a function is defined as defaulted or deleted, mark it as such now.
8285     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8286     // definition kind to FDK_Definition.
8287     switch (D.getFunctionDefinitionKind()) {
8288       case FDK_Declaration:
8289       case FDK_Definition:
8290         break;
8291 
8292       case FDK_Defaulted:
8293         NewFD->setDefaulted();
8294         break;
8295 
8296       case FDK_Deleted:
8297         NewFD->setDeletedAsWritten();
8298         break;
8299     }
8300 
8301     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8302         D.isFunctionDefinition()) {
8303       // C++ [class.mfct]p2:
8304       //   A member function may be defined (8.4) in its class definition, in
8305       //   which case it is an inline member function (7.1.2)
8306       NewFD->setImplicitlyInline();
8307     }
8308 
8309     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8310         !CurContext->isRecord()) {
8311       // C++ [class.static]p1:
8312       //   A data or function member of a class may be declared static
8313       //   in a class definition, in which case it is a static member of
8314       //   the class.
8315 
8316       // Complain about the 'static' specifier if it's on an out-of-line
8317       // member function definition.
8318       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8319            diag::err_static_out_of_line)
8320         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8321     }
8322 
8323     // C++11 [except.spec]p15:
8324     //   A deallocation function with no exception-specification is treated
8325     //   as if it were specified with noexcept(true).
8326     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8327     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8328          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8329         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8330       NewFD->setType(Context.getFunctionType(
8331           FPT->getReturnType(), FPT->getParamTypes(),
8332           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8333   }
8334 
8335   // Filter out previous declarations that don't match the scope.
8336   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8337                        D.getCXXScopeSpec().isNotEmpty() ||
8338                        isExplicitSpecialization ||
8339                        isFunctionTemplateSpecialization);
8340 
8341   // Handle GNU asm-label extension (encoded as an attribute).
8342   if (Expr *E = (Expr*) D.getAsmLabel()) {
8343     // The parser guarantees this is a string.
8344     StringLiteral *SE = cast<StringLiteral>(E);
8345     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8346                                                 SE->getString(), 0));
8347   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8348     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8349       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8350     if (I != ExtnameUndeclaredIdentifiers.end()) {
8351       if (isDeclExternC(NewFD)) {
8352         NewFD->addAttr(I->second);
8353         ExtnameUndeclaredIdentifiers.erase(I);
8354       } else
8355         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8356             << /*Variable*/0 << NewFD;
8357     }
8358   }
8359 
8360   // Copy the parameter declarations from the declarator D to the function
8361   // declaration NewFD, if they are available.  First scavenge them into Params.
8362   SmallVector<ParmVarDecl*, 16> Params;
8363   unsigned FTIIdx;
8364   if (D.isFunctionDeclarator(FTIIdx)) {
8365     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8366 
8367     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8368     // function that takes no arguments, not a function that takes a
8369     // single void argument.
8370     // We let through "const void" here because Sema::GetTypeForDeclarator
8371     // already checks for that case.
8372     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8373       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8374         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8375         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8376         Param->setDeclContext(NewFD);
8377         Params.push_back(Param);
8378 
8379         if (Param->isInvalidDecl())
8380           NewFD->setInvalidDecl();
8381       }
8382     }
8383 
8384     if (!getLangOpts().CPlusPlus) {
8385       // In C, find all the tag declarations from the prototype and move them
8386       // into the function DeclContext. Remove them from the surrounding tag
8387       // injection context of the function, which is typically but not always
8388       // the TU.
8389       DeclContext *PrototypeTagContext =
8390           getTagInjectionContext(NewFD->getLexicalDeclContext());
8391       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8392         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8393 
8394         // We don't want to reparent enumerators. Look at their parent enum
8395         // instead.
8396         if (!TD) {
8397           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8398             TD = cast<EnumDecl>(ECD->getDeclContext());
8399         }
8400         if (!TD)
8401           continue;
8402         DeclContext *TagDC = TD->getLexicalDeclContext();
8403         if (!TagDC->containsDecl(TD))
8404           continue;
8405         TagDC->removeDecl(TD);
8406         TD->setDeclContext(NewFD);
8407         NewFD->addDecl(TD);
8408 
8409         // Preserve the lexical DeclContext if it is not the surrounding tag
8410         // injection context of the FD. In this example, the semantic context of
8411         // E will be f and the lexical context will be S, while both the
8412         // semantic and lexical contexts of S will be f:
8413         //   void f(struct S { enum E { a } f; } s);
8414         if (TagDC != PrototypeTagContext)
8415           TD->setLexicalDeclContext(TagDC);
8416       }
8417     }
8418   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8419     // When we're declaring a function with a typedef, typeof, etc as in the
8420     // following example, we'll need to synthesize (unnamed)
8421     // parameters for use in the declaration.
8422     //
8423     // @code
8424     // typedef void fn(int);
8425     // fn f;
8426     // @endcode
8427 
8428     // Synthesize a parameter for each argument type.
8429     for (const auto &AI : FT->param_types()) {
8430       ParmVarDecl *Param =
8431           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8432       Param->setScopeInfo(0, Params.size());
8433       Params.push_back(Param);
8434     }
8435   } else {
8436     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8437            "Should not need args for typedef of non-prototype fn");
8438   }
8439 
8440   // Finally, we know we have the right number of parameters, install them.
8441   NewFD->setParams(Params);
8442 
8443   if (D.getDeclSpec().isNoreturnSpecified())
8444     NewFD->addAttr(
8445         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8446                                        Context, 0));
8447 
8448   // Functions returning a variably modified type violate C99 6.7.5.2p2
8449   // because all functions have linkage.
8450   if (!NewFD->isInvalidDecl() &&
8451       NewFD->getReturnType()->isVariablyModifiedType()) {
8452     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8453     NewFD->setInvalidDecl();
8454   }
8455 
8456   // Apply an implicit SectionAttr if #pragma code_seg is active.
8457   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8458       !NewFD->hasAttr<SectionAttr>()) {
8459     NewFD->addAttr(
8460         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8461                                     CodeSegStack.CurrentValue->getString(),
8462                                     CodeSegStack.CurrentPragmaLocation));
8463     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8464                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8465                          ASTContext::PSF_Read,
8466                      NewFD))
8467       NewFD->dropAttr<SectionAttr>();
8468   }
8469 
8470   // Handle attributes.
8471   ProcessDeclAttributes(S, NewFD, D);
8472 
8473   if (getLangOpts().OpenCL) {
8474     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8475     // type declaration will generate a compilation error.
8476     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8477     if (AddressSpace == LangAS::opencl_local ||
8478         AddressSpace == LangAS::opencl_global ||
8479         AddressSpace == LangAS::opencl_constant) {
8480       Diag(NewFD->getLocation(),
8481            diag::err_opencl_return_value_with_address_space);
8482       NewFD->setInvalidDecl();
8483     }
8484   }
8485 
8486   if (!getLangOpts().CPlusPlus) {
8487     // Perform semantic checking on the function declaration.
8488     bool isExplicitSpecialization=false;
8489     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8490       CheckMain(NewFD, D.getDeclSpec());
8491 
8492     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8493       CheckMSVCRTEntryPoint(NewFD);
8494 
8495     if (!NewFD->isInvalidDecl())
8496       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8497                                                   isExplicitSpecialization));
8498     else if (!Previous.empty())
8499       // Recover gracefully from an invalid redeclaration.
8500       D.setRedeclaration(true);
8501     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8502             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8503            "previous declaration set still overloaded");
8504 
8505     // Diagnose no-prototype function declarations with calling conventions that
8506     // don't support variadic calls. Only do this in C and do it after merging
8507     // possibly prototyped redeclarations.
8508     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8509     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8510       CallingConv CC = FT->getExtInfo().getCC();
8511       if (!supportsVariadicCall(CC)) {
8512         // Windows system headers sometimes accidentally use stdcall without
8513         // (void) parameters, so we relax this to a warning.
8514         int DiagID =
8515             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8516         Diag(NewFD->getLocation(), DiagID)
8517             << FunctionType::getNameForCallConv(CC);
8518       }
8519     }
8520   } else {
8521     // C++11 [replacement.functions]p3:
8522     //  The program's definitions shall not be specified as inline.
8523     //
8524     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8525     //
8526     // Suppress the diagnostic if the function is __attribute__((used)), since
8527     // that forces an external definition to be emitted.
8528     if (D.getDeclSpec().isInlineSpecified() &&
8529         NewFD->isReplaceableGlobalAllocationFunction() &&
8530         !NewFD->hasAttr<UsedAttr>())
8531       Diag(D.getDeclSpec().getInlineSpecLoc(),
8532            diag::ext_operator_new_delete_declared_inline)
8533         << NewFD->getDeclName();
8534 
8535     // If the declarator is a template-id, translate the parser's template
8536     // argument list into our AST format.
8537     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8538       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8539       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8540       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8541       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8542                                          TemplateId->NumArgs);
8543       translateTemplateArguments(TemplateArgsPtr,
8544                                  TemplateArgs);
8545 
8546       HasExplicitTemplateArgs = true;
8547 
8548       if (NewFD->isInvalidDecl()) {
8549         HasExplicitTemplateArgs = false;
8550       } else if (FunctionTemplate) {
8551         // Function template with explicit template arguments.
8552         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8553           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8554 
8555         HasExplicitTemplateArgs = false;
8556       } else {
8557         assert((isFunctionTemplateSpecialization ||
8558                 D.getDeclSpec().isFriendSpecified()) &&
8559                "should have a 'template<>' for this decl");
8560         // "friend void foo<>(int);" is an implicit specialization decl.
8561         isFunctionTemplateSpecialization = true;
8562       }
8563     } else if (isFriend && isFunctionTemplateSpecialization) {
8564       // This combination is only possible in a recovery case;  the user
8565       // wrote something like:
8566       //   template <> friend void foo(int);
8567       // which we're recovering from as if the user had written:
8568       //   friend void foo<>(int);
8569       // Go ahead and fake up a template id.
8570       HasExplicitTemplateArgs = true;
8571       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8572       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8573     }
8574 
8575     // We do not add HD attributes to specializations here because
8576     // they may have different constexpr-ness compared to their
8577     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8578     // may end up with different effective targets. Instead, a
8579     // specialization inherits its target attributes from its template
8580     // in the CheckFunctionTemplateSpecialization() call below.
8581     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8582       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8583 
8584     // If it's a friend (and only if it's a friend), it's possible
8585     // that either the specialized function type or the specialized
8586     // template is dependent, and therefore matching will fail.  In
8587     // this case, don't check the specialization yet.
8588     bool InstantiationDependent = false;
8589     if (isFunctionTemplateSpecialization && isFriend &&
8590         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8591          TemplateSpecializationType::anyDependentTemplateArguments(
8592             TemplateArgs,
8593             InstantiationDependent))) {
8594       assert(HasExplicitTemplateArgs &&
8595              "friend function specialization without template args");
8596       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8597                                                        Previous))
8598         NewFD->setInvalidDecl();
8599     } else if (isFunctionTemplateSpecialization) {
8600       if (CurContext->isDependentContext() && CurContext->isRecord()
8601           && !isFriend) {
8602         isDependentClassScopeExplicitSpecialization = true;
8603         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8604           diag::ext_function_specialization_in_class :
8605           diag::err_function_specialization_in_class)
8606           << NewFD->getDeclName();
8607       } else if (CheckFunctionTemplateSpecialization(NewFD,
8608                                   (HasExplicitTemplateArgs ? &TemplateArgs
8609                                                            : nullptr),
8610                                                      Previous))
8611         NewFD->setInvalidDecl();
8612 
8613       // C++ [dcl.stc]p1:
8614       //   A storage-class-specifier shall not be specified in an explicit
8615       //   specialization (14.7.3)
8616       FunctionTemplateSpecializationInfo *Info =
8617           NewFD->getTemplateSpecializationInfo();
8618       if (Info && SC != SC_None) {
8619         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8620           Diag(NewFD->getLocation(),
8621                diag::err_explicit_specialization_inconsistent_storage_class)
8622             << SC
8623             << FixItHint::CreateRemoval(
8624                                       D.getDeclSpec().getStorageClassSpecLoc());
8625 
8626         else
8627           Diag(NewFD->getLocation(),
8628                diag::ext_explicit_specialization_storage_class)
8629             << FixItHint::CreateRemoval(
8630                                       D.getDeclSpec().getStorageClassSpecLoc());
8631       }
8632     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8633       if (CheckMemberSpecialization(NewFD, Previous))
8634           NewFD->setInvalidDecl();
8635     }
8636 
8637     // Perform semantic checking on the function declaration.
8638     if (!isDependentClassScopeExplicitSpecialization) {
8639       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8640         CheckMain(NewFD, D.getDeclSpec());
8641 
8642       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8643         CheckMSVCRTEntryPoint(NewFD);
8644 
8645       if (!NewFD->isInvalidDecl())
8646         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8647                                                     isExplicitSpecialization));
8648       else if (!Previous.empty())
8649         // Recover gracefully from an invalid redeclaration.
8650         D.setRedeclaration(true);
8651     }
8652 
8653     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8654             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8655            "previous declaration set still overloaded");
8656 
8657     NamedDecl *PrincipalDecl = (FunctionTemplate
8658                                 ? cast<NamedDecl>(FunctionTemplate)
8659                                 : NewFD);
8660 
8661     if (isFriend && NewFD->getPreviousDecl()) {
8662       AccessSpecifier Access = AS_public;
8663       if (!NewFD->isInvalidDecl())
8664         Access = NewFD->getPreviousDecl()->getAccess();
8665 
8666       NewFD->setAccess(Access);
8667       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8668     }
8669 
8670     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8671         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8672       PrincipalDecl->setNonMemberOperator();
8673 
8674     // If we have a function template, check the template parameter
8675     // list. This will check and merge default template arguments.
8676     if (FunctionTemplate) {
8677       FunctionTemplateDecl *PrevTemplate =
8678                                      FunctionTemplate->getPreviousDecl();
8679       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8680                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8681                                     : nullptr,
8682                             D.getDeclSpec().isFriendSpecified()
8683                               ? (D.isFunctionDefinition()
8684                                    ? TPC_FriendFunctionTemplateDefinition
8685                                    : TPC_FriendFunctionTemplate)
8686                               : (D.getCXXScopeSpec().isSet() &&
8687                                  DC && DC->isRecord() &&
8688                                  DC->isDependentContext())
8689                                   ? TPC_ClassTemplateMember
8690                                   : TPC_FunctionTemplate);
8691     }
8692 
8693     if (NewFD->isInvalidDecl()) {
8694       // Ignore all the rest of this.
8695     } else if (!D.isRedeclaration()) {
8696       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8697                                        AddToScope };
8698       // Fake up an access specifier if it's supposed to be a class member.
8699       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8700         NewFD->setAccess(AS_public);
8701 
8702       // Qualified decls generally require a previous declaration.
8703       if (D.getCXXScopeSpec().isSet()) {
8704         // ...with the major exception of templated-scope or
8705         // dependent-scope friend declarations.
8706 
8707         // TODO: we currently also suppress this check in dependent
8708         // contexts because (1) the parameter depth will be off when
8709         // matching friend templates and (2) we might actually be
8710         // selecting a friend based on a dependent factor.  But there
8711         // are situations where these conditions don't apply and we
8712         // can actually do this check immediately.
8713         if (isFriend &&
8714             (TemplateParamLists.size() ||
8715              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8716              CurContext->isDependentContext())) {
8717           // ignore these
8718         } else {
8719           // The user tried to provide an out-of-line definition for a
8720           // function that is a member of a class or namespace, but there
8721           // was no such member function declared (C++ [class.mfct]p2,
8722           // C++ [namespace.memdef]p2). For example:
8723           //
8724           // class X {
8725           //   void f() const;
8726           // };
8727           //
8728           // void X::f() { } // ill-formed
8729           //
8730           // Complain about this problem, and attempt to suggest close
8731           // matches (e.g., those that differ only in cv-qualifiers and
8732           // whether the parameter types are references).
8733 
8734           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8735                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8736             AddToScope = ExtraArgs.AddToScope;
8737             return Result;
8738           }
8739         }
8740 
8741         // Unqualified local friend declarations are required to resolve
8742         // to something.
8743       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8744         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8745                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8746           AddToScope = ExtraArgs.AddToScope;
8747           return Result;
8748         }
8749       }
8750     } else if (!D.isFunctionDefinition() &&
8751                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8752                !isFriend && !isFunctionTemplateSpecialization &&
8753                !isExplicitSpecialization) {
8754       // An out-of-line member function declaration must also be a
8755       // definition (C++ [class.mfct]p2).
8756       // Note that this is not the case for explicit specializations of
8757       // function templates or member functions of class templates, per
8758       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8759       // extension for compatibility with old SWIG code which likes to
8760       // generate them.
8761       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8762         << D.getCXXScopeSpec().getRange();
8763     }
8764   }
8765 
8766   ProcessPragmaWeak(S, NewFD);
8767   checkAttributesAfterMerging(*this, *NewFD);
8768 
8769   AddKnownFunctionAttributes(NewFD);
8770 
8771   if (NewFD->hasAttr<OverloadableAttr>() &&
8772       !NewFD->getType()->getAs<FunctionProtoType>()) {
8773     Diag(NewFD->getLocation(),
8774          diag::err_attribute_overloadable_no_prototype)
8775       << NewFD;
8776 
8777     // Turn this into a variadic function with no parameters.
8778     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8779     FunctionProtoType::ExtProtoInfo EPI(
8780         Context.getDefaultCallingConvention(true, false));
8781     EPI.Variadic = true;
8782     EPI.ExtInfo = FT->getExtInfo();
8783 
8784     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8785     NewFD->setType(R);
8786   }
8787 
8788   // If there's a #pragma GCC visibility in scope, and this isn't a class
8789   // member, set the visibility of this function.
8790   if (!DC->isRecord() && NewFD->isExternallyVisible())
8791     AddPushedVisibilityAttribute(NewFD);
8792 
8793   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8794   // marking the function.
8795   AddCFAuditedAttribute(NewFD);
8796 
8797   // If this is a function definition, check if we have to apply optnone due to
8798   // a pragma.
8799   if(D.isFunctionDefinition())
8800     AddRangeBasedOptnone(NewFD);
8801 
8802   // If this is the first declaration of an extern C variable, update
8803   // the map of such variables.
8804   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8805       isIncompleteDeclExternC(*this, NewFD))
8806     RegisterLocallyScopedExternCDecl(NewFD, S);
8807 
8808   // Set this FunctionDecl's range up to the right paren.
8809   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8810 
8811   if (D.isRedeclaration() && !Previous.empty()) {
8812     checkDLLAttributeRedeclaration(
8813         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8814         isExplicitSpecialization || isFunctionTemplateSpecialization,
8815         D.isFunctionDefinition());
8816   }
8817 
8818   if (getLangOpts().CUDA) {
8819     IdentifierInfo *II = NewFD->getIdentifier();
8820     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8821         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8822       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8823         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8824 
8825       Context.setcudaConfigureCallDecl(NewFD);
8826     }
8827 
8828     // Variadic functions, other than a *declaration* of printf, are not allowed
8829     // in device-side CUDA code, unless someone passed
8830     // -fcuda-allow-variadic-functions.
8831     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8832         (NewFD->hasAttr<CUDADeviceAttr>() ||
8833          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8834         !(II && II->isStr("printf") && NewFD->isExternC() &&
8835           !D.isFunctionDefinition())) {
8836       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8837     }
8838   }
8839 
8840   if (getLangOpts().CPlusPlus) {
8841     if (FunctionTemplate) {
8842       if (NewFD->isInvalidDecl())
8843         FunctionTemplate->setInvalidDecl();
8844       return FunctionTemplate;
8845     }
8846   }
8847 
8848   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8849     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8850     if ((getLangOpts().OpenCLVersion >= 120)
8851         && (SC == SC_Static)) {
8852       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8853       D.setInvalidType();
8854     }
8855 
8856     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8857     if (!NewFD->getReturnType()->isVoidType()) {
8858       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8859       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8860           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8861                                 : FixItHint());
8862       D.setInvalidType();
8863     }
8864 
8865     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8866     for (auto Param : NewFD->parameters())
8867       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8868   }
8869   for (const ParmVarDecl *Param : NewFD->parameters()) {
8870     QualType PT = Param->getType();
8871 
8872     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8873     // types.
8874     if (getLangOpts().OpenCLVersion >= 200) {
8875       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8876         QualType ElemTy = PipeTy->getElementType();
8877           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8878             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8879             D.setInvalidType();
8880           }
8881       }
8882     }
8883   }
8884 
8885   MarkUnusedFileScopedDecl(NewFD);
8886 
8887   // Here we have an function template explicit specialization at class scope.
8888   // The actually specialization will be postponed to template instatiation
8889   // time via the ClassScopeFunctionSpecializationDecl node.
8890   if (isDependentClassScopeExplicitSpecialization) {
8891     ClassScopeFunctionSpecializationDecl *NewSpec =
8892                          ClassScopeFunctionSpecializationDecl::Create(
8893                                 Context, CurContext, SourceLocation(),
8894                                 cast<CXXMethodDecl>(NewFD),
8895                                 HasExplicitTemplateArgs, TemplateArgs);
8896     CurContext->addDecl(NewSpec);
8897     AddToScope = false;
8898   }
8899 
8900   return NewFD;
8901 }
8902 
8903 /// \brief Checks if the new declaration declared in dependent context must be
8904 /// put in the same redeclaration chain as the specified declaration.
8905 ///
8906 /// \param D Declaration that is checked.
8907 /// \param PrevDecl Previous declaration found with proper lookup method for the
8908 ///                 same declaration name.
8909 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8910 ///          belongs to.
8911 ///
8912 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8913   // Any declarations should be put into redeclaration chains except for
8914   // friend declaration in a dependent context that names a function in
8915   // namespace scope.
8916   //
8917   // This allows to compile code like:
8918   //
8919   //       void func();
8920   //       template<typename T> class C1 { friend void func() { } };
8921   //       template<typename T> class C2 { friend void func() { } };
8922   //
8923   // This code snippet is a valid code unless both templates are instantiated.
8924   return !(D->getLexicalDeclContext()->isDependentContext() &&
8925            D->getDeclContext()->isFileContext() &&
8926            D->getFriendObjectKind() != Decl::FOK_None);
8927 }
8928 
8929 /// \brief Perform semantic checking of a new function declaration.
8930 ///
8931 /// Performs semantic analysis of the new function declaration
8932 /// NewFD. This routine performs all semantic checking that does not
8933 /// require the actual declarator involved in the declaration, and is
8934 /// used both for the declaration of functions as they are parsed
8935 /// (called via ActOnDeclarator) and for the declaration of functions
8936 /// that have been instantiated via C++ template instantiation (called
8937 /// via InstantiateDecl).
8938 ///
8939 /// \param IsExplicitSpecialization whether this new function declaration is
8940 /// an explicit specialization of the previous declaration.
8941 ///
8942 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8943 ///
8944 /// \returns true if the function declaration is a redeclaration.
8945 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8946                                     LookupResult &Previous,
8947                                     bool IsExplicitSpecialization) {
8948   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8949          "Variably modified return types are not handled here");
8950 
8951   // Determine whether the type of this function should be merged with
8952   // a previous visible declaration. This never happens for functions in C++,
8953   // and always happens in C if the previous declaration was visible.
8954   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8955                                !Previous.isShadowed();
8956 
8957   bool Redeclaration = false;
8958   NamedDecl *OldDecl = nullptr;
8959 
8960   // Merge or overload the declaration with an existing declaration of
8961   // the same name, if appropriate.
8962   if (!Previous.empty()) {
8963     // Determine whether NewFD is an overload of PrevDecl or
8964     // a declaration that requires merging. If it's an overload,
8965     // there's no more work to do here; we'll just add the new
8966     // function to the scope.
8967     if (!AllowOverloadingOfFunction(Previous, Context)) {
8968       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8969       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8970         Redeclaration = true;
8971         OldDecl = Candidate;
8972       }
8973     } else {
8974       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8975                             /*NewIsUsingDecl*/ false)) {
8976       case Ovl_Match:
8977         Redeclaration = true;
8978         break;
8979 
8980       case Ovl_NonFunction:
8981         Redeclaration = true;
8982         break;
8983 
8984       case Ovl_Overload:
8985         Redeclaration = false;
8986         break;
8987       }
8988 
8989       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8990         // If a function name is overloadable in C, then every function
8991         // with that name must be marked "overloadable".
8992         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8993           << Redeclaration << NewFD;
8994         NamedDecl *OverloadedDecl = nullptr;
8995         if (Redeclaration)
8996           OverloadedDecl = OldDecl;
8997         else if (!Previous.empty())
8998           OverloadedDecl = Previous.getRepresentativeDecl();
8999         if (OverloadedDecl)
9000           Diag(OverloadedDecl->getLocation(),
9001                diag::note_attribute_overloadable_prev_overload);
9002         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9003       }
9004     }
9005   }
9006 
9007   // Check for a previous extern "C" declaration with this name.
9008   if (!Redeclaration &&
9009       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9010     if (!Previous.empty()) {
9011       // This is an extern "C" declaration with the same name as a previous
9012       // declaration, and thus redeclares that entity...
9013       Redeclaration = true;
9014       OldDecl = Previous.getFoundDecl();
9015       MergeTypeWithPrevious = false;
9016 
9017       // ... except in the presence of __attribute__((overloadable)).
9018       if (OldDecl->hasAttr<OverloadableAttr>()) {
9019         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9020           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9021             << Redeclaration << NewFD;
9022           Diag(Previous.getFoundDecl()->getLocation(),
9023                diag::note_attribute_overloadable_prev_overload);
9024           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9025         }
9026         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9027           Redeclaration = false;
9028           OldDecl = nullptr;
9029         }
9030       }
9031     }
9032   }
9033 
9034   // C++11 [dcl.constexpr]p8:
9035   //   A constexpr specifier for a non-static member function that is not
9036   //   a constructor declares that member function to be const.
9037   //
9038   // This needs to be delayed until we know whether this is an out-of-line
9039   // definition of a static member function.
9040   //
9041   // This rule is not present in C++1y, so we produce a backwards
9042   // compatibility warning whenever it happens in C++11.
9043   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9044   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9045       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9046       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9047     CXXMethodDecl *OldMD = nullptr;
9048     if (OldDecl)
9049       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9050     if (!OldMD || !OldMD->isStatic()) {
9051       const FunctionProtoType *FPT =
9052         MD->getType()->castAs<FunctionProtoType>();
9053       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9054       EPI.TypeQuals |= Qualifiers::Const;
9055       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9056                                           FPT->getParamTypes(), EPI));
9057 
9058       // Warn that we did this, if we're not performing template instantiation.
9059       // In that case, we'll have warned already when the template was defined.
9060       if (ActiveTemplateInstantiations.empty()) {
9061         SourceLocation AddConstLoc;
9062         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9063                 .IgnoreParens().getAs<FunctionTypeLoc>())
9064           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9065 
9066         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9067           << FixItHint::CreateInsertion(AddConstLoc, " const");
9068       }
9069     }
9070   }
9071 
9072   if (Redeclaration) {
9073     // NewFD and OldDecl represent declarations that need to be
9074     // merged.
9075     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9076       NewFD->setInvalidDecl();
9077       return Redeclaration;
9078     }
9079 
9080     Previous.clear();
9081     Previous.addDecl(OldDecl);
9082 
9083     if (FunctionTemplateDecl *OldTemplateDecl
9084                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9085       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9086       FunctionTemplateDecl *NewTemplateDecl
9087         = NewFD->getDescribedFunctionTemplate();
9088       assert(NewTemplateDecl && "Template/non-template mismatch");
9089       if (CXXMethodDecl *Method
9090             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9091         Method->setAccess(OldTemplateDecl->getAccess());
9092         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9093       }
9094 
9095       // If this is an explicit specialization of a member that is a function
9096       // template, mark it as a member specialization.
9097       if (IsExplicitSpecialization &&
9098           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9099         NewTemplateDecl->setMemberSpecialization();
9100         assert(OldTemplateDecl->isMemberSpecialization());
9101         // Explicit specializations of a member template do not inherit deleted
9102         // status from the parent member template that they are specializing.
9103         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9104           FunctionDecl *const OldTemplatedDecl =
9105               OldTemplateDecl->getTemplatedDecl();
9106           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9107           OldTemplatedDecl->setDeletedAsWritten(false);
9108         }
9109       }
9110 
9111     } else {
9112       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9113         // This needs to happen first so that 'inline' propagates.
9114         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9115         if (isa<CXXMethodDecl>(NewFD))
9116           NewFD->setAccess(OldDecl->getAccess());
9117       }
9118     }
9119   }
9120 
9121   // Semantic checking for this function declaration (in isolation).
9122 
9123   if (getLangOpts().CPlusPlus) {
9124     // C++-specific checks.
9125     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9126       CheckConstructor(Constructor);
9127     } else if (CXXDestructorDecl *Destructor =
9128                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9129       CXXRecordDecl *Record = Destructor->getParent();
9130       QualType ClassType = Context.getTypeDeclType(Record);
9131 
9132       // FIXME: Shouldn't we be able to perform this check even when the class
9133       // type is dependent? Both gcc and edg can handle that.
9134       if (!ClassType->isDependentType()) {
9135         DeclarationName Name
9136           = Context.DeclarationNames.getCXXDestructorName(
9137                                         Context.getCanonicalType(ClassType));
9138         if (NewFD->getDeclName() != Name) {
9139           Diag(NewFD->getLocation(), diag::err_destructor_name);
9140           NewFD->setInvalidDecl();
9141           return Redeclaration;
9142         }
9143       }
9144     } else if (CXXConversionDecl *Conversion
9145                = dyn_cast<CXXConversionDecl>(NewFD)) {
9146       ActOnConversionDeclarator(Conversion);
9147     }
9148 
9149     // Find any virtual functions that this function overrides.
9150     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9151       if (!Method->isFunctionTemplateSpecialization() &&
9152           !Method->getDescribedFunctionTemplate() &&
9153           Method->isCanonicalDecl()) {
9154         if (AddOverriddenMethods(Method->getParent(), Method)) {
9155           // If the function was marked as "static", we have a problem.
9156           if (NewFD->getStorageClass() == SC_Static) {
9157             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9158           }
9159         }
9160       }
9161 
9162       if (Method->isStatic())
9163         checkThisInStaticMemberFunctionType(Method);
9164     }
9165 
9166     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9167     if (NewFD->isOverloadedOperator() &&
9168         CheckOverloadedOperatorDeclaration(NewFD)) {
9169       NewFD->setInvalidDecl();
9170       return Redeclaration;
9171     }
9172 
9173     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9174     if (NewFD->getLiteralIdentifier() &&
9175         CheckLiteralOperatorDeclaration(NewFD)) {
9176       NewFD->setInvalidDecl();
9177       return Redeclaration;
9178     }
9179 
9180     // In C++, check default arguments now that we have merged decls. Unless
9181     // the lexical context is the class, because in this case this is done
9182     // during delayed parsing anyway.
9183     if (!CurContext->isRecord())
9184       CheckCXXDefaultArguments(NewFD);
9185 
9186     // If this function declares a builtin function, check the type of this
9187     // declaration against the expected type for the builtin.
9188     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9189       ASTContext::GetBuiltinTypeError Error;
9190       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9191       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9192       // If the type of the builtin differs only in its exception
9193       // specification, that's OK.
9194       // FIXME: If the types do differ in this way, it would be better to
9195       // retain the 'noexcept' form of the type.
9196       if (!T.isNull() &&
9197           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9198                                                             NewFD->getType()))
9199         // The type of this function differs from the type of the builtin,
9200         // so forget about the builtin entirely.
9201         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9202     }
9203 
9204     // If this function is declared as being extern "C", then check to see if
9205     // the function returns a UDT (class, struct, or union type) that is not C
9206     // compatible, and if it does, warn the user.
9207     // But, issue any diagnostic on the first declaration only.
9208     if (Previous.empty() && NewFD->isExternC()) {
9209       QualType R = NewFD->getReturnType();
9210       if (R->isIncompleteType() && !R->isVoidType())
9211         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9212             << NewFD << R;
9213       else if (!R.isPODType(Context) && !R->isVoidType() &&
9214                !R->isObjCObjectPointerType())
9215         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9216     }
9217 
9218     // C++1z [dcl.fct]p6:
9219     //   [...] whether the function has a non-throwing exception-specification
9220     //   [is] part of the function type
9221     //
9222     // This results in an ABI break between C++14 and C++17 for functions whose
9223     // declared type includes an exception-specification in a parameter or
9224     // return type. (Exception specifications on the function itself are OK in
9225     // most cases, and exception specifications are not permitted in most other
9226     // contexts where they could make it into a mangling.)
9227     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9228       auto HasNoexcept = [&](QualType T) -> bool {
9229         // Strip off declarator chunks that could be between us and a function
9230         // type. We don't need to look far, exception specifications are very
9231         // restricted prior to C++17.
9232         if (auto *RT = T->getAs<ReferenceType>())
9233           T = RT->getPointeeType();
9234         else if (T->isAnyPointerType())
9235           T = T->getPointeeType();
9236         else if (auto *MPT = T->getAs<MemberPointerType>())
9237           T = MPT->getPointeeType();
9238         if (auto *FPT = T->getAs<FunctionProtoType>())
9239           if (FPT->isNothrow(Context))
9240             return true;
9241         return false;
9242       };
9243 
9244       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9245       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9246       for (QualType T : FPT->param_types())
9247         AnyNoexcept |= HasNoexcept(T);
9248       if (AnyNoexcept)
9249         Diag(NewFD->getLocation(),
9250              diag::warn_cxx1z_compat_exception_spec_in_signature)
9251             << NewFD;
9252     }
9253 
9254     if (!Redeclaration && LangOpts.CUDA)
9255       checkCUDATargetOverload(NewFD, Previous);
9256   }
9257   return Redeclaration;
9258 }
9259 
9260 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9261   // C++11 [basic.start.main]p3:
9262   //   A program that [...] declares main to be inline, static or
9263   //   constexpr is ill-formed.
9264   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9265   //   appear in a declaration of main.
9266   // static main is not an error under C99, but we should warn about it.
9267   // We accept _Noreturn main as an extension.
9268   if (FD->getStorageClass() == SC_Static)
9269     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9270          ? diag::err_static_main : diag::warn_static_main)
9271       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9272   if (FD->isInlineSpecified())
9273     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9274       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9275   if (DS.isNoreturnSpecified()) {
9276     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9277     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9278     Diag(NoreturnLoc, diag::ext_noreturn_main);
9279     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9280       << FixItHint::CreateRemoval(NoreturnRange);
9281   }
9282   if (FD->isConstexpr()) {
9283     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9284       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9285     FD->setConstexpr(false);
9286   }
9287 
9288   if (getLangOpts().OpenCL) {
9289     Diag(FD->getLocation(), diag::err_opencl_no_main)
9290         << FD->hasAttr<OpenCLKernelAttr>();
9291     FD->setInvalidDecl();
9292     return;
9293   }
9294 
9295   QualType T = FD->getType();
9296   assert(T->isFunctionType() && "function decl is not of function type");
9297   const FunctionType* FT = T->castAs<FunctionType>();
9298 
9299   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9300     // In C with GNU extensions we allow main() to have non-integer return
9301     // type, but we should warn about the extension, and we disable the
9302     // implicit-return-zero rule.
9303 
9304     // GCC in C mode accepts qualified 'int'.
9305     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9306       FD->setHasImplicitReturnZero(true);
9307     else {
9308       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9309       SourceRange RTRange = FD->getReturnTypeSourceRange();
9310       if (RTRange.isValid())
9311         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9312             << FixItHint::CreateReplacement(RTRange, "int");
9313     }
9314   } else {
9315     // In C and C++, main magically returns 0 if you fall off the end;
9316     // set the flag which tells us that.
9317     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9318 
9319     // All the standards say that main() should return 'int'.
9320     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9321       FD->setHasImplicitReturnZero(true);
9322     else {
9323       // Otherwise, this is just a flat-out error.
9324       SourceRange RTRange = FD->getReturnTypeSourceRange();
9325       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9326           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9327                                 : FixItHint());
9328       FD->setInvalidDecl(true);
9329     }
9330   }
9331 
9332   // Treat protoless main() as nullary.
9333   if (isa<FunctionNoProtoType>(FT)) return;
9334 
9335   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9336   unsigned nparams = FTP->getNumParams();
9337   assert(FD->getNumParams() == nparams);
9338 
9339   bool HasExtraParameters = (nparams > 3);
9340 
9341   if (FTP->isVariadic()) {
9342     Diag(FD->getLocation(), diag::ext_variadic_main);
9343     // FIXME: if we had information about the location of the ellipsis, we
9344     // could add a FixIt hint to remove it as a parameter.
9345   }
9346 
9347   // Darwin passes an undocumented fourth argument of type char**.  If
9348   // other platforms start sprouting these, the logic below will start
9349   // getting shifty.
9350   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9351     HasExtraParameters = false;
9352 
9353   if (HasExtraParameters) {
9354     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9355     FD->setInvalidDecl(true);
9356     nparams = 3;
9357   }
9358 
9359   // FIXME: a lot of the following diagnostics would be improved
9360   // if we had some location information about types.
9361 
9362   QualType CharPP =
9363     Context.getPointerType(Context.getPointerType(Context.CharTy));
9364   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9365 
9366   for (unsigned i = 0; i < nparams; ++i) {
9367     QualType AT = FTP->getParamType(i);
9368 
9369     bool mismatch = true;
9370 
9371     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9372       mismatch = false;
9373     else if (Expected[i] == CharPP) {
9374       // As an extension, the following forms are okay:
9375       //   char const **
9376       //   char const * const *
9377       //   char * const *
9378 
9379       QualifierCollector qs;
9380       const PointerType* PT;
9381       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9382           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9383           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9384                               Context.CharTy)) {
9385         qs.removeConst();
9386         mismatch = !qs.empty();
9387       }
9388     }
9389 
9390     if (mismatch) {
9391       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9392       // TODO: suggest replacing given type with expected type
9393       FD->setInvalidDecl(true);
9394     }
9395   }
9396 
9397   if (nparams == 1 && !FD->isInvalidDecl()) {
9398     Diag(FD->getLocation(), diag::warn_main_one_arg);
9399   }
9400 
9401   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9402     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9403     FD->setInvalidDecl();
9404   }
9405 }
9406 
9407 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9408   QualType T = FD->getType();
9409   assert(T->isFunctionType() && "function decl is not of function type");
9410   const FunctionType *FT = T->castAs<FunctionType>();
9411 
9412   // Set an implicit return of 'zero' if the function can return some integral,
9413   // enumeration, pointer or nullptr type.
9414   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9415       FT->getReturnType()->isAnyPointerType() ||
9416       FT->getReturnType()->isNullPtrType())
9417     // DllMain is exempt because a return value of zero means it failed.
9418     if (FD->getName() != "DllMain")
9419       FD->setHasImplicitReturnZero(true);
9420 
9421   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9422     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9423     FD->setInvalidDecl();
9424   }
9425 }
9426 
9427 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9428   // FIXME: Need strict checking.  In C89, we need to check for
9429   // any assignment, increment, decrement, function-calls, or
9430   // commas outside of a sizeof.  In C99, it's the same list,
9431   // except that the aforementioned are allowed in unevaluated
9432   // expressions.  Everything else falls under the
9433   // "may accept other forms of constant expressions" exception.
9434   // (We never end up here for C++, so the constant expression
9435   // rules there don't matter.)
9436   const Expr *Culprit;
9437   if (Init->isConstantInitializer(Context, false, &Culprit))
9438     return false;
9439   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9440     << Culprit->getSourceRange();
9441   return true;
9442 }
9443 
9444 namespace {
9445   // Visits an initialization expression to see if OrigDecl is evaluated in
9446   // its own initialization and throws a warning if it does.
9447   class SelfReferenceChecker
9448       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9449     Sema &S;
9450     Decl *OrigDecl;
9451     bool isRecordType;
9452     bool isPODType;
9453     bool isReferenceType;
9454 
9455     bool isInitList;
9456     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9457 
9458   public:
9459     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9460 
9461     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9462                                                     S(S), OrigDecl(OrigDecl) {
9463       isPODType = false;
9464       isRecordType = false;
9465       isReferenceType = false;
9466       isInitList = false;
9467       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9468         isPODType = VD->getType().isPODType(S.Context);
9469         isRecordType = VD->getType()->isRecordType();
9470         isReferenceType = VD->getType()->isReferenceType();
9471       }
9472     }
9473 
9474     // For most expressions, just call the visitor.  For initializer lists,
9475     // track the index of the field being initialized since fields are
9476     // initialized in order allowing use of previously initialized fields.
9477     void CheckExpr(Expr *E) {
9478       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9479       if (!InitList) {
9480         Visit(E);
9481         return;
9482       }
9483 
9484       // Track and increment the index here.
9485       isInitList = true;
9486       InitFieldIndex.push_back(0);
9487       for (auto Child : InitList->children()) {
9488         CheckExpr(cast<Expr>(Child));
9489         ++InitFieldIndex.back();
9490       }
9491       InitFieldIndex.pop_back();
9492     }
9493 
9494     // Returns true if MemberExpr is checked and no futher checking is needed.
9495     // Returns false if additional checking is required.
9496     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9497       llvm::SmallVector<FieldDecl*, 4> Fields;
9498       Expr *Base = E;
9499       bool ReferenceField = false;
9500 
9501       // Get the field memebers used.
9502       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9503         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9504         if (!FD)
9505           return false;
9506         Fields.push_back(FD);
9507         if (FD->getType()->isReferenceType())
9508           ReferenceField = true;
9509         Base = ME->getBase()->IgnoreParenImpCasts();
9510       }
9511 
9512       // Keep checking only if the base Decl is the same.
9513       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9514       if (!DRE || DRE->getDecl() != OrigDecl)
9515         return false;
9516 
9517       // A reference field can be bound to an unininitialized field.
9518       if (CheckReference && !ReferenceField)
9519         return true;
9520 
9521       // Convert FieldDecls to their index number.
9522       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9523       for (const FieldDecl *I : llvm::reverse(Fields))
9524         UsedFieldIndex.push_back(I->getFieldIndex());
9525 
9526       // See if a warning is needed by checking the first difference in index
9527       // numbers.  If field being used has index less than the field being
9528       // initialized, then the use is safe.
9529       for (auto UsedIter = UsedFieldIndex.begin(),
9530                 UsedEnd = UsedFieldIndex.end(),
9531                 OrigIter = InitFieldIndex.begin(),
9532                 OrigEnd = InitFieldIndex.end();
9533            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9534         if (*UsedIter < *OrigIter)
9535           return true;
9536         if (*UsedIter > *OrigIter)
9537           break;
9538       }
9539 
9540       // TODO: Add a different warning which will print the field names.
9541       HandleDeclRefExpr(DRE);
9542       return true;
9543     }
9544 
9545     // For most expressions, the cast is directly above the DeclRefExpr.
9546     // For conditional operators, the cast can be outside the conditional
9547     // operator if both expressions are DeclRefExpr's.
9548     void HandleValue(Expr *E) {
9549       E = E->IgnoreParens();
9550       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9551         HandleDeclRefExpr(DRE);
9552         return;
9553       }
9554 
9555       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9556         Visit(CO->getCond());
9557         HandleValue(CO->getTrueExpr());
9558         HandleValue(CO->getFalseExpr());
9559         return;
9560       }
9561 
9562       if (BinaryConditionalOperator *BCO =
9563               dyn_cast<BinaryConditionalOperator>(E)) {
9564         Visit(BCO->getCond());
9565         HandleValue(BCO->getFalseExpr());
9566         return;
9567       }
9568 
9569       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9570         HandleValue(OVE->getSourceExpr());
9571         return;
9572       }
9573 
9574       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9575         if (BO->getOpcode() == BO_Comma) {
9576           Visit(BO->getLHS());
9577           HandleValue(BO->getRHS());
9578           return;
9579         }
9580       }
9581 
9582       if (isa<MemberExpr>(E)) {
9583         if (isInitList) {
9584           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9585                                       false /*CheckReference*/))
9586             return;
9587         }
9588 
9589         Expr *Base = E->IgnoreParenImpCasts();
9590         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9591           // Check for static member variables and don't warn on them.
9592           if (!isa<FieldDecl>(ME->getMemberDecl()))
9593             return;
9594           Base = ME->getBase()->IgnoreParenImpCasts();
9595         }
9596         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9597           HandleDeclRefExpr(DRE);
9598         return;
9599       }
9600 
9601       Visit(E);
9602     }
9603 
9604     // Reference types not handled in HandleValue are handled here since all
9605     // uses of references are bad, not just r-value uses.
9606     void VisitDeclRefExpr(DeclRefExpr *E) {
9607       if (isReferenceType)
9608         HandleDeclRefExpr(E);
9609     }
9610 
9611     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9612       if (E->getCastKind() == CK_LValueToRValue) {
9613         HandleValue(E->getSubExpr());
9614         return;
9615       }
9616 
9617       Inherited::VisitImplicitCastExpr(E);
9618     }
9619 
9620     void VisitMemberExpr(MemberExpr *E) {
9621       if (isInitList) {
9622         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9623           return;
9624       }
9625 
9626       // Don't warn on arrays since they can be treated as pointers.
9627       if (E->getType()->canDecayToPointerType()) return;
9628 
9629       // Warn when a non-static method call is followed by non-static member
9630       // field accesses, which is followed by a DeclRefExpr.
9631       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9632       bool Warn = (MD && !MD->isStatic());
9633       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9634       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9635         if (!isa<FieldDecl>(ME->getMemberDecl()))
9636           Warn = false;
9637         Base = ME->getBase()->IgnoreParenImpCasts();
9638       }
9639 
9640       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9641         if (Warn)
9642           HandleDeclRefExpr(DRE);
9643         return;
9644       }
9645 
9646       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9647       // Visit that expression.
9648       Visit(Base);
9649     }
9650 
9651     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9652       Expr *Callee = E->getCallee();
9653 
9654       if (isa<UnresolvedLookupExpr>(Callee))
9655         return Inherited::VisitCXXOperatorCallExpr(E);
9656 
9657       Visit(Callee);
9658       for (auto Arg: E->arguments())
9659         HandleValue(Arg->IgnoreParenImpCasts());
9660     }
9661 
9662     void VisitUnaryOperator(UnaryOperator *E) {
9663       // For POD record types, addresses of its own members are well-defined.
9664       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9665           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9666         if (!isPODType)
9667           HandleValue(E->getSubExpr());
9668         return;
9669       }
9670 
9671       if (E->isIncrementDecrementOp()) {
9672         HandleValue(E->getSubExpr());
9673         return;
9674       }
9675 
9676       Inherited::VisitUnaryOperator(E);
9677     }
9678 
9679     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9680 
9681     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9682       if (E->getConstructor()->isCopyConstructor()) {
9683         Expr *ArgExpr = E->getArg(0);
9684         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9685           if (ILE->getNumInits() == 1)
9686             ArgExpr = ILE->getInit(0);
9687         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9688           if (ICE->getCastKind() == CK_NoOp)
9689             ArgExpr = ICE->getSubExpr();
9690         HandleValue(ArgExpr);
9691         return;
9692       }
9693       Inherited::VisitCXXConstructExpr(E);
9694     }
9695 
9696     void VisitCallExpr(CallExpr *E) {
9697       // Treat std::move as a use.
9698       if (E->getNumArgs() == 1) {
9699         if (FunctionDecl *FD = E->getDirectCallee()) {
9700           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9701               FD->getIdentifier()->isStr("move")) {
9702             HandleValue(E->getArg(0));
9703             return;
9704           }
9705         }
9706       }
9707 
9708       Inherited::VisitCallExpr(E);
9709     }
9710 
9711     void VisitBinaryOperator(BinaryOperator *E) {
9712       if (E->isCompoundAssignmentOp()) {
9713         HandleValue(E->getLHS());
9714         Visit(E->getRHS());
9715         return;
9716       }
9717 
9718       Inherited::VisitBinaryOperator(E);
9719     }
9720 
9721     // A custom visitor for BinaryConditionalOperator is needed because the
9722     // regular visitor would check the condition and true expression separately
9723     // but both point to the same place giving duplicate diagnostics.
9724     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9725       Visit(E->getCond());
9726       Visit(E->getFalseExpr());
9727     }
9728 
9729     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9730       Decl* ReferenceDecl = DRE->getDecl();
9731       if (OrigDecl != ReferenceDecl) return;
9732       unsigned diag;
9733       if (isReferenceType) {
9734         diag = diag::warn_uninit_self_reference_in_reference_init;
9735       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9736         diag = diag::warn_static_self_reference_in_init;
9737       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9738                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9739                  DRE->getDecl()->getType()->isRecordType()) {
9740         diag = diag::warn_uninit_self_reference_in_init;
9741       } else {
9742         // Local variables will be handled by the CFG analysis.
9743         return;
9744       }
9745 
9746       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9747                             S.PDiag(diag)
9748                               << DRE->getNameInfo().getName()
9749                               << OrigDecl->getLocation()
9750                               << DRE->getSourceRange());
9751     }
9752   };
9753 
9754   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9755   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9756                                  bool DirectInit) {
9757     // Parameters arguments are occassionially constructed with itself,
9758     // for instance, in recursive functions.  Skip them.
9759     if (isa<ParmVarDecl>(OrigDecl))
9760       return;
9761 
9762     E = E->IgnoreParens();
9763 
9764     // Skip checking T a = a where T is not a record or reference type.
9765     // Doing so is a way to silence uninitialized warnings.
9766     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9767       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9768         if (ICE->getCastKind() == CK_LValueToRValue)
9769           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9770             if (DRE->getDecl() == OrigDecl)
9771               return;
9772 
9773     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9774   }
9775 } // end anonymous namespace
9776 
9777 namespace {
9778   // Simple wrapper to add the name of a variable or (if no variable is
9779   // available) a DeclarationName into a diagnostic.
9780   struct VarDeclOrName {
9781     VarDecl *VDecl;
9782     DeclarationName Name;
9783 
9784     friend const Sema::SemaDiagnosticBuilder &
9785     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9786       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9787     }
9788   };
9789 } // end anonymous namespace
9790 
9791 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9792                                             DeclarationName Name, QualType Type,
9793                                             TypeSourceInfo *TSI,
9794                                             SourceRange Range, bool DirectInit,
9795                                             Expr *Init) {
9796   bool IsInitCapture = !VDecl;
9797   assert((!VDecl || !VDecl->isInitCapture()) &&
9798          "init captures are expected to be deduced prior to initialization");
9799 
9800   VarDeclOrName VN{VDecl, Name};
9801 
9802   DeducedType *Deduced = Type->getContainedDeducedType();
9803   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9804 
9805   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9806     Diag(Init->getLocStart(), diag::err_deduced_class_template_not_supported);
9807     return QualType();
9808   }
9809 
9810   ArrayRef<Expr *> DeduceInits = Init;
9811   if (DirectInit) {
9812     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9813       DeduceInits = PL->exprs();
9814     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9815       DeduceInits = IL->inits();
9816   }
9817 
9818   // Deduction only works if we have exactly one source expression.
9819   if (DeduceInits.empty()) {
9820     // It isn't possible to write this directly, but it is possible to
9821     // end up in this situation with "auto x(some_pack...);"
9822     Diag(Init->getLocStart(), IsInitCapture
9823                                   ? diag::err_init_capture_no_expression
9824                                   : diag::err_auto_var_init_no_expression)
9825         << VN << Type << Range;
9826     return QualType();
9827   }
9828 
9829   if (DeduceInits.size() > 1) {
9830     Diag(DeduceInits[1]->getLocStart(),
9831          IsInitCapture ? diag::err_init_capture_multiple_expressions
9832                        : diag::err_auto_var_init_multiple_expressions)
9833         << VN << Type << Range;
9834     return QualType();
9835   }
9836 
9837   Expr *DeduceInit = DeduceInits[0];
9838   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9839     Diag(Init->getLocStart(), IsInitCapture
9840                                   ? diag::err_init_capture_paren_braces
9841                                   : diag::err_auto_var_init_paren_braces)
9842         << isa<InitListExpr>(Init) << VN << Type << Range;
9843     return QualType();
9844   }
9845 
9846   // Expressions default to 'id' when we're in a debugger.
9847   bool DefaultedAnyToId = false;
9848   if (getLangOpts().DebuggerCastResultToId &&
9849       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9850     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9851     if (Result.isInvalid()) {
9852       return QualType();
9853     }
9854     Init = Result.get();
9855     DefaultedAnyToId = true;
9856   }
9857 
9858   // C++ [dcl.decomp]p1:
9859   //   If the assignment-expression [...] has array type A and no ref-qualifier
9860   //   is present, e has type cv A
9861   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9862       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9863       DeduceInit->getType()->isConstantArrayType())
9864     return Context.getQualifiedType(DeduceInit->getType(),
9865                                     Type.getQualifiers());
9866 
9867   QualType DeducedType;
9868   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9869     if (!IsInitCapture)
9870       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9871     else if (isa<InitListExpr>(Init))
9872       Diag(Range.getBegin(),
9873            diag::err_init_capture_deduction_failure_from_init_list)
9874           << VN
9875           << (DeduceInit->getType().isNull() ? TSI->getType()
9876                                              : DeduceInit->getType())
9877           << DeduceInit->getSourceRange();
9878     else
9879       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9880           << VN << TSI->getType()
9881           << (DeduceInit->getType().isNull() ? TSI->getType()
9882                                              : DeduceInit->getType())
9883           << DeduceInit->getSourceRange();
9884   }
9885 
9886   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9887   // 'id' instead of a specific object type prevents most of our usual
9888   // checks.
9889   // We only want to warn outside of template instantiations, though:
9890   // inside a template, the 'id' could have come from a parameter.
9891   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9892       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9893     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9894     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9895   }
9896 
9897   return DeducedType;
9898 }
9899 
9900 /// AddInitializerToDecl - Adds the initializer Init to the
9901 /// declaration dcl. If DirectInit is true, this is C++ direct
9902 /// initialization rather than copy initialization.
9903 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
9904   // If there is no declaration, there was an error parsing it.  Just ignore
9905   // the initializer.
9906   if (!RealDecl || RealDecl->isInvalidDecl()) {
9907     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9908     return;
9909   }
9910 
9911   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9912     // Pure-specifiers are handled in ActOnPureSpecifier.
9913     Diag(Method->getLocation(), diag::err_member_function_initialization)
9914       << Method->getDeclName() << Init->getSourceRange();
9915     Method->setInvalidDecl();
9916     return;
9917   }
9918 
9919   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9920   if (!VDecl) {
9921     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9922     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9923     RealDecl->setInvalidDecl();
9924     return;
9925   }
9926 
9927   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9928   if (VDecl->getType()->isUndeducedType()) {
9929     // Attempt typo correction early so that the type of the init expression can
9930     // be deduced based on the chosen correction if the original init contains a
9931     // TypoExpr.
9932     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9933     if (!Res.isUsable()) {
9934       RealDecl->setInvalidDecl();
9935       return;
9936     }
9937     Init = Res.get();
9938 
9939     QualType DeducedType = deduceVarTypeFromInitializer(
9940         VDecl, VDecl->getDeclName(), VDecl->getType(),
9941         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9942     if (DeducedType.isNull()) {
9943       RealDecl->setInvalidDecl();
9944       return;
9945     }
9946 
9947     VDecl->setType(DeducedType);
9948     assert(VDecl->isLinkageValid());
9949 
9950     // In ARC, infer lifetime.
9951     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9952       VDecl->setInvalidDecl();
9953 
9954     // If this is a redeclaration, check that the type we just deduced matches
9955     // the previously declared type.
9956     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9957       // We never need to merge the type, because we cannot form an incomplete
9958       // array of auto, nor deduce such a type.
9959       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9960     }
9961 
9962     // Check the deduced type is valid for a variable declaration.
9963     CheckVariableDeclarationType(VDecl);
9964     if (VDecl->isInvalidDecl())
9965       return;
9966   }
9967 
9968   // dllimport cannot be used on variable definitions.
9969   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9970     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9971     VDecl->setInvalidDecl();
9972     return;
9973   }
9974 
9975   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9976     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9977     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9978     VDecl->setInvalidDecl();
9979     return;
9980   }
9981 
9982   if (!VDecl->getType()->isDependentType()) {
9983     // A definition must end up with a complete type, which means it must be
9984     // complete with the restriction that an array type might be completed by
9985     // the initializer; note that later code assumes this restriction.
9986     QualType BaseDeclType = VDecl->getType();
9987     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9988       BaseDeclType = Array->getElementType();
9989     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9990                             diag::err_typecheck_decl_incomplete_type)) {
9991       RealDecl->setInvalidDecl();
9992       return;
9993     }
9994 
9995     // The variable can not have an abstract class type.
9996     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9997                                diag::err_abstract_type_in_decl,
9998                                AbstractVariableType))
9999       VDecl->setInvalidDecl();
10000   }
10001 
10002   // If adding the initializer will turn this declaration into a definition,
10003   // and we already have a definition for this variable, diagnose or otherwise
10004   // handle the situation.
10005   VarDecl *Def;
10006   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10007       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10008       !VDecl->isThisDeclarationADemotedDefinition() &&
10009       checkVarDeclRedefinition(Def, VDecl))
10010     return;
10011 
10012   if (getLangOpts().CPlusPlus) {
10013     // C++ [class.static.data]p4
10014     //   If a static data member is of const integral or const
10015     //   enumeration type, its declaration in the class definition can
10016     //   specify a constant-initializer which shall be an integral
10017     //   constant expression (5.19). In that case, the member can appear
10018     //   in integral constant expressions. The member shall still be
10019     //   defined in a namespace scope if it is used in the program and the
10020     //   namespace scope definition shall not contain an initializer.
10021     //
10022     // We already performed a redefinition check above, but for static
10023     // data members we also need to check whether there was an in-class
10024     // declaration with an initializer.
10025     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10026       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10027           << VDecl->getDeclName();
10028       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10029            diag::note_previous_initializer)
10030           << 0;
10031       return;
10032     }
10033 
10034     if (VDecl->hasLocalStorage())
10035       getCurFunction()->setHasBranchProtectedScope();
10036 
10037     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10038       VDecl->setInvalidDecl();
10039       return;
10040     }
10041   }
10042 
10043   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10044   // a kernel function cannot be initialized."
10045   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10046     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10047     VDecl->setInvalidDecl();
10048     return;
10049   }
10050 
10051   // Get the decls type and save a reference for later, since
10052   // CheckInitializerTypes may change it.
10053   QualType DclT = VDecl->getType(), SavT = DclT;
10054 
10055   // Expressions default to 'id' when we're in a debugger
10056   // and we are assigning it to a variable of Objective-C pointer type.
10057   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10058       Init->getType() == Context.UnknownAnyTy) {
10059     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10060     if (Result.isInvalid()) {
10061       VDecl->setInvalidDecl();
10062       return;
10063     }
10064     Init = Result.get();
10065   }
10066 
10067   // Perform the initialization.
10068   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10069   if (!VDecl->isInvalidDecl()) {
10070     // Handle errors like: int a({0})
10071     if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
10072         !canInitializeWithParenthesizedList(VDecl->getType()))
10073       if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
10074         Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
10075             << VDecl->getType() << CXXDirectInit->getSourceRange()
10076             << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
10077             << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
10078         Init = IList;
10079         CXXDirectInit = nullptr;
10080       }
10081 
10082     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10083     InitializationKind Kind =
10084         DirectInit
10085             ? CXXDirectInit
10086                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
10087                                                      Init->getLocStart(),
10088                                                      Init->getLocEnd())
10089                   : InitializationKind::CreateDirectList(VDecl->getLocation())
10090             : InitializationKind::CreateCopy(VDecl->getLocation(),
10091                                              Init->getLocStart());
10092 
10093     MultiExprArg Args = Init;
10094     if (CXXDirectInit)
10095       Args = MultiExprArg(CXXDirectInit->getExprs(),
10096                           CXXDirectInit->getNumExprs());
10097 
10098     // Try to correct any TypoExprs in the initialization arguments.
10099     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10100       ExprResult Res = CorrectDelayedTyposInExpr(
10101           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10102             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10103             return Init.Failed() ? ExprError() : E;
10104           });
10105       if (Res.isInvalid()) {
10106         VDecl->setInvalidDecl();
10107       } else if (Res.get() != Args[Idx]) {
10108         Args[Idx] = Res.get();
10109       }
10110     }
10111     if (VDecl->isInvalidDecl())
10112       return;
10113 
10114     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10115                                    /*TopLevelOfInitList=*/false,
10116                                    /*TreatUnavailableAsInvalid=*/false);
10117     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10118     if (Result.isInvalid()) {
10119       VDecl->setInvalidDecl();
10120       return;
10121     }
10122 
10123     Init = Result.getAs<Expr>();
10124   }
10125 
10126   // Check for self-references within variable initializers.
10127   // Variables declared within a function/method body (except for references)
10128   // are handled by a dataflow analysis.
10129   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10130       VDecl->getType()->isReferenceType()) {
10131     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10132   }
10133 
10134   // If the type changed, it means we had an incomplete type that was
10135   // completed by the initializer. For example:
10136   //   int ary[] = { 1, 3, 5 };
10137   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10138   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10139     VDecl->setType(DclT);
10140 
10141   if (!VDecl->isInvalidDecl()) {
10142     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10143 
10144     if (VDecl->hasAttr<BlocksAttr>())
10145       checkRetainCycles(VDecl, Init);
10146 
10147     // It is safe to assign a weak reference into a strong variable.
10148     // Although this code can still have problems:
10149     //   id x = self.weakProp;
10150     //   id y = self.weakProp;
10151     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10152     // paths through the function. This should be revisited if
10153     // -Wrepeated-use-of-weak is made flow-sensitive.
10154     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
10155         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10156                          Init->getLocStart()))
10157       getCurFunction()->markSafeWeakUse(Init);
10158   }
10159 
10160   // The initialization is usually a full-expression.
10161   //
10162   // FIXME: If this is a braced initialization of an aggregate, it is not
10163   // an expression, and each individual field initializer is a separate
10164   // full-expression. For instance, in:
10165   //
10166   //   struct Temp { ~Temp(); };
10167   //   struct S { S(Temp); };
10168   //   struct T { S a, b; } t = { Temp(), Temp() }
10169   //
10170   // we should destroy the first Temp before constructing the second.
10171   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10172                                           false,
10173                                           VDecl->isConstexpr());
10174   if (Result.isInvalid()) {
10175     VDecl->setInvalidDecl();
10176     return;
10177   }
10178   Init = Result.get();
10179 
10180   // Attach the initializer to the decl.
10181   VDecl->setInit(Init);
10182 
10183   if (VDecl->isLocalVarDecl()) {
10184     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10185     // static storage duration shall be constant expressions or string literals.
10186     // C++ does not have this restriction.
10187     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10188       const Expr *Culprit;
10189       if (VDecl->getStorageClass() == SC_Static)
10190         CheckForConstantInitializer(Init, DclT);
10191       // C89 is stricter than C99 for non-static aggregate types.
10192       // C89 6.5.7p3: All the expressions [...] in an initializer list
10193       // for an object that has aggregate or union type shall be
10194       // constant expressions.
10195       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10196                isa<InitListExpr>(Init) &&
10197                !Init->isConstantInitializer(Context, false, &Culprit))
10198         Diag(Culprit->getExprLoc(),
10199              diag::ext_aggregate_init_not_constant)
10200           << Culprit->getSourceRange();
10201     }
10202   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10203              VDecl->getLexicalDeclContext()->isRecord()) {
10204     // This is an in-class initialization for a static data member, e.g.,
10205     //
10206     // struct S {
10207     //   static const int value = 17;
10208     // };
10209 
10210     // C++ [class.mem]p4:
10211     //   A member-declarator can contain a constant-initializer only
10212     //   if it declares a static member (9.4) of const integral or
10213     //   const enumeration type, see 9.4.2.
10214     //
10215     // C++11 [class.static.data]p3:
10216     //   If a non-volatile non-inline const static data member is of integral
10217     //   or enumeration type, its declaration in the class definition can
10218     //   specify a brace-or-equal-initializer in which every initalizer-clause
10219     //   that is an assignment-expression is a constant expression. A static
10220     //   data member of literal type can be declared in the class definition
10221     //   with the constexpr specifier; if so, its declaration shall specify a
10222     //   brace-or-equal-initializer in which every initializer-clause that is
10223     //   an assignment-expression is a constant expression.
10224 
10225     // Do nothing on dependent types.
10226     if (DclT->isDependentType()) {
10227 
10228     // Allow any 'static constexpr' members, whether or not they are of literal
10229     // type. We separately check that every constexpr variable is of literal
10230     // type.
10231     } else if (VDecl->isConstexpr()) {
10232 
10233     // Require constness.
10234     } else if (!DclT.isConstQualified()) {
10235       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10236         << Init->getSourceRange();
10237       VDecl->setInvalidDecl();
10238 
10239     // We allow integer constant expressions in all cases.
10240     } else if (DclT->isIntegralOrEnumerationType()) {
10241       // Check whether the expression is a constant expression.
10242       SourceLocation Loc;
10243       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10244         // In C++11, a non-constexpr const static data member with an
10245         // in-class initializer cannot be volatile.
10246         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10247       else if (Init->isValueDependent())
10248         ; // Nothing to check.
10249       else if (Init->isIntegerConstantExpr(Context, &Loc))
10250         ; // Ok, it's an ICE!
10251       else if (Init->isEvaluatable(Context)) {
10252         // If we can constant fold the initializer through heroics, accept it,
10253         // but report this as a use of an extension for -pedantic.
10254         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10255           << Init->getSourceRange();
10256       } else {
10257         // Otherwise, this is some crazy unknown case.  Report the issue at the
10258         // location provided by the isIntegerConstantExpr failed check.
10259         Diag(Loc, diag::err_in_class_initializer_non_constant)
10260           << Init->getSourceRange();
10261         VDecl->setInvalidDecl();
10262       }
10263 
10264     // We allow foldable floating-point constants as an extension.
10265     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10266       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10267       // it anyway and provide a fixit to add the 'constexpr'.
10268       if (getLangOpts().CPlusPlus11) {
10269         Diag(VDecl->getLocation(),
10270              diag::ext_in_class_initializer_float_type_cxx11)
10271             << DclT << Init->getSourceRange();
10272         Diag(VDecl->getLocStart(),
10273              diag::note_in_class_initializer_float_type_cxx11)
10274             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10275       } else {
10276         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10277           << DclT << Init->getSourceRange();
10278 
10279         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10280           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10281             << Init->getSourceRange();
10282           VDecl->setInvalidDecl();
10283         }
10284       }
10285 
10286     // Suggest adding 'constexpr' in C++11 for literal types.
10287     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10288       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10289         << DclT << Init->getSourceRange()
10290         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10291       VDecl->setConstexpr(true);
10292 
10293     } else {
10294       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10295         << DclT << Init->getSourceRange();
10296       VDecl->setInvalidDecl();
10297     }
10298   } else if (VDecl->isFileVarDecl()) {
10299     // In C, extern is typically used to avoid tentative definitions when
10300     // declaring variables in headers, but adding an intializer makes it a
10301     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10302     // In C++, extern is often used to give implictly static const variables
10303     // external linkage, so don't warn in that case. If selectany is present,
10304     // this might be header code intended for C and C++ inclusion, so apply the
10305     // C++ rules.
10306     if (VDecl->getStorageClass() == SC_Extern &&
10307         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10308          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10309         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10310         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10311       Diag(VDecl->getLocation(), diag::warn_extern_init);
10312 
10313     // C99 6.7.8p4. All file scoped initializers need to be constant.
10314     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10315       CheckForConstantInitializer(Init, DclT);
10316   }
10317 
10318   // We will represent direct-initialization similarly to copy-initialization:
10319   //    int x(1);  -as-> int x = 1;
10320   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10321   //
10322   // Clients that want to distinguish between the two forms, can check for
10323   // direct initializer using VarDecl::getInitStyle().
10324   // A major benefit is that clients that don't particularly care about which
10325   // exactly form was it (like the CodeGen) can handle both cases without
10326   // special case code.
10327 
10328   // C++ 8.5p11:
10329   // The form of initialization (using parentheses or '=') is generally
10330   // insignificant, but does matter when the entity being initialized has a
10331   // class type.
10332   if (CXXDirectInit) {
10333     assert(DirectInit && "Call-style initializer must be direct init.");
10334     VDecl->setInitStyle(VarDecl::CallInit);
10335   } else if (DirectInit) {
10336     // This must be list-initialization. No other way is direct-initialization.
10337     VDecl->setInitStyle(VarDecl::ListInit);
10338   }
10339 
10340   CheckCompleteVariableDeclaration(VDecl);
10341 }
10342 
10343 /// ActOnInitializerError - Given that there was an error parsing an
10344 /// initializer for the given declaration, try to return to some form
10345 /// of sanity.
10346 void Sema::ActOnInitializerError(Decl *D) {
10347   // Our main concern here is re-establishing invariants like "a
10348   // variable's type is either dependent or complete".
10349   if (!D || D->isInvalidDecl()) return;
10350 
10351   VarDecl *VD = dyn_cast<VarDecl>(D);
10352   if (!VD) return;
10353 
10354   // Bindings are not usable if we can't make sense of the initializer.
10355   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10356     for (auto *BD : DD->bindings())
10357       BD->setInvalidDecl();
10358 
10359   // Auto types are meaningless if we can't make sense of the initializer.
10360   if (ParsingInitForAutoVars.count(D)) {
10361     D->setInvalidDecl();
10362     return;
10363   }
10364 
10365   QualType Ty = VD->getType();
10366   if (Ty->isDependentType()) return;
10367 
10368   // Require a complete type.
10369   if (RequireCompleteType(VD->getLocation(),
10370                           Context.getBaseElementType(Ty),
10371                           diag::err_typecheck_decl_incomplete_type)) {
10372     VD->setInvalidDecl();
10373     return;
10374   }
10375 
10376   // Require a non-abstract type.
10377   if (RequireNonAbstractType(VD->getLocation(), Ty,
10378                              diag::err_abstract_type_in_decl,
10379                              AbstractVariableType)) {
10380     VD->setInvalidDecl();
10381     return;
10382   }
10383 
10384   // Don't bother complaining about constructors or destructors,
10385   // though.
10386 }
10387 
10388 /// Checks if an object of the given type can be initialized with parenthesized
10389 /// init-list.
10390 ///
10391 /// \param TargetType Type of object being initialized.
10392 ///
10393 /// The function is used to detect wrong initializations, such as 'int({0})'.
10394 ///
10395 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
10396   return TargetType->isDependentType() || TargetType->isRecordType() ||
10397          TargetType->getContainedAutoType();
10398 }
10399 
10400 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10401   // If there is no declaration, there was an error parsing it. Just ignore it.
10402   if (!RealDecl)
10403     return;
10404 
10405   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10406     QualType Type = Var->getType();
10407 
10408     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10409     if (isa<DecompositionDecl>(RealDecl)) {
10410       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10411       Var->setInvalidDecl();
10412       return;
10413     }
10414 
10415     // C++11 [dcl.spec.auto]p3
10416     if (Type->isUndeducedType()) {
10417       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10418         << Var->getDeclName() << Type;
10419       Var->setInvalidDecl();
10420       return;
10421     }
10422 
10423     // C++11 [class.static.data]p3: A static data member can be declared with
10424     // the constexpr specifier; if so, its declaration shall specify
10425     // a brace-or-equal-initializer.
10426     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10427     // the definition of a variable [...] or the declaration of a static data
10428     // member.
10429     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10430         !Var->isThisDeclarationADemotedDefinition()) {
10431       if (Var->isStaticDataMember()) {
10432         // C++1z removes the relevant rule; the in-class declaration is always
10433         // a definition there.
10434         if (!getLangOpts().CPlusPlus1z) {
10435           Diag(Var->getLocation(),
10436                diag::err_constexpr_static_mem_var_requires_init)
10437             << Var->getDeclName();
10438           Var->setInvalidDecl();
10439           return;
10440         }
10441       } else {
10442         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10443         Var->setInvalidDecl();
10444         return;
10445       }
10446     }
10447 
10448     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10449     // definition having the concept specifier is called a variable concept. A
10450     // concept definition refers to [...] a variable concept and its initializer.
10451     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10452       if (VTD->isConcept()) {
10453         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10454         Var->setInvalidDecl();
10455         return;
10456       }
10457     }
10458 
10459     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10460     // be initialized.
10461     if (!Var->isInvalidDecl() &&
10462         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10463         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10464       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10465       Var->setInvalidDecl();
10466       return;
10467     }
10468 
10469     switch (Var->isThisDeclarationADefinition()) {
10470     case VarDecl::Definition:
10471       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10472         break;
10473 
10474       // We have an out-of-line definition of a static data member
10475       // that has an in-class initializer, so we type-check this like
10476       // a declaration.
10477       //
10478       // Fall through
10479 
10480     case VarDecl::DeclarationOnly:
10481       // It's only a declaration.
10482 
10483       // Block scope. C99 6.7p7: If an identifier for an object is
10484       // declared with no linkage (C99 6.2.2p6), the type for the
10485       // object shall be complete.
10486       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10487           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10488           RequireCompleteType(Var->getLocation(), Type,
10489                               diag::err_typecheck_decl_incomplete_type))
10490         Var->setInvalidDecl();
10491 
10492       // Make sure that the type is not abstract.
10493       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10494           RequireNonAbstractType(Var->getLocation(), Type,
10495                                  diag::err_abstract_type_in_decl,
10496                                  AbstractVariableType))
10497         Var->setInvalidDecl();
10498       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10499           Var->getStorageClass() == SC_PrivateExtern) {
10500         Diag(Var->getLocation(), diag::warn_private_extern);
10501         Diag(Var->getLocation(), diag::note_private_extern);
10502       }
10503 
10504       return;
10505 
10506     case VarDecl::TentativeDefinition:
10507       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10508       // object that has file scope without an initializer, and without a
10509       // storage-class specifier or with the storage-class specifier "static",
10510       // constitutes a tentative definition. Note: A tentative definition with
10511       // external linkage is valid (C99 6.2.2p5).
10512       if (!Var->isInvalidDecl()) {
10513         if (const IncompleteArrayType *ArrayT
10514                                     = Context.getAsIncompleteArrayType(Type)) {
10515           if (RequireCompleteType(Var->getLocation(),
10516                                   ArrayT->getElementType(),
10517                                   diag::err_illegal_decl_array_incomplete_type))
10518             Var->setInvalidDecl();
10519         } else if (Var->getStorageClass() == SC_Static) {
10520           // C99 6.9.2p3: If the declaration of an identifier for an object is
10521           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10522           // declared type shall not be an incomplete type.
10523           // NOTE: code such as the following
10524           //     static struct s;
10525           //     struct s { int a; };
10526           // is accepted by gcc. Hence here we issue a warning instead of
10527           // an error and we do not invalidate the static declaration.
10528           // NOTE: to avoid multiple warnings, only check the first declaration.
10529           if (Var->isFirstDecl())
10530             RequireCompleteType(Var->getLocation(), Type,
10531                                 diag::ext_typecheck_decl_incomplete_type);
10532         }
10533       }
10534 
10535       // Record the tentative definition; we're done.
10536       if (!Var->isInvalidDecl())
10537         TentativeDefinitions.push_back(Var);
10538       return;
10539     }
10540 
10541     // Provide a specific diagnostic for uninitialized variable
10542     // definitions with incomplete array type.
10543     if (Type->isIncompleteArrayType()) {
10544       Diag(Var->getLocation(),
10545            diag::err_typecheck_incomplete_array_needs_initializer);
10546       Var->setInvalidDecl();
10547       return;
10548     }
10549 
10550     // Provide a specific diagnostic for uninitialized variable
10551     // definitions with reference type.
10552     if (Type->isReferenceType()) {
10553       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10554         << Var->getDeclName()
10555         << SourceRange(Var->getLocation(), Var->getLocation());
10556       Var->setInvalidDecl();
10557       return;
10558     }
10559 
10560     // Do not attempt to type-check the default initializer for a
10561     // variable with dependent type.
10562     if (Type->isDependentType())
10563       return;
10564 
10565     if (Var->isInvalidDecl())
10566       return;
10567 
10568     if (!Var->hasAttr<AliasAttr>()) {
10569       if (RequireCompleteType(Var->getLocation(),
10570                               Context.getBaseElementType(Type),
10571                               diag::err_typecheck_decl_incomplete_type)) {
10572         Var->setInvalidDecl();
10573         return;
10574       }
10575     } else {
10576       return;
10577     }
10578 
10579     // The variable can not have an abstract class type.
10580     if (RequireNonAbstractType(Var->getLocation(), Type,
10581                                diag::err_abstract_type_in_decl,
10582                                AbstractVariableType)) {
10583       Var->setInvalidDecl();
10584       return;
10585     }
10586 
10587     // Check for jumps past the implicit initializer.  C++0x
10588     // clarifies that this applies to a "variable with automatic
10589     // storage duration", not a "local variable".
10590     // C++11 [stmt.dcl]p3
10591     //   A program that jumps from a point where a variable with automatic
10592     //   storage duration is not in scope to a point where it is in scope is
10593     //   ill-formed unless the variable has scalar type, class type with a
10594     //   trivial default constructor and a trivial destructor, a cv-qualified
10595     //   version of one of these types, or an array of one of the preceding
10596     //   types and is declared without an initializer.
10597     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10598       if (const RecordType *Record
10599             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10600         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10601         // Mark the function for further checking even if the looser rules of
10602         // C++11 do not require such checks, so that we can diagnose
10603         // incompatibilities with C++98.
10604         if (!CXXRecord->isPOD())
10605           getCurFunction()->setHasBranchProtectedScope();
10606       }
10607     }
10608 
10609     // C++03 [dcl.init]p9:
10610     //   If no initializer is specified for an object, and the
10611     //   object is of (possibly cv-qualified) non-POD class type (or
10612     //   array thereof), the object shall be default-initialized; if
10613     //   the object is of const-qualified type, the underlying class
10614     //   type shall have a user-declared default
10615     //   constructor. Otherwise, if no initializer is specified for
10616     //   a non- static object, the object and its subobjects, if
10617     //   any, have an indeterminate initial value); if the object
10618     //   or any of its subobjects are of const-qualified type, the
10619     //   program is ill-formed.
10620     // C++0x [dcl.init]p11:
10621     //   If no initializer is specified for an object, the object is
10622     //   default-initialized; [...].
10623     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10624     InitializationKind Kind
10625       = InitializationKind::CreateDefault(Var->getLocation());
10626 
10627     InitializationSequence InitSeq(*this, Entity, Kind, None);
10628     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10629     if (Init.isInvalid())
10630       Var->setInvalidDecl();
10631     else if (Init.get()) {
10632       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10633       // This is important for template substitution.
10634       Var->setInitStyle(VarDecl::CallInit);
10635     }
10636 
10637     CheckCompleteVariableDeclaration(Var);
10638   }
10639 }
10640 
10641 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10642   // If there is no declaration, there was an error parsing it. Ignore it.
10643   if (!D)
10644     return;
10645 
10646   VarDecl *VD = dyn_cast<VarDecl>(D);
10647   if (!VD) {
10648     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10649     D->setInvalidDecl();
10650     return;
10651   }
10652 
10653   VD->setCXXForRangeDecl(true);
10654 
10655   // for-range-declaration cannot be given a storage class specifier.
10656   int Error = -1;
10657   switch (VD->getStorageClass()) {
10658   case SC_None:
10659     break;
10660   case SC_Extern:
10661     Error = 0;
10662     break;
10663   case SC_Static:
10664     Error = 1;
10665     break;
10666   case SC_PrivateExtern:
10667     Error = 2;
10668     break;
10669   case SC_Auto:
10670     Error = 3;
10671     break;
10672   case SC_Register:
10673     Error = 4;
10674     break;
10675   }
10676   if (Error != -1) {
10677     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10678       << VD->getDeclName() << Error;
10679     D->setInvalidDecl();
10680   }
10681 }
10682 
10683 StmtResult
10684 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10685                                  IdentifierInfo *Ident,
10686                                  ParsedAttributes &Attrs,
10687                                  SourceLocation AttrEnd) {
10688   // C++1y [stmt.iter]p1:
10689   //   A range-based for statement of the form
10690   //      for ( for-range-identifier : for-range-initializer ) statement
10691   //   is equivalent to
10692   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10693   DeclSpec DS(Attrs.getPool().getFactory());
10694 
10695   const char *PrevSpec;
10696   unsigned DiagID;
10697   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10698                      getPrintingPolicy());
10699 
10700   Declarator D(DS, Declarator::ForContext);
10701   D.SetIdentifier(Ident, IdentLoc);
10702   D.takeAttributes(Attrs, AttrEnd);
10703 
10704   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10705   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10706                 EmptyAttrs, IdentLoc);
10707   Decl *Var = ActOnDeclarator(S, D);
10708   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10709   FinalizeDeclaration(Var);
10710   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10711                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10712 }
10713 
10714 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10715   if (var->isInvalidDecl()) return;
10716 
10717   if (getLangOpts().OpenCL) {
10718     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10719     // initialiser
10720     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10721         !var->hasInit()) {
10722       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10723           << 1 /*Init*/;
10724       var->setInvalidDecl();
10725       return;
10726     }
10727   }
10728 
10729   // In Objective-C, don't allow jumps past the implicit initialization of a
10730   // local retaining variable.
10731   if (getLangOpts().ObjC1 &&
10732       var->hasLocalStorage()) {
10733     switch (var->getType().getObjCLifetime()) {
10734     case Qualifiers::OCL_None:
10735     case Qualifiers::OCL_ExplicitNone:
10736     case Qualifiers::OCL_Autoreleasing:
10737       break;
10738 
10739     case Qualifiers::OCL_Weak:
10740     case Qualifiers::OCL_Strong:
10741       getCurFunction()->setHasBranchProtectedScope();
10742       break;
10743     }
10744   }
10745 
10746   // Warn about externally-visible variables being defined without a
10747   // prior declaration.  We only want to do this for global
10748   // declarations, but we also specifically need to avoid doing it for
10749   // class members because the linkage of an anonymous class can
10750   // change if it's later given a typedef name.
10751   if (var->isThisDeclarationADefinition() &&
10752       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10753       var->isExternallyVisible() && var->hasLinkage() &&
10754       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10755                                   var->getLocation())) {
10756     // Find a previous declaration that's not a definition.
10757     VarDecl *prev = var->getPreviousDecl();
10758     while (prev && prev->isThisDeclarationADefinition())
10759       prev = prev->getPreviousDecl();
10760 
10761     if (!prev)
10762       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10763   }
10764 
10765   // Cache the result of checking for constant initialization.
10766   Optional<bool> CacheHasConstInit;
10767   const Expr *CacheCulprit;
10768   auto checkConstInit = [&]() mutable {
10769     if (!CacheHasConstInit)
10770       CacheHasConstInit = var->getInit()->isConstantInitializer(
10771             Context, var->getType()->isReferenceType(), &CacheCulprit);
10772     return *CacheHasConstInit;
10773   };
10774 
10775   if (var->getTLSKind() == VarDecl::TLS_Static) {
10776     if (var->getType().isDestructedType()) {
10777       // GNU C++98 edits for __thread, [basic.start.term]p3:
10778       //   The type of an object with thread storage duration shall not
10779       //   have a non-trivial destructor.
10780       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10781       if (getLangOpts().CPlusPlus11)
10782         Diag(var->getLocation(), diag::note_use_thread_local);
10783     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10784       if (!checkConstInit()) {
10785         // GNU C++98 edits for __thread, [basic.start.init]p4:
10786         //   An object of thread storage duration shall not require dynamic
10787         //   initialization.
10788         // FIXME: Need strict checking here.
10789         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10790           << CacheCulprit->getSourceRange();
10791         if (getLangOpts().CPlusPlus11)
10792           Diag(var->getLocation(), diag::note_use_thread_local);
10793       }
10794     }
10795   }
10796 
10797   // Apply section attributes and pragmas to global variables.
10798   bool GlobalStorage = var->hasGlobalStorage();
10799   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10800       ActiveTemplateInstantiations.empty()) {
10801     PragmaStack<StringLiteral *> *Stack = nullptr;
10802     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10803     if (var->getType().isConstQualified())
10804       Stack = &ConstSegStack;
10805     else if (!var->getInit()) {
10806       Stack = &BSSSegStack;
10807       SectionFlags |= ASTContext::PSF_Write;
10808     } else {
10809       Stack = &DataSegStack;
10810       SectionFlags |= ASTContext::PSF_Write;
10811     }
10812     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10813       var->addAttr(SectionAttr::CreateImplicit(
10814           Context, SectionAttr::Declspec_allocate,
10815           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10816     }
10817     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10818       if (UnifySection(SA->getName(), SectionFlags, var))
10819         var->dropAttr<SectionAttr>();
10820 
10821     // Apply the init_seg attribute if this has an initializer.  If the
10822     // initializer turns out to not be dynamic, we'll end up ignoring this
10823     // attribute.
10824     if (CurInitSeg && var->getInit())
10825       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10826                                                CurInitSegLoc));
10827   }
10828 
10829   // All the following checks are C++ only.
10830   if (!getLangOpts().CPlusPlus) {
10831       // If this variable must be emitted, add it as an initializer for the
10832       // current module.
10833      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10834        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10835      return;
10836   }
10837 
10838   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10839     CheckCompleteDecompositionDeclaration(DD);
10840 
10841   QualType type = var->getType();
10842   if (type->isDependentType()) return;
10843 
10844   // __block variables might require us to capture a copy-initializer.
10845   if (var->hasAttr<BlocksAttr>()) {
10846     // It's currently invalid to ever have a __block variable with an
10847     // array type; should we diagnose that here?
10848 
10849     // Regardless, we don't want to ignore array nesting when
10850     // constructing this copy.
10851     if (type->isStructureOrClassType()) {
10852       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10853       SourceLocation poi = var->getLocation();
10854       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10855       ExprResult result
10856         = PerformMoveOrCopyInitialization(
10857             InitializedEntity::InitializeBlock(poi, type, false),
10858             var, var->getType(), varRef, /*AllowNRVO=*/true);
10859       if (!result.isInvalid()) {
10860         result = MaybeCreateExprWithCleanups(result);
10861         Expr *init = result.getAs<Expr>();
10862         Context.setBlockVarCopyInits(var, init);
10863       }
10864     }
10865   }
10866 
10867   Expr *Init = var->getInit();
10868   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10869   QualType baseType = Context.getBaseElementType(type);
10870 
10871   if (!var->getDeclContext()->isDependentContext() &&
10872       Init && !Init->isValueDependent()) {
10873 
10874     if (var->isConstexpr()) {
10875       SmallVector<PartialDiagnosticAt, 8> Notes;
10876       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10877         SourceLocation DiagLoc = var->getLocation();
10878         // If the note doesn't add any useful information other than a source
10879         // location, fold it into the primary diagnostic.
10880         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10881               diag::note_invalid_subexpr_in_const_expr) {
10882           DiagLoc = Notes[0].first;
10883           Notes.clear();
10884         }
10885         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10886           << var << Init->getSourceRange();
10887         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10888           Diag(Notes[I].first, Notes[I].second);
10889       }
10890     } else if (var->isUsableInConstantExpressions(Context)) {
10891       // Check whether the initializer of a const variable of integral or
10892       // enumeration type is an ICE now, since we can't tell whether it was
10893       // initialized by a constant expression if we check later.
10894       var->checkInitIsICE();
10895     }
10896 
10897     // Don't emit further diagnostics about constexpr globals since they
10898     // were just diagnosed.
10899     if (!var->isConstexpr() && GlobalStorage &&
10900             var->hasAttr<RequireConstantInitAttr>()) {
10901       // FIXME: Need strict checking in C++03 here.
10902       bool DiagErr = getLangOpts().CPlusPlus11
10903           ? !var->checkInitIsICE() : !checkConstInit();
10904       if (DiagErr) {
10905         auto attr = var->getAttr<RequireConstantInitAttr>();
10906         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10907           << Init->getSourceRange();
10908         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10909           << attr->getRange();
10910       }
10911     }
10912     else if (!var->isConstexpr() && IsGlobal &&
10913              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10914                                     var->getLocation())) {
10915       // Warn about globals which don't have a constant initializer.  Don't
10916       // warn about globals with a non-trivial destructor because we already
10917       // warned about them.
10918       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10919       if (!(RD && !RD->hasTrivialDestructor())) {
10920         if (!checkConstInit())
10921           Diag(var->getLocation(), diag::warn_global_constructor)
10922             << Init->getSourceRange();
10923       }
10924     }
10925   }
10926 
10927   // Require the destructor.
10928   if (const RecordType *recordType = baseType->getAs<RecordType>())
10929     FinalizeVarWithDestructor(var, recordType);
10930 
10931   // If this variable must be emitted, add it as an initializer for the current
10932   // module.
10933   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10934     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10935 }
10936 
10937 /// \brief Determines if a variable's alignment is dependent.
10938 static bool hasDependentAlignment(VarDecl *VD) {
10939   if (VD->getType()->isDependentType())
10940     return true;
10941   for (auto *I : VD->specific_attrs<AlignedAttr>())
10942     if (I->isAlignmentDependent())
10943       return true;
10944   return false;
10945 }
10946 
10947 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10948 /// any semantic actions necessary after any initializer has been attached.
10949 void
10950 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10951   // Note that we are no longer parsing the initializer for this declaration.
10952   ParsingInitForAutoVars.erase(ThisDecl);
10953 
10954   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10955   if (!VD)
10956     return;
10957 
10958   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10959     for (auto *BD : DD->bindings()) {
10960       FinalizeDeclaration(BD);
10961     }
10962   }
10963 
10964   checkAttributesAfterMerging(*this, *VD);
10965 
10966   // Perform TLS alignment check here after attributes attached to the variable
10967   // which may affect the alignment have been processed. Only perform the check
10968   // if the target has a maximum TLS alignment (zero means no constraints).
10969   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10970     // Protect the check so that it's not performed on dependent types and
10971     // dependent alignments (we can't determine the alignment in that case).
10972     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
10973         !VD->isInvalidDecl()) {
10974       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10975       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10976         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10977           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10978           << (unsigned)MaxAlignChars.getQuantity();
10979       }
10980     }
10981   }
10982 
10983   if (VD->isStaticLocal()) {
10984     if (FunctionDecl *FD =
10985             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10986       // Static locals inherit dll attributes from their function.
10987       if (Attr *A = getDLLAttr(FD)) {
10988         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10989         NewAttr->setInherited(true);
10990         VD->addAttr(NewAttr);
10991       }
10992       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10993       // function, only __shared__ variables may be declared with
10994       // static storage class.
10995       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
10996           CUDADiagIfDeviceCode(VD->getLocation(),
10997                                diag::err_device_static_local_var)
10998               << CurrentCUDATarget())
10999         VD->setInvalidDecl();
11000     }
11001   }
11002 
11003   // Perform check for initializers of device-side global variables.
11004   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11005   // 7.5). We must also apply the same checks to all __shared__
11006   // variables whether they are local or not. CUDA also allows
11007   // constant initializers for __constant__ and __device__ variables.
11008   if (getLangOpts().CUDA) {
11009     const Expr *Init = VD->getInit();
11010     if (Init && VD->hasGlobalStorage()) {
11011       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11012           VD->hasAttr<CUDASharedAttr>()) {
11013         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11014         bool AllowedInit = false;
11015         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11016           AllowedInit =
11017               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11018         // We'll allow constant initializers even if it's a non-empty
11019         // constructor according to CUDA rules. This deviates from NVCC,
11020         // but allows us to handle things like constexpr constructors.
11021         if (!AllowedInit &&
11022             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11023           AllowedInit = VD->getInit()->isConstantInitializer(
11024               Context, VD->getType()->isReferenceType());
11025 
11026         // Also make sure that destructor, if there is one, is empty.
11027         if (AllowedInit)
11028           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11029             AllowedInit =
11030                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11031 
11032         if (!AllowedInit) {
11033           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11034                                       ? diag::err_shared_var_init
11035                                       : diag::err_dynamic_var_init)
11036               << Init->getSourceRange();
11037           VD->setInvalidDecl();
11038         }
11039       } else {
11040         // This is a host-side global variable.  Check that the initializer is
11041         // callable from the host side.
11042         const FunctionDecl *InitFn = nullptr;
11043         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11044           InitFn = CE->getConstructor();
11045         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11046           InitFn = CE->getDirectCallee();
11047         }
11048         if (InitFn) {
11049           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11050           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11051             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11052                 << InitFnTarget << InitFn;
11053             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11054             VD->setInvalidDecl();
11055           }
11056         }
11057       }
11058     }
11059   }
11060 
11061   // Grab the dllimport or dllexport attribute off of the VarDecl.
11062   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11063 
11064   // Imported static data members cannot be defined out-of-line.
11065   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11066     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11067         VD->isThisDeclarationADefinition()) {
11068       // We allow definitions of dllimport class template static data members
11069       // with a warning.
11070       CXXRecordDecl *Context =
11071         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11072       bool IsClassTemplateMember =
11073           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11074           Context->getDescribedClassTemplate();
11075 
11076       Diag(VD->getLocation(),
11077            IsClassTemplateMember
11078                ? diag::warn_attribute_dllimport_static_field_definition
11079                : diag::err_attribute_dllimport_static_field_definition);
11080       Diag(IA->getLocation(), diag::note_attribute);
11081       if (!IsClassTemplateMember)
11082         VD->setInvalidDecl();
11083     }
11084   }
11085 
11086   // dllimport/dllexport variables cannot be thread local, their TLS index
11087   // isn't exported with the variable.
11088   if (DLLAttr && VD->getTLSKind()) {
11089     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11090     if (F && getDLLAttr(F)) {
11091       assert(VD->isStaticLocal());
11092       // But if this is a static local in a dlimport/dllexport function, the
11093       // function will never be inlined, which means the var would never be
11094       // imported, so having it marked import/export is safe.
11095     } else {
11096       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11097                                                                     << DLLAttr;
11098       VD->setInvalidDecl();
11099     }
11100   }
11101 
11102   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11103     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11104       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11105       VD->dropAttr<UsedAttr>();
11106     }
11107   }
11108 
11109   const DeclContext *DC = VD->getDeclContext();
11110   // If there's a #pragma GCC visibility in scope, and this isn't a class
11111   // member, set the visibility of this variable.
11112   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11113     AddPushedVisibilityAttribute(VD);
11114 
11115   // FIXME: Warn on unused templates.
11116   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11117       !isa<VarTemplatePartialSpecializationDecl>(VD))
11118     MarkUnusedFileScopedDecl(VD);
11119 
11120   // Now we have parsed the initializer and can update the table of magic
11121   // tag values.
11122   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11123       !VD->getType()->isIntegralOrEnumerationType())
11124     return;
11125 
11126   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11127     const Expr *MagicValueExpr = VD->getInit();
11128     if (!MagicValueExpr) {
11129       continue;
11130     }
11131     llvm::APSInt MagicValueInt;
11132     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11133       Diag(I->getRange().getBegin(),
11134            diag::err_type_tag_for_datatype_not_ice)
11135         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11136       continue;
11137     }
11138     if (MagicValueInt.getActiveBits() > 64) {
11139       Diag(I->getRange().getBegin(),
11140            diag::err_type_tag_for_datatype_too_large)
11141         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11142       continue;
11143     }
11144     uint64_t MagicValue = MagicValueInt.getZExtValue();
11145     RegisterTypeTagForDatatype(I->getArgumentKind(),
11146                                MagicValue,
11147                                I->getMatchingCType(),
11148                                I->getLayoutCompatible(),
11149                                I->getMustBeNull());
11150   }
11151 }
11152 
11153 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11154   auto *VD = dyn_cast<VarDecl>(DD);
11155   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11156 }
11157 
11158 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11159                                                    ArrayRef<Decl *> Group) {
11160   SmallVector<Decl*, 8> Decls;
11161 
11162   if (DS.isTypeSpecOwned())
11163     Decls.push_back(DS.getRepAsDecl());
11164 
11165   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11166   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11167   bool DiagnosedMultipleDecomps = false;
11168   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11169   bool DiagnosedNonDeducedAuto = false;
11170 
11171   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11172     if (Decl *D = Group[i]) {
11173       // For declarators, there are some additional syntactic-ish checks we need
11174       // to perform.
11175       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11176         if (!FirstDeclaratorInGroup)
11177           FirstDeclaratorInGroup = DD;
11178         if (!FirstDecompDeclaratorInGroup)
11179           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11180         if (!FirstNonDeducedAutoInGroup && DS.containsPlaceholderType() &&
11181             !hasDeducedAuto(DD))
11182           FirstNonDeducedAutoInGroup = DD;
11183 
11184         if (FirstDeclaratorInGroup != DD) {
11185           // A decomposition declaration cannot be combined with any other
11186           // declaration in the same group.
11187           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11188             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11189                  diag::err_decomp_decl_not_alone)
11190                 << FirstDeclaratorInGroup->getSourceRange()
11191                 << DD->getSourceRange();
11192             DiagnosedMultipleDecomps = true;
11193           }
11194 
11195           // A declarator that uses 'auto' in any way other than to declare a
11196           // variable with a deduced type cannot be combined with any other
11197           // declarator in the same group.
11198           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11199             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11200                  diag::err_auto_non_deduced_not_alone)
11201                 << FirstNonDeducedAutoInGroup->getType()
11202                        ->hasAutoForTrailingReturnType()
11203                 << FirstDeclaratorInGroup->getSourceRange()
11204                 << DD->getSourceRange();
11205             DiagnosedNonDeducedAuto = true;
11206           }
11207         }
11208       }
11209 
11210       Decls.push_back(D);
11211     }
11212   }
11213 
11214   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11215     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11216       handleTagNumbering(Tag, S);
11217       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11218           getLangOpts().CPlusPlus)
11219         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11220     }
11221   }
11222 
11223   return BuildDeclaratorGroup(Decls);
11224 }
11225 
11226 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11227 /// group, performing any necessary semantic checking.
11228 Sema::DeclGroupPtrTy
11229 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11230   // C++14 [dcl.spec.auto]p7: (DR1347)
11231   //   If the type that replaces the placeholder type is not the same in each
11232   //   deduction, the program is ill-formed.
11233   if (Group.size() > 1) {
11234     QualType Deduced;
11235     VarDecl *DeducedDecl = nullptr;
11236     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11237       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11238       if (!D || D->isInvalidDecl())
11239         break;
11240       AutoType *AT = D->getType()->getContainedAutoType();
11241       if (!AT || AT->getDeducedType().isNull())
11242         continue;
11243       if (Deduced.isNull()) {
11244         Deduced = AT->getDeducedType();
11245         DeducedDecl = D;
11246       } else if (!Context.hasSameType(AT->getDeducedType(), Deduced)) {
11247         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11248              diag::err_auto_different_deductions)
11249           << (unsigned)AT->getKeyword()
11250           << Deduced << DeducedDecl->getDeclName()
11251           << AT->getDeducedType() << D->getDeclName()
11252           << DeducedDecl->getInit()->getSourceRange()
11253           << D->getInit()->getSourceRange();
11254         D->setInvalidDecl();
11255         break;
11256       }
11257     }
11258   }
11259 
11260   ActOnDocumentableDecls(Group);
11261 
11262   return DeclGroupPtrTy::make(
11263       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11264 }
11265 
11266 void Sema::ActOnDocumentableDecl(Decl *D) {
11267   ActOnDocumentableDecls(D);
11268 }
11269 
11270 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11271   // Don't parse the comment if Doxygen diagnostics are ignored.
11272   if (Group.empty() || !Group[0])
11273     return;
11274 
11275   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11276                       Group[0]->getLocation()) &&
11277       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11278                       Group[0]->getLocation()))
11279     return;
11280 
11281   if (Group.size() >= 2) {
11282     // This is a decl group.  Normally it will contain only declarations
11283     // produced from declarator list.  But in case we have any definitions or
11284     // additional declaration references:
11285     //   'typedef struct S {} S;'
11286     //   'typedef struct S *S;'
11287     //   'struct S *pS;'
11288     // FinalizeDeclaratorGroup adds these as separate declarations.
11289     Decl *MaybeTagDecl = Group[0];
11290     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11291       Group = Group.slice(1);
11292     }
11293   }
11294 
11295   // See if there are any new comments that are not attached to a decl.
11296   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11297   if (!Comments.empty() &&
11298       !Comments.back()->isAttached()) {
11299     // There is at least one comment that not attached to a decl.
11300     // Maybe it should be attached to one of these decls?
11301     //
11302     // Note that this way we pick up not only comments that precede the
11303     // declaration, but also comments that *follow* the declaration -- thanks to
11304     // the lookahead in the lexer: we've consumed the semicolon and looked
11305     // ahead through comments.
11306     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11307       Context.getCommentForDecl(Group[i], &PP);
11308   }
11309 }
11310 
11311 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11312 /// to introduce parameters into function prototype scope.
11313 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11314   const DeclSpec &DS = D.getDeclSpec();
11315 
11316   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11317 
11318   // C++03 [dcl.stc]p2 also permits 'auto'.
11319   StorageClass SC = SC_None;
11320   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11321     SC = SC_Register;
11322   } else if (getLangOpts().CPlusPlus &&
11323              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11324     SC = SC_Auto;
11325   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11326     Diag(DS.getStorageClassSpecLoc(),
11327          diag::err_invalid_storage_class_in_func_decl);
11328     D.getMutableDeclSpec().ClearStorageClassSpecs();
11329   }
11330 
11331   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11332     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11333       << DeclSpec::getSpecifierName(TSCS);
11334   if (DS.isInlineSpecified())
11335     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11336         << getLangOpts().CPlusPlus1z;
11337   if (DS.isConstexprSpecified())
11338     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11339       << 0;
11340   if (DS.isConceptSpecified())
11341     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11342 
11343   DiagnoseFunctionSpecifiers(DS);
11344 
11345   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11346   QualType parmDeclType = TInfo->getType();
11347 
11348   if (getLangOpts().CPlusPlus) {
11349     // Check that there are no default arguments inside the type of this
11350     // parameter.
11351     CheckExtraCXXDefaultArguments(D);
11352 
11353     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11354     if (D.getCXXScopeSpec().isSet()) {
11355       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11356         << D.getCXXScopeSpec().getRange();
11357       D.getCXXScopeSpec().clear();
11358     }
11359   }
11360 
11361   // Ensure we have a valid name
11362   IdentifierInfo *II = nullptr;
11363   if (D.hasName()) {
11364     II = D.getIdentifier();
11365     if (!II) {
11366       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11367         << GetNameForDeclarator(D).getName();
11368       D.setInvalidType(true);
11369     }
11370   }
11371 
11372   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11373   if (II) {
11374     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11375                    ForRedeclaration);
11376     LookupName(R, S);
11377     if (R.isSingleResult()) {
11378       NamedDecl *PrevDecl = R.getFoundDecl();
11379       if (PrevDecl->isTemplateParameter()) {
11380         // Maybe we will complain about the shadowed template parameter.
11381         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11382         // Just pretend that we didn't see the previous declaration.
11383         PrevDecl = nullptr;
11384       } else if (S->isDeclScope(PrevDecl)) {
11385         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11386         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11387 
11388         // Recover by removing the name
11389         II = nullptr;
11390         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11391         D.setInvalidType(true);
11392       }
11393     }
11394   }
11395 
11396   // Temporarily put parameter variables in the translation unit, not
11397   // the enclosing context.  This prevents them from accidentally
11398   // looking like class members in C++.
11399   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11400                                     D.getLocStart(),
11401                                     D.getIdentifierLoc(), II,
11402                                     parmDeclType, TInfo,
11403                                     SC);
11404 
11405   if (D.isInvalidType())
11406     New->setInvalidDecl();
11407 
11408   assert(S->isFunctionPrototypeScope());
11409   assert(S->getFunctionPrototypeDepth() >= 1);
11410   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11411                     S->getNextFunctionPrototypeIndex());
11412 
11413   // Add the parameter declaration into this scope.
11414   S->AddDecl(New);
11415   if (II)
11416     IdResolver.AddDecl(New);
11417 
11418   ProcessDeclAttributes(S, New, D);
11419 
11420   if (D.getDeclSpec().isModulePrivateSpecified())
11421     Diag(New->getLocation(), diag::err_module_private_local)
11422       << 1 << New->getDeclName()
11423       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11424       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11425 
11426   if (New->hasAttr<BlocksAttr>()) {
11427     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11428   }
11429   return New;
11430 }
11431 
11432 /// \brief Synthesizes a variable for a parameter arising from a
11433 /// typedef.
11434 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11435                                               SourceLocation Loc,
11436                                               QualType T) {
11437   /* FIXME: setting StartLoc == Loc.
11438      Would it be worth to modify callers so as to provide proper source
11439      location for the unnamed parameters, embedding the parameter's type? */
11440   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11441                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11442                                            SC_None, nullptr);
11443   Param->setImplicit();
11444   return Param;
11445 }
11446 
11447 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11448   // Don't diagnose unused-parameter errors in template instantiations; we
11449   // will already have done so in the template itself.
11450   if (!ActiveTemplateInstantiations.empty())
11451     return;
11452 
11453   for (const ParmVarDecl *Parameter : Parameters) {
11454     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11455         !Parameter->hasAttr<UnusedAttr>()) {
11456       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11457         << Parameter->getDeclName();
11458     }
11459   }
11460 }
11461 
11462 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11463     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11464   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11465     return;
11466 
11467   // Warn if the return value is pass-by-value and larger than the specified
11468   // threshold.
11469   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11470     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11471     if (Size > LangOpts.NumLargeByValueCopy)
11472       Diag(D->getLocation(), diag::warn_return_value_size)
11473           << D->getDeclName() << Size;
11474   }
11475 
11476   // Warn if any parameter is pass-by-value and larger than the specified
11477   // threshold.
11478   for (const ParmVarDecl *Parameter : Parameters) {
11479     QualType T = Parameter->getType();
11480     if (T->isDependentType() || !T.isPODType(Context))
11481       continue;
11482     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11483     if (Size > LangOpts.NumLargeByValueCopy)
11484       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11485           << Parameter->getDeclName() << Size;
11486   }
11487 }
11488 
11489 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11490                                   SourceLocation NameLoc, IdentifierInfo *Name,
11491                                   QualType T, TypeSourceInfo *TSInfo,
11492                                   StorageClass SC) {
11493   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11494   if (getLangOpts().ObjCAutoRefCount &&
11495       T.getObjCLifetime() == Qualifiers::OCL_None &&
11496       T->isObjCLifetimeType()) {
11497 
11498     Qualifiers::ObjCLifetime lifetime;
11499 
11500     // Special cases for arrays:
11501     //   - if it's const, use __unsafe_unretained
11502     //   - otherwise, it's an error
11503     if (T->isArrayType()) {
11504       if (!T.isConstQualified()) {
11505         DelayedDiagnostics.add(
11506             sema::DelayedDiagnostic::makeForbiddenType(
11507             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11508       }
11509       lifetime = Qualifiers::OCL_ExplicitNone;
11510     } else {
11511       lifetime = T->getObjCARCImplicitLifetime();
11512     }
11513     T = Context.getLifetimeQualifiedType(T, lifetime);
11514   }
11515 
11516   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11517                                          Context.getAdjustedParameterType(T),
11518                                          TSInfo, SC, nullptr);
11519 
11520   // Parameters can not be abstract class types.
11521   // For record types, this is done by the AbstractClassUsageDiagnoser once
11522   // the class has been completely parsed.
11523   if (!CurContext->isRecord() &&
11524       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11525                              AbstractParamType))
11526     New->setInvalidDecl();
11527 
11528   // Parameter declarators cannot be interface types. All ObjC objects are
11529   // passed by reference.
11530   if (T->isObjCObjectType()) {
11531     SourceLocation TypeEndLoc =
11532         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11533     Diag(NameLoc,
11534          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11535       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11536     T = Context.getObjCObjectPointerType(T);
11537     New->setType(T);
11538   }
11539 
11540   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11541   // duration shall not be qualified by an address-space qualifier."
11542   // Since all parameters have automatic store duration, they can not have
11543   // an address space.
11544   if (T.getAddressSpace() != 0) {
11545     // OpenCL allows function arguments declared to be an array of a type
11546     // to be qualified with an address space.
11547     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11548       Diag(NameLoc, diag::err_arg_with_address_space);
11549       New->setInvalidDecl();
11550     }
11551   }
11552 
11553   return New;
11554 }
11555 
11556 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11557                                            SourceLocation LocAfterDecls) {
11558   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11559 
11560   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11561   // for a K&R function.
11562   if (!FTI.hasPrototype) {
11563     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11564       --i;
11565       if (FTI.Params[i].Param == nullptr) {
11566         SmallString<256> Code;
11567         llvm::raw_svector_ostream(Code)
11568             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11569         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11570             << FTI.Params[i].Ident
11571             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11572 
11573         // Implicitly declare the argument as type 'int' for lack of a better
11574         // type.
11575         AttributeFactory attrs;
11576         DeclSpec DS(attrs);
11577         const char* PrevSpec; // unused
11578         unsigned DiagID; // unused
11579         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11580                            DiagID, Context.getPrintingPolicy());
11581         // Use the identifier location for the type source range.
11582         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11583         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11584         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11585         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11586         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11587       }
11588     }
11589   }
11590 }
11591 
11592 Decl *
11593 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11594                               MultiTemplateParamsArg TemplateParameterLists,
11595                               SkipBodyInfo *SkipBody) {
11596   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11597   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11598   Scope *ParentScope = FnBodyScope->getParent();
11599 
11600   D.setFunctionDefinitionKind(FDK_Definition);
11601   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11602   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11603 }
11604 
11605 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11606   Consumer.HandleInlineFunctionDefinition(D);
11607 }
11608 
11609 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11610                              const FunctionDecl*& PossibleZeroParamPrototype) {
11611   // Don't warn about invalid declarations.
11612   if (FD->isInvalidDecl())
11613     return false;
11614 
11615   // Or declarations that aren't global.
11616   if (!FD->isGlobal())
11617     return false;
11618 
11619   // Don't warn about C++ member functions.
11620   if (isa<CXXMethodDecl>(FD))
11621     return false;
11622 
11623   // Don't warn about 'main'.
11624   if (FD->isMain())
11625     return false;
11626 
11627   // Don't warn about inline functions.
11628   if (FD->isInlined())
11629     return false;
11630 
11631   // Don't warn about function templates.
11632   if (FD->getDescribedFunctionTemplate())
11633     return false;
11634 
11635   // Don't warn about function template specializations.
11636   if (FD->isFunctionTemplateSpecialization())
11637     return false;
11638 
11639   // Don't warn for OpenCL kernels.
11640   if (FD->hasAttr<OpenCLKernelAttr>())
11641     return false;
11642 
11643   // Don't warn on explicitly deleted functions.
11644   if (FD->isDeleted())
11645     return false;
11646 
11647   bool MissingPrototype = true;
11648   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11649        Prev; Prev = Prev->getPreviousDecl()) {
11650     // Ignore any declarations that occur in function or method
11651     // scope, because they aren't visible from the header.
11652     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11653       continue;
11654 
11655     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11656     if (FD->getNumParams() == 0)
11657       PossibleZeroParamPrototype = Prev;
11658     break;
11659   }
11660 
11661   return MissingPrototype;
11662 }
11663 
11664 void
11665 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11666                                    const FunctionDecl *EffectiveDefinition,
11667                                    SkipBodyInfo *SkipBody) {
11668   // Don't complain if we're in GNU89 mode and the previous definition
11669   // was an extern inline function.
11670   const FunctionDecl *Definition = EffectiveDefinition;
11671   if (!Definition)
11672     if (!FD->isDefined(Definition))
11673       return;
11674 
11675   if (canRedefineFunction(Definition, getLangOpts()))
11676     return;
11677 
11678   // If we don't have a visible definition of the function, and it's inline or
11679   // a template, skip the new definition.
11680   if (SkipBody && !hasVisibleDefinition(Definition) &&
11681       (Definition->getFormalLinkage() == InternalLinkage ||
11682        Definition->isInlined() ||
11683        Definition->getDescribedFunctionTemplate() ||
11684        Definition->getNumTemplateParameterLists())) {
11685     SkipBody->ShouldSkip = true;
11686     if (auto *TD = Definition->getDescribedFunctionTemplate())
11687       makeMergedDefinitionVisible(TD, FD->getLocation());
11688     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11689                                 FD->getLocation());
11690     return;
11691   }
11692 
11693   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11694       Definition->getStorageClass() == SC_Extern)
11695     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11696         << FD->getDeclName() << getLangOpts().CPlusPlus;
11697   else
11698     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11699 
11700   Diag(Definition->getLocation(), diag::note_previous_definition);
11701   FD->setInvalidDecl();
11702 }
11703 
11704 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11705                                    Sema &S) {
11706   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11707 
11708   LambdaScopeInfo *LSI = S.PushLambdaScope();
11709   LSI->CallOperator = CallOperator;
11710   LSI->Lambda = LambdaClass;
11711   LSI->ReturnType = CallOperator->getReturnType();
11712   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11713 
11714   if (LCD == LCD_None)
11715     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11716   else if (LCD == LCD_ByCopy)
11717     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11718   else if (LCD == LCD_ByRef)
11719     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11720   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11721 
11722   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11723   LSI->Mutable = !CallOperator->isConst();
11724 
11725   // Add the captures to the LSI so they can be noted as already
11726   // captured within tryCaptureVar.
11727   auto I = LambdaClass->field_begin();
11728   for (const auto &C : LambdaClass->captures()) {
11729     if (C.capturesVariable()) {
11730       VarDecl *VD = C.getCapturedVar();
11731       if (VD->isInitCapture())
11732         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11733       QualType CaptureType = VD->getType();
11734       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11735       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11736           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11737           /*EllipsisLoc*/C.isPackExpansion()
11738                          ? C.getEllipsisLoc() : SourceLocation(),
11739           CaptureType, /*Expr*/ nullptr);
11740 
11741     } else if (C.capturesThis()) {
11742       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11743                               /*Expr*/ nullptr,
11744                               C.getCaptureKind() == LCK_StarThis);
11745     } else {
11746       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11747     }
11748     ++I;
11749   }
11750 }
11751 
11752 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11753                                     SkipBodyInfo *SkipBody) {
11754   // Clear the last template instantiation error context.
11755   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11756 
11757   if (!D)
11758     return D;
11759   FunctionDecl *FD = nullptr;
11760 
11761   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11762     FD = FunTmpl->getTemplatedDecl();
11763   else
11764     FD = cast<FunctionDecl>(D);
11765 
11766   // See if this is a redefinition.
11767   if (!FD->isLateTemplateParsed()) {
11768     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11769 
11770     // If we're skipping the body, we're done. Don't enter the scope.
11771     if (SkipBody && SkipBody->ShouldSkip)
11772       return D;
11773   }
11774 
11775   // Mark this function as "will have a body eventually".  This lets users to
11776   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11777   // this function.
11778   FD->setWillHaveBody();
11779 
11780   // If we are instantiating a generic lambda call operator, push
11781   // a LambdaScopeInfo onto the function stack.  But use the information
11782   // that's already been calculated (ActOnLambdaExpr) to prime the current
11783   // LambdaScopeInfo.
11784   // When the template operator is being specialized, the LambdaScopeInfo,
11785   // has to be properly restored so that tryCaptureVariable doesn't try
11786   // and capture any new variables. In addition when calculating potential
11787   // captures during transformation of nested lambdas, it is necessary to
11788   // have the LSI properly restored.
11789   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11790     assert(ActiveTemplateInstantiations.size() &&
11791       "There should be an active template instantiation on the stack "
11792       "when instantiating a generic lambda!");
11793     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11794   }
11795   else
11796     // Enter a new function scope
11797     PushFunctionScope();
11798 
11799   // Builtin functions cannot be defined.
11800   if (unsigned BuiltinID = FD->getBuiltinID()) {
11801     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11802         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11803       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11804       FD->setInvalidDecl();
11805     }
11806   }
11807 
11808   // The return type of a function definition must be complete
11809   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11810   QualType ResultType = FD->getReturnType();
11811   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11812       !FD->isInvalidDecl() &&
11813       RequireCompleteType(FD->getLocation(), ResultType,
11814                           diag::err_func_def_incomplete_result))
11815     FD->setInvalidDecl();
11816 
11817   if (FnBodyScope)
11818     PushDeclContext(FnBodyScope, FD);
11819 
11820   // Check the validity of our function parameters
11821   CheckParmsForFunctionDef(FD->parameters(),
11822                            /*CheckParameterNames=*/true);
11823 
11824   // Add non-parameter declarations already in the function to the current
11825   // scope.
11826   if (FnBodyScope) {
11827     for (Decl *NPD : FD->decls()) {
11828       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11829       if (!NonParmDecl)
11830         continue;
11831       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11832              "parameters should not be in newly created FD yet");
11833 
11834       // If the decl has a name, make it accessible in the current scope.
11835       if (NonParmDecl->getDeclName())
11836         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11837 
11838       // Similarly, dive into enums and fish their constants out, making them
11839       // accessible in this scope.
11840       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11841         for (auto *EI : ED->enumerators())
11842           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11843       }
11844     }
11845   }
11846 
11847   // Introduce our parameters into the function scope
11848   for (auto Param : FD->parameters()) {
11849     Param->setOwningFunction(FD);
11850 
11851     // If this has an identifier, add it to the scope stack.
11852     if (Param->getIdentifier() && FnBodyScope) {
11853       CheckShadow(FnBodyScope, Param);
11854 
11855       PushOnScopeChains(Param, FnBodyScope);
11856     }
11857   }
11858 
11859   // Ensure that the function's exception specification is instantiated.
11860   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11861     ResolveExceptionSpec(D->getLocation(), FPT);
11862 
11863   // dllimport cannot be applied to non-inline function definitions.
11864   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11865       !FD->isTemplateInstantiation()) {
11866     assert(!FD->hasAttr<DLLExportAttr>());
11867     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11868     FD->setInvalidDecl();
11869     return D;
11870   }
11871   // We want to attach documentation to original Decl (which might be
11872   // a function template).
11873   ActOnDocumentableDecl(D);
11874   if (getCurLexicalContext()->isObjCContainer() &&
11875       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11876       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11877     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11878 
11879   return D;
11880 }
11881 
11882 /// \brief Given the set of return statements within a function body,
11883 /// compute the variables that are subject to the named return value
11884 /// optimization.
11885 ///
11886 /// Each of the variables that is subject to the named return value
11887 /// optimization will be marked as NRVO variables in the AST, and any
11888 /// return statement that has a marked NRVO variable as its NRVO candidate can
11889 /// use the named return value optimization.
11890 ///
11891 /// This function applies a very simplistic algorithm for NRVO: if every return
11892 /// statement in the scope of a variable has the same NRVO candidate, that
11893 /// candidate is an NRVO variable.
11894 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11895   ReturnStmt **Returns = Scope->Returns.data();
11896 
11897   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11898     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11899       if (!NRVOCandidate->isNRVOVariable())
11900         Returns[I]->setNRVOCandidate(nullptr);
11901     }
11902   }
11903 }
11904 
11905 bool Sema::canDelayFunctionBody(const Declarator &D) {
11906   // We can't delay parsing the body of a constexpr function template (yet).
11907   if (D.getDeclSpec().isConstexprSpecified())
11908     return false;
11909 
11910   // We can't delay parsing the body of a function template with a deduced
11911   // return type (yet).
11912   if (D.getDeclSpec().containsPlaceholderType()) {
11913     // If the placeholder introduces a non-deduced trailing return type,
11914     // we can still delay parsing it.
11915     if (D.getNumTypeObjects()) {
11916       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11917       if (Outer.Kind == DeclaratorChunk::Function &&
11918           Outer.Fun.hasTrailingReturnType()) {
11919         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11920         return Ty.isNull() || !Ty->isUndeducedType();
11921       }
11922     }
11923     return false;
11924   }
11925 
11926   return true;
11927 }
11928 
11929 bool Sema::canSkipFunctionBody(Decl *D) {
11930   // We cannot skip the body of a function (or function template) which is
11931   // constexpr, since we may need to evaluate its body in order to parse the
11932   // rest of the file.
11933   // We cannot skip the body of a function with an undeduced return type,
11934   // because any callers of that function need to know the type.
11935   if (const FunctionDecl *FD = D->getAsFunction())
11936     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11937       return false;
11938   return Consumer.shouldSkipFunctionBody(D);
11939 }
11940 
11941 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11942   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11943     FD->setHasSkippedBody();
11944   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11945     MD->setHasSkippedBody();
11946   return Decl;
11947 }
11948 
11949 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11950   return ActOnFinishFunctionBody(D, BodyArg, false);
11951 }
11952 
11953 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11954                                     bool IsInstantiation) {
11955   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11956 
11957   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11958   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11959 
11960   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11961     CheckCompletedCoroutineBody(FD, Body);
11962 
11963   if (FD) {
11964     FD->setBody(Body);
11965 
11966     if (getLangOpts().CPlusPlus14) {
11967       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11968           FD->getReturnType()->isUndeducedType()) {
11969         // If the function has a deduced result type but contains no 'return'
11970         // statements, the result type as written must be exactly 'auto', and
11971         // the deduced result type is 'void'.
11972         if (!FD->getReturnType()->getAs<AutoType>()) {
11973           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11974               << FD->getReturnType();
11975           FD->setInvalidDecl();
11976         } else {
11977           // Substitute 'void' for the 'auto' in the type.
11978           TypeLoc ResultType = getReturnTypeLoc(FD);
11979           Context.adjustDeducedFunctionResultType(
11980               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11981         }
11982       }
11983     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11984       // In C++11, we don't use 'auto' deduction rules for lambda call
11985       // operators because we don't support return type deduction.
11986       auto *LSI = getCurLambda();
11987       if (LSI->HasImplicitReturnType) {
11988         deduceClosureReturnType(*LSI);
11989 
11990         // C++11 [expr.prim.lambda]p4:
11991         //   [...] if there are no return statements in the compound-statement
11992         //   [the deduced type is] the type void
11993         QualType RetType =
11994             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11995 
11996         // Update the return type to the deduced type.
11997         const FunctionProtoType *Proto =
11998             FD->getType()->getAs<FunctionProtoType>();
11999         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12000                                             Proto->getExtProtoInfo()));
12001       }
12002     }
12003 
12004     // The only way to be included in UndefinedButUsed is if there is an
12005     // ODR use before the definition. Avoid the expensive map lookup if this
12006     // is the first declaration.
12007     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12008       if (!FD->isExternallyVisible())
12009         UndefinedButUsed.erase(FD);
12010       else if (FD->isInlined() &&
12011                !LangOpts.GNUInline &&
12012                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12013         UndefinedButUsed.erase(FD);
12014     }
12015 
12016     // If the function implicitly returns zero (like 'main') or is naked,
12017     // don't complain about missing return statements.
12018     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12019       WP.disableCheckFallThrough();
12020 
12021     // MSVC permits the use of pure specifier (=0) on function definition,
12022     // defined at class scope, warn about this non-standard construct.
12023     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12024       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12025 
12026     if (!FD->isInvalidDecl()) {
12027       // Don't diagnose unused parameters of defaulted or deleted functions.
12028       if (!FD->isDeleted() && !FD->isDefaulted())
12029         DiagnoseUnusedParameters(FD->parameters());
12030       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12031                                              FD->getReturnType(), FD);
12032 
12033       // If this is a structor, we need a vtable.
12034       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12035         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12036       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12037         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12038 
12039       // Try to apply the named return value optimization. We have to check
12040       // if we can do this here because lambdas keep return statements around
12041       // to deduce an implicit return type.
12042       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12043           !FD->isDependentContext())
12044         computeNRVO(Body, getCurFunction());
12045     }
12046 
12047     // GNU warning -Wmissing-prototypes:
12048     //   Warn if a global function is defined without a previous
12049     //   prototype declaration. This warning is issued even if the
12050     //   definition itself provides a prototype. The aim is to detect
12051     //   global functions that fail to be declared in header files.
12052     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12053     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12054       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12055 
12056       if (PossibleZeroParamPrototype) {
12057         // We found a declaration that is not a prototype,
12058         // but that could be a zero-parameter prototype
12059         if (TypeSourceInfo *TI =
12060                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12061           TypeLoc TL = TI->getTypeLoc();
12062           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12063             Diag(PossibleZeroParamPrototype->getLocation(),
12064                  diag::note_declaration_not_a_prototype)
12065                 << PossibleZeroParamPrototype
12066                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12067         }
12068       }
12069 
12070       // GNU warning -Wstrict-prototypes
12071       //   Warn if K&R function is defined without a previous declaration.
12072       //   This warning is issued only if the definition itself does not provide
12073       //   a prototype. Only K&R definitions do not provide a prototype.
12074       //   An empty list in a function declarator that is part of a definition
12075       //   of that function specifies that the function has no parameters
12076       //   (C99 6.7.5.3p14)
12077       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12078           !LangOpts.CPlusPlus) {
12079         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12080         TypeLoc TL = TI->getTypeLoc();
12081         FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>();
12082         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12083       }
12084     }
12085 
12086     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12087       const CXXMethodDecl *KeyFunction;
12088       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12089           MD->isVirtual() &&
12090           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12091           MD == KeyFunction->getCanonicalDecl()) {
12092         // Update the key-function state if necessary for this ABI.
12093         if (FD->isInlined() &&
12094             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12095           Context.setNonKeyFunction(MD);
12096 
12097           // If the newly-chosen key function is already defined, then we
12098           // need to mark the vtable as used retroactively.
12099           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12100           const FunctionDecl *Definition;
12101           if (KeyFunction && KeyFunction->isDefined(Definition))
12102             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12103         } else {
12104           // We just defined they key function; mark the vtable as used.
12105           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12106         }
12107       }
12108     }
12109 
12110     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12111            "Function parsing confused");
12112   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12113     assert(MD == getCurMethodDecl() && "Method parsing confused");
12114     MD->setBody(Body);
12115     if (!MD->isInvalidDecl()) {
12116       DiagnoseUnusedParameters(MD->parameters());
12117       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12118                                              MD->getReturnType(), MD);
12119 
12120       if (Body)
12121         computeNRVO(Body, getCurFunction());
12122     }
12123     if (getCurFunction()->ObjCShouldCallSuper) {
12124       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12125         << MD->getSelector().getAsString();
12126       getCurFunction()->ObjCShouldCallSuper = false;
12127     }
12128     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12129       const ObjCMethodDecl *InitMethod = nullptr;
12130       bool isDesignated =
12131           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12132       assert(isDesignated && InitMethod);
12133       (void)isDesignated;
12134 
12135       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12136         auto IFace = MD->getClassInterface();
12137         if (!IFace)
12138           return false;
12139         auto SuperD = IFace->getSuperClass();
12140         if (!SuperD)
12141           return false;
12142         return SuperD->getIdentifier() ==
12143             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12144       };
12145       // Don't issue this warning for unavailable inits or direct subclasses
12146       // of NSObject.
12147       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12148         Diag(MD->getLocation(),
12149              diag::warn_objc_designated_init_missing_super_call);
12150         Diag(InitMethod->getLocation(),
12151              diag::note_objc_designated_init_marked_here);
12152       }
12153       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12154     }
12155     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12156       // Don't issue this warning for unavaialable inits.
12157       if (!MD->isUnavailable())
12158         Diag(MD->getLocation(),
12159              diag::warn_objc_secondary_init_missing_init_call);
12160       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12161     }
12162   } else {
12163     return nullptr;
12164   }
12165 
12166   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12167     DiagnoseUnguardedAvailabilityViolations(dcl);
12168 
12169   assert(!getCurFunction()->ObjCShouldCallSuper &&
12170          "This should only be set for ObjC methods, which should have been "
12171          "handled in the block above.");
12172 
12173   // Verify and clean out per-function state.
12174   if (Body && (!FD || !FD->isDefaulted())) {
12175     // C++ constructors that have function-try-blocks can't have return
12176     // statements in the handlers of that block. (C++ [except.handle]p14)
12177     // Verify this.
12178     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12179       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12180 
12181     // Verify that gotos and switch cases don't jump into scopes illegally.
12182     if (getCurFunction()->NeedsScopeChecking() &&
12183         !PP.isCodeCompletionEnabled())
12184       DiagnoseInvalidJumps(Body);
12185 
12186     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12187       if (!Destructor->getParent()->isDependentType())
12188         CheckDestructor(Destructor);
12189 
12190       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12191                                              Destructor->getParent());
12192     }
12193 
12194     // If any errors have occurred, clear out any temporaries that may have
12195     // been leftover. This ensures that these temporaries won't be picked up for
12196     // deletion in some later function.
12197     if (getDiagnostics().hasErrorOccurred() ||
12198         getDiagnostics().getSuppressAllDiagnostics()) {
12199       DiscardCleanupsInEvaluationContext();
12200     }
12201     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12202         !isa<FunctionTemplateDecl>(dcl)) {
12203       // Since the body is valid, issue any analysis-based warnings that are
12204       // enabled.
12205       ActivePolicy = &WP;
12206     }
12207 
12208     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12209         (!CheckConstexprFunctionDecl(FD) ||
12210          !CheckConstexprFunctionBody(FD, Body)))
12211       FD->setInvalidDecl();
12212 
12213     if (FD && FD->hasAttr<NakedAttr>()) {
12214       for (const Stmt *S : Body->children()) {
12215         // Allow local register variables without initializer as they don't
12216         // require prologue.
12217         bool RegisterVariables = false;
12218         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12219           for (const auto *Decl : DS->decls()) {
12220             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12221               RegisterVariables =
12222                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12223               if (!RegisterVariables)
12224                 break;
12225             }
12226           }
12227         }
12228         if (RegisterVariables)
12229           continue;
12230         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12231           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12232           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12233           FD->setInvalidDecl();
12234           break;
12235         }
12236       }
12237     }
12238 
12239     assert(ExprCleanupObjects.size() ==
12240                ExprEvalContexts.back().NumCleanupObjects &&
12241            "Leftover temporaries in function");
12242     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12243     assert(MaybeODRUseExprs.empty() &&
12244            "Leftover expressions for odr-use checking");
12245   }
12246 
12247   if (!IsInstantiation)
12248     PopDeclContext();
12249 
12250   PopFunctionScopeInfo(ActivePolicy, dcl);
12251   // If any errors have occurred, clear out any temporaries that may have
12252   // been leftover. This ensures that these temporaries won't be picked up for
12253   // deletion in some later function.
12254   if (getDiagnostics().hasErrorOccurred()) {
12255     DiscardCleanupsInEvaluationContext();
12256   }
12257 
12258   return dcl;
12259 }
12260 
12261 /// When we finish delayed parsing of an attribute, we must attach it to the
12262 /// relevant Decl.
12263 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12264                                        ParsedAttributes &Attrs) {
12265   // Always attach attributes to the underlying decl.
12266   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12267     D = TD->getTemplatedDecl();
12268   ProcessDeclAttributeList(S, D, Attrs.getList());
12269 
12270   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12271     if (Method->isStatic())
12272       checkThisInStaticMemberFunctionAttributes(Method);
12273 }
12274 
12275 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12276 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12277 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12278                                           IdentifierInfo &II, Scope *S) {
12279   // Before we produce a declaration for an implicitly defined
12280   // function, see whether there was a locally-scoped declaration of
12281   // this name as a function or variable. If so, use that
12282   // (non-visible) declaration, and complain about it.
12283   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12284     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12285     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12286     return ExternCPrev;
12287   }
12288 
12289   // Extension in C99.  Legal in C90, but warn about it.
12290   unsigned diag_id;
12291   if (II.getName().startswith("__builtin_"))
12292     diag_id = diag::warn_builtin_unknown;
12293   else if (getLangOpts().C99)
12294     diag_id = diag::ext_implicit_function_decl;
12295   else
12296     diag_id = diag::warn_implicit_function_decl;
12297   Diag(Loc, diag_id) << &II;
12298 
12299   // Because typo correction is expensive, only do it if the implicit
12300   // function declaration is going to be treated as an error.
12301   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12302     TypoCorrection Corrected;
12303     if (S &&
12304         (Corrected = CorrectTypo(
12305              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12306              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12307       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12308                    /*ErrorRecovery*/false);
12309   }
12310 
12311   // Set a Declarator for the implicit definition: int foo();
12312   const char *Dummy;
12313   AttributeFactory attrFactory;
12314   DeclSpec DS(attrFactory);
12315   unsigned DiagID;
12316   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12317                                   Context.getPrintingPolicy());
12318   (void)Error; // Silence warning.
12319   assert(!Error && "Error setting up implicit decl!");
12320   SourceLocation NoLoc;
12321   Declarator D(DS, Declarator::BlockContext);
12322   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12323                                              /*IsAmbiguous=*/false,
12324                                              /*LParenLoc=*/NoLoc,
12325                                              /*Params=*/nullptr,
12326                                              /*NumParams=*/0,
12327                                              /*EllipsisLoc=*/NoLoc,
12328                                              /*RParenLoc=*/NoLoc,
12329                                              /*TypeQuals=*/0,
12330                                              /*RefQualifierIsLvalueRef=*/true,
12331                                              /*RefQualifierLoc=*/NoLoc,
12332                                              /*ConstQualifierLoc=*/NoLoc,
12333                                              /*VolatileQualifierLoc=*/NoLoc,
12334                                              /*RestrictQualifierLoc=*/NoLoc,
12335                                              /*MutableLoc=*/NoLoc,
12336                                              EST_None,
12337                                              /*ESpecRange=*/SourceRange(),
12338                                              /*Exceptions=*/nullptr,
12339                                              /*ExceptionRanges=*/nullptr,
12340                                              /*NumExceptions=*/0,
12341                                              /*NoexceptExpr=*/nullptr,
12342                                              /*ExceptionSpecTokens=*/nullptr,
12343                                              /*DeclsInPrototype=*/None,
12344                                              Loc, Loc, D),
12345                 DS.getAttributes(),
12346                 SourceLocation());
12347   D.SetIdentifier(&II, Loc);
12348 
12349   // Insert this function into translation-unit scope.
12350 
12351   DeclContext *PrevDC = CurContext;
12352   CurContext = Context.getTranslationUnitDecl();
12353 
12354   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12355   FD->setImplicit();
12356 
12357   CurContext = PrevDC;
12358 
12359   AddKnownFunctionAttributes(FD);
12360 
12361   return FD;
12362 }
12363 
12364 /// \brief Adds any function attributes that we know a priori based on
12365 /// the declaration of this function.
12366 ///
12367 /// These attributes can apply both to implicitly-declared builtins
12368 /// (like __builtin___printf_chk) or to library-declared functions
12369 /// like NSLog or printf.
12370 ///
12371 /// We need to check for duplicate attributes both here and where user-written
12372 /// attributes are applied to declarations.
12373 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12374   if (FD->isInvalidDecl())
12375     return;
12376 
12377   // If this is a built-in function, map its builtin attributes to
12378   // actual attributes.
12379   if (unsigned BuiltinID = FD->getBuiltinID()) {
12380     // Handle printf-formatting attributes.
12381     unsigned FormatIdx;
12382     bool HasVAListArg;
12383     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12384       if (!FD->hasAttr<FormatAttr>()) {
12385         const char *fmt = "printf";
12386         unsigned int NumParams = FD->getNumParams();
12387         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12388             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12389           fmt = "NSString";
12390         FD->addAttr(FormatAttr::CreateImplicit(Context,
12391                                                &Context.Idents.get(fmt),
12392                                                FormatIdx+1,
12393                                                HasVAListArg ? 0 : FormatIdx+2,
12394                                                FD->getLocation()));
12395       }
12396     }
12397     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12398                                              HasVAListArg)) {
12399      if (!FD->hasAttr<FormatAttr>())
12400        FD->addAttr(FormatAttr::CreateImplicit(Context,
12401                                               &Context.Idents.get("scanf"),
12402                                               FormatIdx+1,
12403                                               HasVAListArg ? 0 : FormatIdx+2,
12404                                               FD->getLocation()));
12405     }
12406 
12407     // Mark const if we don't care about errno and that is the only
12408     // thing preventing the function from being const. This allows
12409     // IRgen to use LLVM intrinsics for such functions.
12410     if (!getLangOpts().MathErrno &&
12411         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12412       if (!FD->hasAttr<ConstAttr>())
12413         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12414     }
12415 
12416     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12417         !FD->hasAttr<ReturnsTwiceAttr>())
12418       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12419                                          FD->getLocation()));
12420     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12421       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12422     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12423       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12424     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12425       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12426     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12427         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12428       // Add the appropriate attribute, depending on the CUDA compilation mode
12429       // and which target the builtin belongs to. For example, during host
12430       // compilation, aux builtins are __device__, while the rest are __host__.
12431       if (getLangOpts().CUDAIsDevice !=
12432           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12433         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12434       else
12435         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12436     }
12437   }
12438 
12439   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12440   // throw, add an implicit nothrow attribute to any extern "C" function we come
12441   // across.
12442   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12443       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12444     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12445     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12446       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12447   }
12448 
12449   IdentifierInfo *Name = FD->getIdentifier();
12450   if (!Name)
12451     return;
12452   if ((!getLangOpts().CPlusPlus &&
12453        FD->getDeclContext()->isTranslationUnit()) ||
12454       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12455        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12456        LinkageSpecDecl::lang_c)) {
12457     // Okay: this could be a libc/libm/Objective-C function we know
12458     // about.
12459   } else
12460     return;
12461 
12462   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12463     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12464     // target-specific builtins, perhaps?
12465     if (!FD->hasAttr<FormatAttr>())
12466       FD->addAttr(FormatAttr::CreateImplicit(Context,
12467                                              &Context.Idents.get("printf"), 2,
12468                                              Name->isStr("vasprintf") ? 0 : 3,
12469                                              FD->getLocation()));
12470   }
12471 
12472   if (Name->isStr("__CFStringMakeConstantString")) {
12473     // We already have a __builtin___CFStringMakeConstantString,
12474     // but builds that use -fno-constant-cfstrings don't go through that.
12475     if (!FD->hasAttr<FormatArgAttr>())
12476       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12477                                                 FD->getLocation()));
12478   }
12479 }
12480 
12481 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12482                                     TypeSourceInfo *TInfo) {
12483   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12484   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12485 
12486   if (!TInfo) {
12487     assert(D.isInvalidType() && "no declarator info for valid type");
12488     TInfo = Context.getTrivialTypeSourceInfo(T);
12489   }
12490 
12491   // Scope manipulation handled by caller.
12492   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12493                                            D.getLocStart(),
12494                                            D.getIdentifierLoc(),
12495                                            D.getIdentifier(),
12496                                            TInfo);
12497 
12498   // Bail out immediately if we have an invalid declaration.
12499   if (D.isInvalidType()) {
12500     NewTD->setInvalidDecl();
12501     return NewTD;
12502   }
12503 
12504   if (D.getDeclSpec().isModulePrivateSpecified()) {
12505     if (CurContext->isFunctionOrMethod())
12506       Diag(NewTD->getLocation(), diag::err_module_private_local)
12507         << 2 << NewTD->getDeclName()
12508         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12509         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12510     else
12511       NewTD->setModulePrivate();
12512   }
12513 
12514   // C++ [dcl.typedef]p8:
12515   //   If the typedef declaration defines an unnamed class (or
12516   //   enum), the first typedef-name declared by the declaration
12517   //   to be that class type (or enum type) is used to denote the
12518   //   class type (or enum type) for linkage purposes only.
12519   // We need to check whether the type was declared in the declaration.
12520   switch (D.getDeclSpec().getTypeSpecType()) {
12521   case TST_enum:
12522   case TST_struct:
12523   case TST_interface:
12524   case TST_union:
12525   case TST_class: {
12526     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12527     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12528     break;
12529   }
12530 
12531   default:
12532     break;
12533   }
12534 
12535   return NewTD;
12536 }
12537 
12538 /// \brief Check that this is a valid underlying type for an enum declaration.
12539 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12540   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12541   QualType T = TI->getType();
12542 
12543   if (T->isDependentType())
12544     return false;
12545 
12546   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12547     if (BT->isInteger())
12548       return false;
12549 
12550   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12551   return true;
12552 }
12553 
12554 /// Check whether this is a valid redeclaration of a previous enumeration.
12555 /// \return true if the redeclaration was invalid.
12556 bool Sema::CheckEnumRedeclaration(
12557     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12558     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12559   bool IsFixed = !EnumUnderlyingTy.isNull();
12560 
12561   if (IsScoped != Prev->isScoped()) {
12562     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12563       << Prev->isScoped();
12564     Diag(Prev->getLocation(), diag::note_previous_declaration);
12565     return true;
12566   }
12567 
12568   if (IsFixed && Prev->isFixed()) {
12569     if (!EnumUnderlyingTy->isDependentType() &&
12570         !Prev->getIntegerType()->isDependentType() &&
12571         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12572                                         Prev->getIntegerType())) {
12573       // TODO: Highlight the underlying type of the redeclaration.
12574       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12575         << EnumUnderlyingTy << Prev->getIntegerType();
12576       Diag(Prev->getLocation(), diag::note_previous_declaration)
12577           << Prev->getIntegerTypeRange();
12578       return true;
12579     }
12580   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12581     ;
12582   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12583     ;
12584   } else if (IsFixed != Prev->isFixed()) {
12585     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12586       << Prev->isFixed();
12587     Diag(Prev->getLocation(), diag::note_previous_declaration);
12588     return true;
12589   }
12590 
12591   return false;
12592 }
12593 
12594 /// \brief Get diagnostic %select index for tag kind for
12595 /// redeclaration diagnostic message.
12596 /// WARNING: Indexes apply to particular diagnostics only!
12597 ///
12598 /// \returns diagnostic %select index.
12599 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12600   switch (Tag) {
12601   case TTK_Struct: return 0;
12602   case TTK_Interface: return 1;
12603   case TTK_Class:  return 2;
12604   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12605   }
12606 }
12607 
12608 /// \brief Determine if tag kind is a class-key compatible with
12609 /// class for redeclaration (class, struct, or __interface).
12610 ///
12611 /// \returns true iff the tag kind is compatible.
12612 static bool isClassCompatTagKind(TagTypeKind Tag)
12613 {
12614   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12615 }
12616 
12617 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12618                                              TagTypeKind TTK) {
12619   if (isa<TypedefDecl>(PrevDecl))
12620     return NTK_Typedef;
12621   else if (isa<TypeAliasDecl>(PrevDecl))
12622     return NTK_TypeAlias;
12623   else if (isa<ClassTemplateDecl>(PrevDecl))
12624     return NTK_Template;
12625   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12626     return NTK_TypeAliasTemplate;
12627   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12628     return NTK_TemplateTemplateArgument;
12629   switch (TTK) {
12630   case TTK_Struct:
12631   case TTK_Interface:
12632   case TTK_Class:
12633     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12634   case TTK_Union:
12635     return NTK_NonUnion;
12636   case TTK_Enum:
12637     return NTK_NonEnum;
12638   }
12639   llvm_unreachable("invalid TTK");
12640 }
12641 
12642 /// \brief Determine whether a tag with a given kind is acceptable
12643 /// as a redeclaration of the given tag declaration.
12644 ///
12645 /// \returns true if the new tag kind is acceptable, false otherwise.
12646 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12647                                         TagTypeKind NewTag, bool isDefinition,
12648                                         SourceLocation NewTagLoc,
12649                                         const IdentifierInfo *Name) {
12650   // C++ [dcl.type.elab]p3:
12651   //   The class-key or enum keyword present in the
12652   //   elaborated-type-specifier shall agree in kind with the
12653   //   declaration to which the name in the elaborated-type-specifier
12654   //   refers. This rule also applies to the form of
12655   //   elaborated-type-specifier that declares a class-name or
12656   //   friend class since it can be construed as referring to the
12657   //   definition of the class. Thus, in any
12658   //   elaborated-type-specifier, the enum keyword shall be used to
12659   //   refer to an enumeration (7.2), the union class-key shall be
12660   //   used to refer to a union (clause 9), and either the class or
12661   //   struct class-key shall be used to refer to a class (clause 9)
12662   //   declared using the class or struct class-key.
12663   TagTypeKind OldTag = Previous->getTagKind();
12664   if (!isDefinition || !isClassCompatTagKind(NewTag))
12665     if (OldTag == NewTag)
12666       return true;
12667 
12668   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12669     // Warn about the struct/class tag mismatch.
12670     bool isTemplate = false;
12671     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12672       isTemplate = Record->getDescribedClassTemplate();
12673 
12674     if (!ActiveTemplateInstantiations.empty()) {
12675       // In a template instantiation, do not offer fix-its for tag mismatches
12676       // since they usually mess up the template instead of fixing the problem.
12677       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12678         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12679         << getRedeclDiagFromTagKind(OldTag);
12680       return true;
12681     }
12682 
12683     if (isDefinition) {
12684       // On definitions, check previous tags and issue a fix-it for each
12685       // one that doesn't match the current tag.
12686       if (Previous->getDefinition()) {
12687         // Don't suggest fix-its for redefinitions.
12688         return true;
12689       }
12690 
12691       bool previousMismatch = false;
12692       for (auto I : Previous->redecls()) {
12693         if (I->getTagKind() != NewTag) {
12694           if (!previousMismatch) {
12695             previousMismatch = true;
12696             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12697               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12698               << getRedeclDiagFromTagKind(I->getTagKind());
12699           }
12700           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12701             << getRedeclDiagFromTagKind(NewTag)
12702             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12703                  TypeWithKeyword::getTagTypeKindName(NewTag));
12704         }
12705       }
12706       return true;
12707     }
12708 
12709     // Check for a previous definition.  If current tag and definition
12710     // are same type, do nothing.  If no definition, but disagree with
12711     // with previous tag type, give a warning, but no fix-it.
12712     const TagDecl *Redecl = Previous->getDefinition() ?
12713                             Previous->getDefinition() : Previous;
12714     if (Redecl->getTagKind() == NewTag) {
12715       return true;
12716     }
12717 
12718     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12719       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12720       << getRedeclDiagFromTagKind(OldTag);
12721     Diag(Redecl->getLocation(), diag::note_previous_use);
12722 
12723     // If there is a previous definition, suggest a fix-it.
12724     if (Previous->getDefinition()) {
12725         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12726           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12727           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12728                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12729     }
12730 
12731     return true;
12732   }
12733   return false;
12734 }
12735 
12736 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12737 /// from an outer enclosing namespace or file scope inside a friend declaration.
12738 /// This should provide the commented out code in the following snippet:
12739 ///   namespace N {
12740 ///     struct X;
12741 ///     namespace M {
12742 ///       struct Y { friend struct /*N::*/ X; };
12743 ///     }
12744 ///   }
12745 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12746                                          SourceLocation NameLoc) {
12747   // While the decl is in a namespace, do repeated lookup of that name and see
12748   // if we get the same namespace back.  If we do not, continue until
12749   // translation unit scope, at which point we have a fully qualified NNS.
12750   SmallVector<IdentifierInfo *, 4> Namespaces;
12751   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12752   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12753     // This tag should be declared in a namespace, which can only be enclosed by
12754     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12755     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12756     if (!Namespace || Namespace->isAnonymousNamespace())
12757       return FixItHint();
12758     IdentifierInfo *II = Namespace->getIdentifier();
12759     Namespaces.push_back(II);
12760     NamedDecl *Lookup = SemaRef.LookupSingleName(
12761         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12762     if (Lookup == Namespace)
12763       break;
12764   }
12765 
12766   // Once we have all the namespaces, reverse them to go outermost first, and
12767   // build an NNS.
12768   SmallString<64> Insertion;
12769   llvm::raw_svector_ostream OS(Insertion);
12770   if (DC->isTranslationUnit())
12771     OS << "::";
12772   std::reverse(Namespaces.begin(), Namespaces.end());
12773   for (auto *II : Namespaces)
12774     OS << II->getName() << "::";
12775   return FixItHint::CreateInsertion(NameLoc, Insertion);
12776 }
12777 
12778 /// \brief Determine whether a tag originally declared in context \p OldDC can
12779 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12780 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12781 /// using-declaration).
12782 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12783                                          DeclContext *NewDC) {
12784   OldDC = OldDC->getRedeclContext();
12785   NewDC = NewDC->getRedeclContext();
12786 
12787   if (OldDC->Equals(NewDC))
12788     return true;
12789 
12790   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12791   // encloses the other).
12792   if (S.getLangOpts().MSVCCompat &&
12793       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12794     return true;
12795 
12796   return false;
12797 }
12798 
12799 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12800 /// former case, Name will be non-null.  In the later case, Name will be null.
12801 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12802 /// reference/declaration/definition of a tag.
12803 ///
12804 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12805 /// trailing-type-specifier) other than one in an alias-declaration.
12806 ///
12807 /// \param SkipBody If non-null, will be set to indicate if the caller should
12808 /// skip the definition of this tag and treat it as if it were a declaration.
12809 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12810                      SourceLocation KWLoc, CXXScopeSpec &SS,
12811                      IdentifierInfo *Name, SourceLocation NameLoc,
12812                      AttributeList *Attr, AccessSpecifier AS,
12813                      SourceLocation ModulePrivateLoc,
12814                      MultiTemplateParamsArg TemplateParameterLists,
12815                      bool &OwnedDecl, bool &IsDependent,
12816                      SourceLocation ScopedEnumKWLoc,
12817                      bool ScopedEnumUsesClassTag,
12818                      TypeResult UnderlyingType,
12819                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12820   // If this is not a definition, it must have a name.
12821   IdentifierInfo *OrigName = Name;
12822   assert((Name != nullptr || TUK == TUK_Definition) &&
12823          "Nameless record must be a definition!");
12824   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12825 
12826   OwnedDecl = false;
12827   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12828   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12829 
12830   // FIXME: Check explicit specializations more carefully.
12831   bool isExplicitSpecialization = false;
12832   bool Invalid = false;
12833 
12834   // We only need to do this matching if we have template parameters
12835   // or a scope specifier, which also conveniently avoids this work
12836   // for non-C++ cases.
12837   if (TemplateParameterLists.size() > 0 ||
12838       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12839     if (TemplateParameterList *TemplateParams =
12840             MatchTemplateParametersToScopeSpecifier(
12841                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12842                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12843       if (Kind == TTK_Enum) {
12844         Diag(KWLoc, diag::err_enum_template);
12845         return nullptr;
12846       }
12847 
12848       if (TemplateParams->size() > 0) {
12849         // This is a declaration or definition of a class template (which may
12850         // be a member of another template).
12851 
12852         if (Invalid)
12853           return nullptr;
12854 
12855         OwnedDecl = false;
12856         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12857                                                SS, Name, NameLoc, Attr,
12858                                                TemplateParams, AS,
12859                                                ModulePrivateLoc,
12860                                                /*FriendLoc*/SourceLocation(),
12861                                                TemplateParameterLists.size()-1,
12862                                                TemplateParameterLists.data(),
12863                                                SkipBody);
12864         return Result.get();
12865       } else {
12866         // The "template<>" header is extraneous.
12867         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12868           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12869         isExplicitSpecialization = true;
12870       }
12871     }
12872   }
12873 
12874   // Figure out the underlying type if this a enum declaration. We need to do
12875   // this early, because it's needed to detect if this is an incompatible
12876   // redeclaration.
12877   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12878   bool EnumUnderlyingIsImplicit = false;
12879 
12880   if (Kind == TTK_Enum) {
12881     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12882       // No underlying type explicitly specified, or we failed to parse the
12883       // type, default to int.
12884       EnumUnderlying = Context.IntTy.getTypePtr();
12885     else if (UnderlyingType.get()) {
12886       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12887       // integral type; any cv-qualification is ignored.
12888       TypeSourceInfo *TI = nullptr;
12889       GetTypeFromParser(UnderlyingType.get(), &TI);
12890       EnumUnderlying = TI;
12891 
12892       if (CheckEnumUnderlyingType(TI))
12893         // Recover by falling back to int.
12894         EnumUnderlying = Context.IntTy.getTypePtr();
12895 
12896       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12897                                           UPPC_FixedUnderlyingType))
12898         EnumUnderlying = Context.IntTy.getTypePtr();
12899 
12900     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12901       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12902         // Microsoft enums are always of int type.
12903         EnumUnderlying = Context.IntTy.getTypePtr();
12904         EnumUnderlyingIsImplicit = true;
12905       }
12906     }
12907   }
12908 
12909   DeclContext *SearchDC = CurContext;
12910   DeclContext *DC = CurContext;
12911   bool isStdBadAlloc = false;
12912   bool isStdAlignValT = false;
12913 
12914   RedeclarationKind Redecl = ForRedeclaration;
12915   if (TUK == TUK_Friend || TUK == TUK_Reference)
12916     Redecl = NotForRedeclaration;
12917 
12918   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12919   if (Name && SS.isNotEmpty()) {
12920     // We have a nested-name tag ('struct foo::bar').
12921 
12922     // Check for invalid 'foo::'.
12923     if (SS.isInvalid()) {
12924       Name = nullptr;
12925       goto CreateNewDecl;
12926     }
12927 
12928     // If this is a friend or a reference to a class in a dependent
12929     // context, don't try to make a decl for it.
12930     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12931       DC = computeDeclContext(SS, false);
12932       if (!DC) {
12933         IsDependent = true;
12934         return nullptr;
12935       }
12936     } else {
12937       DC = computeDeclContext(SS, true);
12938       if (!DC) {
12939         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12940           << SS.getRange();
12941         return nullptr;
12942       }
12943     }
12944 
12945     if (RequireCompleteDeclContext(SS, DC))
12946       return nullptr;
12947 
12948     SearchDC = DC;
12949     // Look-up name inside 'foo::'.
12950     LookupQualifiedName(Previous, DC);
12951 
12952     if (Previous.isAmbiguous())
12953       return nullptr;
12954 
12955     if (Previous.empty()) {
12956       // Name lookup did not find anything. However, if the
12957       // nested-name-specifier refers to the current instantiation,
12958       // and that current instantiation has any dependent base
12959       // classes, we might find something at instantiation time: treat
12960       // this as a dependent elaborated-type-specifier.
12961       // But this only makes any sense for reference-like lookups.
12962       if (Previous.wasNotFoundInCurrentInstantiation() &&
12963           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12964         IsDependent = true;
12965         return nullptr;
12966       }
12967 
12968       // A tag 'foo::bar' must already exist.
12969       Diag(NameLoc, diag::err_not_tag_in_scope)
12970         << Kind << Name << DC << SS.getRange();
12971       Name = nullptr;
12972       Invalid = true;
12973       goto CreateNewDecl;
12974     }
12975   } else if (Name) {
12976     // C++14 [class.mem]p14:
12977     //   If T is the name of a class, then each of the following shall have a
12978     //   name different from T:
12979     //    -- every member of class T that is itself a type
12980     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12981         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12982       return nullptr;
12983 
12984     // If this is a named struct, check to see if there was a previous forward
12985     // declaration or definition.
12986     // FIXME: We're looking into outer scopes here, even when we
12987     // shouldn't be. Doing so can result in ambiguities that we
12988     // shouldn't be diagnosing.
12989     LookupName(Previous, S);
12990 
12991     // When declaring or defining a tag, ignore ambiguities introduced
12992     // by types using'ed into this scope.
12993     if (Previous.isAmbiguous() &&
12994         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12995       LookupResult::Filter F = Previous.makeFilter();
12996       while (F.hasNext()) {
12997         NamedDecl *ND = F.next();
12998         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12999                 SearchDC->getRedeclContext()))
13000           F.erase();
13001       }
13002       F.done();
13003     }
13004 
13005     // C++11 [namespace.memdef]p3:
13006     //   If the name in a friend declaration is neither qualified nor
13007     //   a template-id and the declaration is a function or an
13008     //   elaborated-type-specifier, the lookup to determine whether
13009     //   the entity has been previously declared shall not consider
13010     //   any scopes outside the innermost enclosing namespace.
13011     //
13012     // MSVC doesn't implement the above rule for types, so a friend tag
13013     // declaration may be a redeclaration of a type declared in an enclosing
13014     // scope.  They do implement this rule for friend functions.
13015     //
13016     // Does it matter that this should be by scope instead of by
13017     // semantic context?
13018     if (!Previous.empty() && TUK == TUK_Friend) {
13019       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13020       LookupResult::Filter F = Previous.makeFilter();
13021       bool FriendSawTagOutsideEnclosingNamespace = false;
13022       while (F.hasNext()) {
13023         NamedDecl *ND = F.next();
13024         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13025         if (DC->isFileContext() &&
13026             !EnclosingNS->Encloses(ND->getDeclContext())) {
13027           if (getLangOpts().MSVCCompat)
13028             FriendSawTagOutsideEnclosingNamespace = true;
13029           else
13030             F.erase();
13031         }
13032       }
13033       F.done();
13034 
13035       // Diagnose this MSVC extension in the easy case where lookup would have
13036       // unambiguously found something outside the enclosing namespace.
13037       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13038         NamedDecl *ND = Previous.getFoundDecl();
13039         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13040             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13041       }
13042     }
13043 
13044     // Note:  there used to be some attempt at recovery here.
13045     if (Previous.isAmbiguous())
13046       return nullptr;
13047 
13048     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13049       // FIXME: This makes sure that we ignore the contexts associated
13050       // with C structs, unions, and enums when looking for a matching
13051       // tag declaration or definition. See the similar lookup tweak
13052       // in Sema::LookupName; is there a better way to deal with this?
13053       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13054         SearchDC = SearchDC->getParent();
13055     }
13056   }
13057 
13058   if (Previous.isSingleResult() &&
13059       Previous.getFoundDecl()->isTemplateParameter()) {
13060     // Maybe we will complain about the shadowed template parameter.
13061     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13062     // Just pretend that we didn't see the previous declaration.
13063     Previous.clear();
13064   }
13065 
13066   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13067       DC->Equals(getStdNamespace())) {
13068     if (Name->isStr("bad_alloc")) {
13069       // This is a declaration of or a reference to "std::bad_alloc".
13070       isStdBadAlloc = true;
13071 
13072       // If std::bad_alloc has been implicitly declared (but made invisible to
13073       // name lookup), fill in this implicit declaration as the previous
13074       // declaration, so that the declarations get chained appropriately.
13075       if (Previous.empty() && StdBadAlloc)
13076         Previous.addDecl(getStdBadAlloc());
13077     } else if (Name->isStr("align_val_t")) {
13078       isStdAlignValT = true;
13079       if (Previous.empty() && StdAlignValT)
13080         Previous.addDecl(getStdAlignValT());
13081     }
13082   }
13083 
13084   // If we didn't find a previous declaration, and this is a reference
13085   // (or friend reference), move to the correct scope.  In C++, we
13086   // also need to do a redeclaration lookup there, just in case
13087   // there's a shadow friend decl.
13088   if (Name && Previous.empty() &&
13089       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13090     if (Invalid) goto CreateNewDecl;
13091     assert(SS.isEmpty());
13092 
13093     if (TUK == TUK_Reference) {
13094       // C++ [basic.scope.pdecl]p5:
13095       //   -- for an elaborated-type-specifier of the form
13096       //
13097       //          class-key identifier
13098       //
13099       //      if the elaborated-type-specifier is used in the
13100       //      decl-specifier-seq or parameter-declaration-clause of a
13101       //      function defined in namespace scope, the identifier is
13102       //      declared as a class-name in the namespace that contains
13103       //      the declaration; otherwise, except as a friend
13104       //      declaration, the identifier is declared in the smallest
13105       //      non-class, non-function-prototype scope that contains the
13106       //      declaration.
13107       //
13108       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13109       // C structs and unions.
13110       //
13111       // It is an error in C++ to declare (rather than define) an enum
13112       // type, including via an elaborated type specifier.  We'll
13113       // diagnose that later; for now, declare the enum in the same
13114       // scope as we would have picked for any other tag type.
13115       //
13116       // GNU C also supports this behavior as part of its incomplete
13117       // enum types extension, while GNU C++ does not.
13118       //
13119       // Find the context where we'll be declaring the tag.
13120       // FIXME: We would like to maintain the current DeclContext as the
13121       // lexical context,
13122       SearchDC = getTagInjectionContext(SearchDC);
13123 
13124       // Find the scope where we'll be declaring the tag.
13125       S = getTagInjectionScope(S, getLangOpts());
13126     } else {
13127       assert(TUK == TUK_Friend);
13128       // C++ [namespace.memdef]p3:
13129       //   If a friend declaration in a non-local class first declares a
13130       //   class or function, the friend class or function is a member of
13131       //   the innermost enclosing namespace.
13132       SearchDC = SearchDC->getEnclosingNamespaceContext();
13133     }
13134 
13135     // In C++, we need to do a redeclaration lookup to properly
13136     // diagnose some problems.
13137     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13138     // hidden declaration so that we don't get ambiguity errors when using a
13139     // type declared by an elaborated-type-specifier.  In C that is not correct
13140     // and we should instead merge compatible types found by lookup.
13141     if (getLangOpts().CPlusPlus) {
13142       Previous.setRedeclarationKind(ForRedeclaration);
13143       LookupQualifiedName(Previous, SearchDC);
13144     } else {
13145       Previous.setRedeclarationKind(ForRedeclaration);
13146       LookupName(Previous, S);
13147     }
13148   }
13149 
13150   // If we have a known previous declaration to use, then use it.
13151   if (Previous.empty() && SkipBody && SkipBody->Previous)
13152     Previous.addDecl(SkipBody->Previous);
13153 
13154   if (!Previous.empty()) {
13155     NamedDecl *PrevDecl = Previous.getFoundDecl();
13156     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13157 
13158     // It's okay to have a tag decl in the same scope as a typedef
13159     // which hides a tag decl in the same scope.  Finding this
13160     // insanity with a redeclaration lookup can only actually happen
13161     // in C++.
13162     //
13163     // This is also okay for elaborated-type-specifiers, which is
13164     // technically forbidden by the current standard but which is
13165     // okay according to the likely resolution of an open issue;
13166     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13167     if (getLangOpts().CPlusPlus) {
13168       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13169         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13170           TagDecl *Tag = TT->getDecl();
13171           if (Tag->getDeclName() == Name &&
13172               Tag->getDeclContext()->getRedeclContext()
13173                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13174             PrevDecl = Tag;
13175             Previous.clear();
13176             Previous.addDecl(Tag);
13177             Previous.resolveKind();
13178           }
13179         }
13180       }
13181     }
13182 
13183     // If this is a redeclaration of a using shadow declaration, it must
13184     // declare a tag in the same context. In MSVC mode, we allow a
13185     // redefinition if either context is within the other.
13186     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13187       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13188       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13189           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
13190           !(OldTag && isAcceptableTagRedeclContext(
13191                           *this, OldTag->getDeclContext(), SearchDC))) {
13192         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13193         Diag(Shadow->getTargetDecl()->getLocation(),
13194              diag::note_using_decl_target);
13195         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13196             << 0;
13197         // Recover by ignoring the old declaration.
13198         Previous.clear();
13199         goto CreateNewDecl;
13200       }
13201     }
13202 
13203     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13204       // If this is a use of a previous tag, or if the tag is already declared
13205       // in the same scope (so that the definition/declaration completes or
13206       // rementions the tag), reuse the decl.
13207       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13208           isDeclInScope(DirectPrevDecl, SearchDC, S,
13209                         SS.isNotEmpty() || isExplicitSpecialization)) {
13210         // Make sure that this wasn't declared as an enum and now used as a
13211         // struct or something similar.
13212         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13213                                           TUK == TUK_Definition, KWLoc,
13214                                           Name)) {
13215           bool SafeToContinue
13216             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13217                Kind != TTK_Enum);
13218           if (SafeToContinue)
13219             Diag(KWLoc, diag::err_use_with_wrong_tag)
13220               << Name
13221               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13222                                               PrevTagDecl->getKindName());
13223           else
13224             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13225           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13226 
13227           if (SafeToContinue)
13228             Kind = PrevTagDecl->getTagKind();
13229           else {
13230             // Recover by making this an anonymous redefinition.
13231             Name = nullptr;
13232             Previous.clear();
13233             Invalid = true;
13234           }
13235         }
13236 
13237         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13238           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13239 
13240           // If this is an elaborated-type-specifier for a scoped enumeration,
13241           // the 'class' keyword is not necessary and not permitted.
13242           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13243             if (ScopedEnum)
13244               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13245                 << PrevEnum->isScoped()
13246                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13247             return PrevTagDecl;
13248           }
13249 
13250           QualType EnumUnderlyingTy;
13251           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13252             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13253           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13254             EnumUnderlyingTy = QualType(T, 0);
13255 
13256           // All conflicts with previous declarations are recovered by
13257           // returning the previous declaration, unless this is a definition,
13258           // in which case we want the caller to bail out.
13259           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13260                                      ScopedEnum, EnumUnderlyingTy,
13261                                      EnumUnderlyingIsImplicit, PrevEnum))
13262             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13263         }
13264 
13265         // C++11 [class.mem]p1:
13266         //   A member shall not be declared twice in the member-specification,
13267         //   except that a nested class or member class template can be declared
13268         //   and then later defined.
13269         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13270             S->isDeclScope(PrevDecl)) {
13271           Diag(NameLoc, diag::ext_member_redeclared);
13272           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13273         }
13274 
13275         if (!Invalid) {
13276           // If this is a use, just return the declaration we found, unless
13277           // we have attributes.
13278           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13279             if (Attr) {
13280               // FIXME: Diagnose these attributes. For now, we create a new
13281               // declaration to hold them.
13282             } else if (TUK == TUK_Reference &&
13283                        (PrevTagDecl->getFriendObjectKind() ==
13284                             Decl::FOK_Undeclared ||
13285                         PP.getModuleContainingLocation(
13286                             PrevDecl->getLocation()) !=
13287                             PP.getModuleContainingLocation(KWLoc)) &&
13288                        SS.isEmpty()) {
13289               // This declaration is a reference to an existing entity, but
13290               // has different visibility from that entity: it either makes
13291               // a friend visible or it makes a type visible in a new module.
13292               // In either case, create a new declaration. We only do this if
13293               // the declaration would have meant the same thing if no prior
13294               // declaration were found, that is, if it was found in the same
13295               // scope where we would have injected a declaration.
13296               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13297                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13298                 return PrevTagDecl;
13299               // This is in the injected scope, create a new declaration in
13300               // that scope.
13301               S = getTagInjectionScope(S, getLangOpts());
13302             } else {
13303               return PrevTagDecl;
13304             }
13305           }
13306 
13307           // Diagnose attempts to redefine a tag.
13308           if (TUK == TUK_Definition) {
13309             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13310               // If we're defining a specialization and the previous definition
13311               // is from an implicit instantiation, don't emit an error
13312               // here; we'll catch this in the general case below.
13313               bool IsExplicitSpecializationAfterInstantiation = false;
13314               if (isExplicitSpecialization) {
13315                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13316                   IsExplicitSpecializationAfterInstantiation =
13317                     RD->getTemplateSpecializationKind() !=
13318                     TSK_ExplicitSpecialization;
13319                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13320                   IsExplicitSpecializationAfterInstantiation =
13321                     ED->getTemplateSpecializationKind() !=
13322                     TSK_ExplicitSpecialization;
13323               }
13324 
13325               NamedDecl *Hidden = nullptr;
13326               if (SkipBody && getLangOpts().CPlusPlus &&
13327                   !hasVisibleDefinition(Def, &Hidden)) {
13328                 // There is a definition of this tag, but it is not visible. We
13329                 // explicitly make use of C++'s one definition rule here, and
13330                 // assume that this definition is identical to the hidden one
13331                 // we already have. Make the existing definition visible and
13332                 // use it in place of this one.
13333                 SkipBody->ShouldSkip = true;
13334                 makeMergedDefinitionVisible(Hidden, KWLoc);
13335                 return Def;
13336               } else if (!IsExplicitSpecializationAfterInstantiation) {
13337                 // A redeclaration in function prototype scope in C isn't
13338                 // visible elsewhere, so merely issue a warning.
13339                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13340                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13341                 else
13342                   Diag(NameLoc, diag::err_redefinition) << Name;
13343                 Diag(Def->getLocation(), diag::note_previous_definition);
13344                 // If this is a redefinition, recover by making this
13345                 // struct be anonymous, which will make any later
13346                 // references get the previous definition.
13347                 Name = nullptr;
13348                 Previous.clear();
13349                 Invalid = true;
13350               }
13351             } else {
13352               // If the type is currently being defined, complain
13353               // about a nested redefinition.
13354               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13355               if (TD->isBeingDefined()) {
13356                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13357                 Diag(PrevTagDecl->getLocation(),
13358                      diag::note_previous_definition);
13359                 Name = nullptr;
13360                 Previous.clear();
13361                 Invalid = true;
13362               }
13363             }
13364 
13365             // Okay, this is definition of a previously declared or referenced
13366             // tag. We're going to create a new Decl for it.
13367           }
13368 
13369           // Okay, we're going to make a redeclaration.  If this is some kind
13370           // of reference, make sure we build the redeclaration in the same DC
13371           // as the original, and ignore the current access specifier.
13372           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13373             SearchDC = PrevTagDecl->getDeclContext();
13374             AS = AS_none;
13375           }
13376         }
13377         // If we get here we have (another) forward declaration or we
13378         // have a definition.  Just create a new decl.
13379 
13380       } else {
13381         // If we get here, this is a definition of a new tag type in a nested
13382         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13383         // new decl/type.  We set PrevDecl to NULL so that the entities
13384         // have distinct types.
13385         Previous.clear();
13386       }
13387       // If we get here, we're going to create a new Decl. If PrevDecl
13388       // is non-NULL, it's a definition of the tag declared by
13389       // PrevDecl. If it's NULL, we have a new definition.
13390 
13391     // Otherwise, PrevDecl is not a tag, but was found with tag
13392     // lookup.  This is only actually possible in C++, where a few
13393     // things like templates still live in the tag namespace.
13394     } else {
13395       // Use a better diagnostic if an elaborated-type-specifier
13396       // found the wrong kind of type on the first
13397       // (non-redeclaration) lookup.
13398       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13399           !Previous.isForRedeclaration()) {
13400         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13401         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13402                                                        << Kind;
13403         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13404         Invalid = true;
13405 
13406       // Otherwise, only diagnose if the declaration is in scope.
13407       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13408                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13409         // do nothing
13410 
13411       // Diagnose implicit declarations introduced by elaborated types.
13412       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13413         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13414         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13415         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13416         Invalid = true;
13417 
13418       // Otherwise it's a declaration.  Call out a particularly common
13419       // case here.
13420       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13421         unsigned Kind = 0;
13422         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13423         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13424           << Name << Kind << TND->getUnderlyingType();
13425         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13426         Invalid = true;
13427 
13428       // Otherwise, diagnose.
13429       } else {
13430         // The tag name clashes with something else in the target scope,
13431         // issue an error and recover by making this tag be anonymous.
13432         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13433         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13434         Name = nullptr;
13435         Invalid = true;
13436       }
13437 
13438       // The existing declaration isn't relevant to us; we're in a
13439       // new scope, so clear out the previous declaration.
13440       Previous.clear();
13441     }
13442   }
13443 
13444 CreateNewDecl:
13445 
13446   TagDecl *PrevDecl = nullptr;
13447   if (Previous.isSingleResult())
13448     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13449 
13450   // If there is an identifier, use the location of the identifier as the
13451   // location of the decl, otherwise use the location of the struct/union
13452   // keyword.
13453   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13454 
13455   // Otherwise, create a new declaration. If there is a previous
13456   // declaration of the same entity, the two will be linked via
13457   // PrevDecl.
13458   TagDecl *New;
13459 
13460   bool IsForwardReference = false;
13461   if (Kind == TTK_Enum) {
13462     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13463     // enum X { A, B, C } D;    D should chain to X.
13464     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13465                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13466                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13467 
13468     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13469       StdAlignValT = cast<EnumDecl>(New);
13470 
13471     // If this is an undefined enum, warn.
13472     if (TUK != TUK_Definition && !Invalid) {
13473       TagDecl *Def;
13474       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13475           cast<EnumDecl>(New)->isFixed()) {
13476         // C++0x: 7.2p2: opaque-enum-declaration.
13477         // Conflicts are diagnosed above. Do nothing.
13478       }
13479       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13480         Diag(Loc, diag::ext_forward_ref_enum_def)
13481           << New;
13482         Diag(Def->getLocation(), diag::note_previous_definition);
13483       } else {
13484         unsigned DiagID = diag::ext_forward_ref_enum;
13485         if (getLangOpts().MSVCCompat)
13486           DiagID = diag::ext_ms_forward_ref_enum;
13487         else if (getLangOpts().CPlusPlus)
13488           DiagID = diag::err_forward_ref_enum;
13489         Diag(Loc, DiagID);
13490 
13491         // If this is a forward-declared reference to an enumeration, make a
13492         // note of it; we won't actually be introducing the declaration into
13493         // the declaration context.
13494         if (TUK == TUK_Reference)
13495           IsForwardReference = true;
13496       }
13497     }
13498 
13499     if (EnumUnderlying) {
13500       EnumDecl *ED = cast<EnumDecl>(New);
13501       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13502         ED->setIntegerTypeSourceInfo(TI);
13503       else
13504         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13505       ED->setPromotionType(ED->getIntegerType());
13506     }
13507   } else {
13508     // struct/union/class
13509 
13510     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13511     // struct X { int A; } D;    D should chain to X.
13512     if (getLangOpts().CPlusPlus) {
13513       // FIXME: Look for a way to use RecordDecl for simple structs.
13514       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13515                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13516 
13517       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13518         StdBadAlloc = cast<CXXRecordDecl>(New);
13519     } else
13520       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13521                                cast_or_null<RecordDecl>(PrevDecl));
13522   }
13523 
13524   // C++11 [dcl.type]p3:
13525   //   A type-specifier-seq shall not define a class or enumeration [...].
13526   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13527     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13528       << Context.getTagDeclType(New);
13529     Invalid = true;
13530   }
13531 
13532   // Maybe add qualifier info.
13533   if (SS.isNotEmpty()) {
13534     if (SS.isSet()) {
13535       // If this is either a declaration or a definition, check the
13536       // nested-name-specifier against the current context. We don't do this
13537       // for explicit specializations, because they have similar checking
13538       // (with more specific diagnostics) in the call to
13539       // CheckMemberSpecialization, below.
13540       if (!isExplicitSpecialization &&
13541           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13542           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13543         Invalid = true;
13544 
13545       New->setQualifierInfo(SS.getWithLocInContext(Context));
13546       if (TemplateParameterLists.size() > 0) {
13547         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13548       }
13549     }
13550     else
13551       Invalid = true;
13552   }
13553 
13554   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13555     // Add alignment attributes if necessary; these attributes are checked when
13556     // the ASTContext lays out the structure.
13557     //
13558     // It is important for implementing the correct semantics that this
13559     // happen here (in act on tag decl). The #pragma pack stack is
13560     // maintained as a result of parser callbacks which can occur at
13561     // many points during the parsing of a struct declaration (because
13562     // the #pragma tokens are effectively skipped over during the
13563     // parsing of the struct).
13564     if (TUK == TUK_Definition) {
13565       AddAlignmentAttributesForRecord(RD);
13566       AddMsStructLayoutForRecord(RD);
13567     }
13568   }
13569 
13570   if (ModulePrivateLoc.isValid()) {
13571     if (isExplicitSpecialization)
13572       Diag(New->getLocation(), diag::err_module_private_specialization)
13573         << 2
13574         << FixItHint::CreateRemoval(ModulePrivateLoc);
13575     // __module_private__ does not apply to local classes. However, we only
13576     // diagnose this as an error when the declaration specifiers are
13577     // freestanding. Here, we just ignore the __module_private__.
13578     else if (!SearchDC->isFunctionOrMethod())
13579       New->setModulePrivate();
13580   }
13581 
13582   // If this is a specialization of a member class (of a class template),
13583   // check the specialization.
13584   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13585     Invalid = true;
13586 
13587   // If we're declaring or defining a tag in function prototype scope in C,
13588   // note that this type can only be used within the function and add it to
13589   // the list of decls to inject into the function definition scope.
13590   if ((Name || Kind == TTK_Enum) &&
13591       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13592     if (getLangOpts().CPlusPlus) {
13593       // C++ [dcl.fct]p6:
13594       //   Types shall not be defined in return or parameter types.
13595       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13596         Diag(Loc, diag::err_type_defined_in_param_type)
13597             << Name;
13598         Invalid = true;
13599       }
13600     } else if (!PrevDecl) {
13601       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13602     }
13603   }
13604 
13605   if (Invalid)
13606     New->setInvalidDecl();
13607 
13608   if (Attr)
13609     ProcessDeclAttributeList(S, New, Attr);
13610 
13611   // Set the lexical context. If the tag has a C++ scope specifier, the
13612   // lexical context will be different from the semantic context.
13613   New->setLexicalDeclContext(CurContext);
13614 
13615   // Mark this as a friend decl if applicable.
13616   // In Microsoft mode, a friend declaration also acts as a forward
13617   // declaration so we always pass true to setObjectOfFriendDecl to make
13618   // the tag name visible.
13619   if (TUK == TUK_Friend)
13620     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13621 
13622   // Set the access specifier.
13623   if (!Invalid && SearchDC->isRecord())
13624     SetMemberAccessSpecifier(New, PrevDecl, AS);
13625 
13626   if (TUK == TUK_Definition)
13627     New->startDefinition();
13628 
13629   // If this has an identifier, add it to the scope stack.
13630   if (TUK == TUK_Friend) {
13631     // We might be replacing an existing declaration in the lookup tables;
13632     // if so, borrow its access specifier.
13633     if (PrevDecl)
13634       New->setAccess(PrevDecl->getAccess());
13635 
13636     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13637     DC->makeDeclVisibleInContext(New);
13638     if (Name) // can be null along some error paths
13639       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13640         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13641   } else if (Name) {
13642     S = getNonFieldDeclScope(S);
13643     PushOnScopeChains(New, S, !IsForwardReference);
13644     if (IsForwardReference)
13645       SearchDC->makeDeclVisibleInContext(New);
13646   } else {
13647     CurContext->addDecl(New);
13648   }
13649 
13650   // If this is the C FILE type, notify the AST context.
13651   if (IdentifierInfo *II = New->getIdentifier())
13652     if (!New->isInvalidDecl() &&
13653         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13654         II->isStr("FILE"))
13655       Context.setFILEDecl(New);
13656 
13657   if (PrevDecl)
13658     mergeDeclAttributes(New, PrevDecl);
13659 
13660   // If there's a #pragma GCC visibility in scope, set the visibility of this
13661   // record.
13662   AddPushedVisibilityAttribute(New);
13663 
13664   OwnedDecl = true;
13665   // In C++, don't return an invalid declaration. We can't recover well from
13666   // the cases where we make the type anonymous.
13667   if (Invalid && getLangOpts().CPlusPlus) {
13668     if (New->isBeingDefined())
13669       if (auto RD = dyn_cast<RecordDecl>(New))
13670         RD->completeDefinition();
13671     return nullptr;
13672   } else {
13673     return New;
13674   }
13675 }
13676 
13677 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13678   AdjustDeclIfTemplate(TagD);
13679   TagDecl *Tag = cast<TagDecl>(TagD);
13680 
13681   // Enter the tag context.
13682   PushDeclContext(S, Tag);
13683 
13684   ActOnDocumentableDecl(TagD);
13685 
13686   // If there's a #pragma GCC visibility in scope, set the visibility of this
13687   // record.
13688   AddPushedVisibilityAttribute(Tag);
13689 }
13690 
13691 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13692   assert(isa<ObjCContainerDecl>(IDecl) &&
13693          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13694   DeclContext *OCD = cast<DeclContext>(IDecl);
13695   assert(getContainingDC(OCD) == CurContext &&
13696       "The next DeclContext should be lexically contained in the current one.");
13697   CurContext = OCD;
13698   return IDecl;
13699 }
13700 
13701 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13702                                            SourceLocation FinalLoc,
13703                                            bool IsFinalSpelledSealed,
13704                                            SourceLocation LBraceLoc) {
13705   AdjustDeclIfTemplate(TagD);
13706   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13707 
13708   FieldCollector->StartClass();
13709 
13710   if (!Record->getIdentifier())
13711     return;
13712 
13713   if (FinalLoc.isValid())
13714     Record->addAttr(new (Context)
13715                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13716 
13717   // C++ [class]p2:
13718   //   [...] The class-name is also inserted into the scope of the
13719   //   class itself; this is known as the injected-class-name. For
13720   //   purposes of access checking, the injected-class-name is treated
13721   //   as if it were a public member name.
13722   CXXRecordDecl *InjectedClassName
13723     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13724                             Record->getLocStart(), Record->getLocation(),
13725                             Record->getIdentifier(),
13726                             /*PrevDecl=*/nullptr,
13727                             /*DelayTypeCreation=*/true);
13728   Context.getTypeDeclType(InjectedClassName, Record);
13729   InjectedClassName->setImplicit();
13730   InjectedClassName->setAccess(AS_public);
13731   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13732       InjectedClassName->setDescribedClassTemplate(Template);
13733   PushOnScopeChains(InjectedClassName, S);
13734   assert(InjectedClassName->isInjectedClassName() &&
13735          "Broken injected-class-name");
13736 }
13737 
13738 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13739                                     SourceRange BraceRange) {
13740   AdjustDeclIfTemplate(TagD);
13741   TagDecl *Tag = cast<TagDecl>(TagD);
13742   Tag->setBraceRange(BraceRange);
13743 
13744   // Make sure we "complete" the definition even it is invalid.
13745   if (Tag->isBeingDefined()) {
13746     assert(Tag->isInvalidDecl() && "We should already have completed it");
13747     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13748       RD->completeDefinition();
13749   }
13750 
13751   if (isa<CXXRecordDecl>(Tag))
13752     FieldCollector->FinishClass();
13753 
13754   // Exit this scope of this tag's definition.
13755   PopDeclContext();
13756 
13757   if (getCurLexicalContext()->isObjCContainer() &&
13758       Tag->getDeclContext()->isFileContext())
13759     Tag->setTopLevelDeclInObjCContainer();
13760 
13761   // Notify the consumer that we've defined a tag.
13762   if (!Tag->isInvalidDecl())
13763     Consumer.HandleTagDeclDefinition(Tag);
13764 }
13765 
13766 void Sema::ActOnObjCContainerFinishDefinition() {
13767   // Exit this scope of this interface definition.
13768   PopDeclContext();
13769 }
13770 
13771 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13772   assert(DC == CurContext && "Mismatch of container contexts");
13773   OriginalLexicalContext = DC;
13774   ActOnObjCContainerFinishDefinition();
13775 }
13776 
13777 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13778   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13779   OriginalLexicalContext = nullptr;
13780 }
13781 
13782 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13783   AdjustDeclIfTemplate(TagD);
13784   TagDecl *Tag = cast<TagDecl>(TagD);
13785   Tag->setInvalidDecl();
13786 
13787   // Make sure we "complete" the definition even it is invalid.
13788   if (Tag->isBeingDefined()) {
13789     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13790       RD->completeDefinition();
13791   }
13792 
13793   // We're undoing ActOnTagStartDefinition here, not
13794   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13795   // the FieldCollector.
13796 
13797   PopDeclContext();
13798 }
13799 
13800 // Note that FieldName may be null for anonymous bitfields.
13801 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13802                                 IdentifierInfo *FieldName,
13803                                 QualType FieldTy, bool IsMsStruct,
13804                                 Expr *BitWidth, bool *ZeroWidth) {
13805   // Default to true; that shouldn't confuse checks for emptiness
13806   if (ZeroWidth)
13807     *ZeroWidth = true;
13808 
13809   // C99 6.7.2.1p4 - verify the field type.
13810   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13811   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13812     // Handle incomplete types with specific error.
13813     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13814       return ExprError();
13815     if (FieldName)
13816       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13817         << FieldName << FieldTy << BitWidth->getSourceRange();
13818     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13819       << FieldTy << BitWidth->getSourceRange();
13820   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13821                                              UPPC_BitFieldWidth))
13822     return ExprError();
13823 
13824   // If the bit-width is type- or value-dependent, don't try to check
13825   // it now.
13826   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13827     return BitWidth;
13828 
13829   llvm::APSInt Value;
13830   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13831   if (ICE.isInvalid())
13832     return ICE;
13833   BitWidth = ICE.get();
13834 
13835   if (Value != 0 && ZeroWidth)
13836     *ZeroWidth = false;
13837 
13838   // Zero-width bitfield is ok for anonymous field.
13839   if (Value == 0 && FieldName)
13840     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13841 
13842   if (Value.isSigned() && Value.isNegative()) {
13843     if (FieldName)
13844       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13845                << FieldName << Value.toString(10);
13846     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13847       << Value.toString(10);
13848   }
13849 
13850   if (!FieldTy->isDependentType()) {
13851     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13852     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13853     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13854 
13855     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13856     // ABI.
13857     bool CStdConstraintViolation =
13858         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13859     bool MSBitfieldViolation =
13860         Value.ugt(TypeStorageSize) &&
13861         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13862     if (CStdConstraintViolation || MSBitfieldViolation) {
13863       unsigned DiagWidth =
13864           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13865       if (FieldName)
13866         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13867                << FieldName << (unsigned)Value.getZExtValue()
13868                << !CStdConstraintViolation << DiagWidth;
13869 
13870       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13871              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13872              << DiagWidth;
13873     }
13874 
13875     // Warn on types where the user might conceivably expect to get all
13876     // specified bits as value bits: that's all integral types other than
13877     // 'bool'.
13878     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13879       if (FieldName)
13880         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13881             << FieldName << (unsigned)Value.getZExtValue()
13882             << (unsigned)TypeWidth;
13883       else
13884         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13885             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13886     }
13887   }
13888 
13889   return BitWidth;
13890 }
13891 
13892 /// ActOnField - Each field of a C struct/union is passed into this in order
13893 /// to create a FieldDecl object for it.
13894 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13895                        Declarator &D, Expr *BitfieldWidth) {
13896   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13897                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13898                                /*InitStyle=*/ICIS_NoInit, AS_public);
13899   return Res;
13900 }
13901 
13902 /// HandleField - Analyze a field of a C struct or a C++ data member.
13903 ///
13904 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13905                              SourceLocation DeclStart,
13906                              Declarator &D, Expr *BitWidth,
13907                              InClassInitStyle InitStyle,
13908                              AccessSpecifier AS) {
13909   if (D.isDecompositionDeclarator()) {
13910     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13911     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13912       << Decomp.getSourceRange();
13913     return nullptr;
13914   }
13915 
13916   IdentifierInfo *II = D.getIdentifier();
13917   SourceLocation Loc = DeclStart;
13918   if (II) Loc = D.getIdentifierLoc();
13919 
13920   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13921   QualType T = TInfo->getType();
13922   if (getLangOpts().CPlusPlus) {
13923     CheckExtraCXXDefaultArguments(D);
13924 
13925     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13926                                         UPPC_DataMemberType)) {
13927       D.setInvalidType();
13928       T = Context.IntTy;
13929       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13930     }
13931   }
13932 
13933   // TR 18037 does not allow fields to be declared with address spaces.
13934   if (T.getQualifiers().hasAddressSpace()) {
13935     Diag(Loc, diag::err_field_with_address_space);
13936     D.setInvalidType();
13937   }
13938 
13939   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13940   // used as structure or union field: image, sampler, event or block types.
13941   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13942                           T->isSamplerT() || T->isBlockPointerType())) {
13943     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13944     D.setInvalidType();
13945   }
13946 
13947   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13948 
13949   if (D.getDeclSpec().isInlineSpecified())
13950     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13951         << getLangOpts().CPlusPlus1z;
13952   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13953     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13954          diag::err_invalid_thread)
13955       << DeclSpec::getSpecifierName(TSCS);
13956 
13957   // Check to see if this name was declared as a member previously
13958   NamedDecl *PrevDecl = nullptr;
13959   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13960   LookupName(Previous, S);
13961   switch (Previous.getResultKind()) {
13962     case LookupResult::Found:
13963     case LookupResult::FoundUnresolvedValue:
13964       PrevDecl = Previous.getAsSingle<NamedDecl>();
13965       break;
13966 
13967     case LookupResult::FoundOverloaded:
13968       PrevDecl = Previous.getRepresentativeDecl();
13969       break;
13970 
13971     case LookupResult::NotFound:
13972     case LookupResult::NotFoundInCurrentInstantiation:
13973     case LookupResult::Ambiguous:
13974       break;
13975   }
13976   Previous.suppressDiagnostics();
13977 
13978   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13979     // Maybe we will complain about the shadowed template parameter.
13980     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13981     // Just pretend that we didn't see the previous declaration.
13982     PrevDecl = nullptr;
13983   }
13984 
13985   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13986     PrevDecl = nullptr;
13987 
13988   bool Mutable
13989     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13990   SourceLocation TSSL = D.getLocStart();
13991   FieldDecl *NewFD
13992     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13993                      TSSL, AS, PrevDecl, &D);
13994 
13995   if (NewFD->isInvalidDecl())
13996     Record->setInvalidDecl();
13997 
13998   if (D.getDeclSpec().isModulePrivateSpecified())
13999     NewFD->setModulePrivate();
14000 
14001   if (NewFD->isInvalidDecl() && PrevDecl) {
14002     // Don't introduce NewFD into scope; there's already something
14003     // with the same name in the same scope.
14004   } else if (II) {
14005     PushOnScopeChains(NewFD, S);
14006   } else
14007     Record->addDecl(NewFD);
14008 
14009   return NewFD;
14010 }
14011 
14012 /// \brief Build a new FieldDecl and check its well-formedness.
14013 ///
14014 /// This routine builds a new FieldDecl given the fields name, type,
14015 /// record, etc. \p PrevDecl should refer to any previous declaration
14016 /// with the same name and in the same scope as the field to be
14017 /// created.
14018 ///
14019 /// \returns a new FieldDecl.
14020 ///
14021 /// \todo The Declarator argument is a hack. It will be removed once
14022 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14023                                 TypeSourceInfo *TInfo,
14024                                 RecordDecl *Record, SourceLocation Loc,
14025                                 bool Mutable, Expr *BitWidth,
14026                                 InClassInitStyle InitStyle,
14027                                 SourceLocation TSSL,
14028                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14029                                 Declarator *D) {
14030   IdentifierInfo *II = Name.getAsIdentifierInfo();
14031   bool InvalidDecl = false;
14032   if (D) InvalidDecl = D->isInvalidType();
14033 
14034   // If we receive a broken type, recover by assuming 'int' and
14035   // marking this declaration as invalid.
14036   if (T.isNull()) {
14037     InvalidDecl = true;
14038     T = Context.IntTy;
14039   }
14040 
14041   QualType EltTy = Context.getBaseElementType(T);
14042   if (!EltTy->isDependentType()) {
14043     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14044       // Fields of incomplete type force their record to be invalid.
14045       Record->setInvalidDecl();
14046       InvalidDecl = true;
14047     } else {
14048       NamedDecl *Def;
14049       EltTy->isIncompleteType(&Def);
14050       if (Def && Def->isInvalidDecl()) {
14051         Record->setInvalidDecl();
14052         InvalidDecl = true;
14053       }
14054     }
14055   }
14056 
14057   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14058   if (BitWidth && getLangOpts().OpenCL) {
14059     Diag(Loc, diag::err_opencl_bitfields);
14060     InvalidDecl = true;
14061   }
14062 
14063   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14064   // than a variably modified type.
14065   if (!InvalidDecl && T->isVariablyModifiedType()) {
14066     bool SizeIsNegative;
14067     llvm::APSInt Oversized;
14068 
14069     TypeSourceInfo *FixedTInfo =
14070       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14071                                                     SizeIsNegative,
14072                                                     Oversized);
14073     if (FixedTInfo) {
14074       Diag(Loc, diag::warn_illegal_constant_array_size);
14075       TInfo = FixedTInfo;
14076       T = FixedTInfo->getType();
14077     } else {
14078       if (SizeIsNegative)
14079         Diag(Loc, diag::err_typecheck_negative_array_size);
14080       else if (Oversized.getBoolValue())
14081         Diag(Loc, diag::err_array_too_large)
14082           << Oversized.toString(10);
14083       else
14084         Diag(Loc, diag::err_typecheck_field_variable_size);
14085       InvalidDecl = true;
14086     }
14087   }
14088 
14089   // Fields can not have abstract class types
14090   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14091                                              diag::err_abstract_type_in_decl,
14092                                              AbstractFieldType))
14093     InvalidDecl = true;
14094 
14095   bool ZeroWidth = false;
14096   if (InvalidDecl)
14097     BitWidth = nullptr;
14098   // If this is declared as a bit-field, check the bit-field.
14099   if (BitWidth) {
14100     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14101                               &ZeroWidth).get();
14102     if (!BitWidth) {
14103       InvalidDecl = true;
14104       BitWidth = nullptr;
14105       ZeroWidth = false;
14106     }
14107   }
14108 
14109   // Check that 'mutable' is consistent with the type of the declaration.
14110   if (!InvalidDecl && Mutable) {
14111     unsigned DiagID = 0;
14112     if (T->isReferenceType())
14113       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14114                                         : diag::err_mutable_reference;
14115     else if (T.isConstQualified())
14116       DiagID = diag::err_mutable_const;
14117 
14118     if (DiagID) {
14119       SourceLocation ErrLoc = Loc;
14120       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14121         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14122       Diag(ErrLoc, DiagID);
14123       if (DiagID != diag::ext_mutable_reference) {
14124         Mutable = false;
14125         InvalidDecl = true;
14126       }
14127     }
14128   }
14129 
14130   // C++11 [class.union]p8 (DR1460):
14131   //   At most one variant member of a union may have a
14132   //   brace-or-equal-initializer.
14133   if (InitStyle != ICIS_NoInit)
14134     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14135 
14136   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14137                                        BitWidth, Mutable, InitStyle);
14138   if (InvalidDecl)
14139     NewFD->setInvalidDecl();
14140 
14141   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14142     Diag(Loc, diag::err_duplicate_member) << II;
14143     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14144     NewFD->setInvalidDecl();
14145   }
14146 
14147   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14148     if (Record->isUnion()) {
14149       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14150         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14151         if (RDecl->getDefinition()) {
14152           // C++ [class.union]p1: An object of a class with a non-trivial
14153           // constructor, a non-trivial copy constructor, a non-trivial
14154           // destructor, or a non-trivial copy assignment operator
14155           // cannot be a member of a union, nor can an array of such
14156           // objects.
14157           if (CheckNontrivialField(NewFD))
14158             NewFD->setInvalidDecl();
14159         }
14160       }
14161 
14162       // C++ [class.union]p1: If a union contains a member of reference type,
14163       // the program is ill-formed, except when compiling with MSVC extensions
14164       // enabled.
14165       if (EltTy->isReferenceType()) {
14166         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14167                                     diag::ext_union_member_of_reference_type :
14168                                     diag::err_union_member_of_reference_type)
14169           << NewFD->getDeclName() << EltTy;
14170         if (!getLangOpts().MicrosoftExt)
14171           NewFD->setInvalidDecl();
14172       }
14173     }
14174   }
14175 
14176   // FIXME: We need to pass in the attributes given an AST
14177   // representation, not a parser representation.
14178   if (D) {
14179     // FIXME: The current scope is almost... but not entirely... correct here.
14180     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14181 
14182     if (NewFD->hasAttrs())
14183       CheckAlignasUnderalignment(NewFD);
14184   }
14185 
14186   // In auto-retain/release, infer strong retension for fields of
14187   // retainable type.
14188   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14189     NewFD->setInvalidDecl();
14190 
14191   if (T.isObjCGCWeak())
14192     Diag(Loc, diag::warn_attribute_weak_on_field);
14193 
14194   NewFD->setAccess(AS);
14195   return NewFD;
14196 }
14197 
14198 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14199   assert(FD);
14200   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14201 
14202   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14203     return false;
14204 
14205   QualType EltTy = Context.getBaseElementType(FD->getType());
14206   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14207     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14208     if (RDecl->getDefinition()) {
14209       // We check for copy constructors before constructors
14210       // because otherwise we'll never get complaints about
14211       // copy constructors.
14212 
14213       CXXSpecialMember member = CXXInvalid;
14214       // We're required to check for any non-trivial constructors. Since the
14215       // implicit default constructor is suppressed if there are any
14216       // user-declared constructors, we just need to check that there is a
14217       // trivial default constructor and a trivial copy constructor. (We don't
14218       // worry about move constructors here, since this is a C++98 check.)
14219       if (RDecl->hasNonTrivialCopyConstructor())
14220         member = CXXCopyConstructor;
14221       else if (!RDecl->hasTrivialDefaultConstructor())
14222         member = CXXDefaultConstructor;
14223       else if (RDecl->hasNonTrivialCopyAssignment())
14224         member = CXXCopyAssignment;
14225       else if (RDecl->hasNonTrivialDestructor())
14226         member = CXXDestructor;
14227 
14228       if (member != CXXInvalid) {
14229         if (!getLangOpts().CPlusPlus11 &&
14230             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14231           // Objective-C++ ARC: it is an error to have a non-trivial field of
14232           // a union. However, system headers in Objective-C programs
14233           // occasionally have Objective-C lifetime objects within unions,
14234           // and rather than cause the program to fail, we make those
14235           // members unavailable.
14236           SourceLocation Loc = FD->getLocation();
14237           if (getSourceManager().isInSystemHeader(Loc)) {
14238             if (!FD->hasAttr<UnavailableAttr>())
14239               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14240                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14241             return false;
14242           }
14243         }
14244 
14245         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14246                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14247                diag::err_illegal_union_or_anon_struct_member)
14248           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14249         DiagnoseNontrivial(RDecl, member);
14250         return !getLangOpts().CPlusPlus11;
14251       }
14252     }
14253   }
14254 
14255   return false;
14256 }
14257 
14258 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14259 ///  AST enum value.
14260 static ObjCIvarDecl::AccessControl
14261 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14262   switch (ivarVisibility) {
14263   default: llvm_unreachable("Unknown visitibility kind");
14264   case tok::objc_private: return ObjCIvarDecl::Private;
14265   case tok::objc_public: return ObjCIvarDecl::Public;
14266   case tok::objc_protected: return ObjCIvarDecl::Protected;
14267   case tok::objc_package: return ObjCIvarDecl::Package;
14268   }
14269 }
14270 
14271 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14272 /// in order to create an IvarDecl object for it.
14273 Decl *Sema::ActOnIvar(Scope *S,
14274                                 SourceLocation DeclStart,
14275                                 Declarator &D, Expr *BitfieldWidth,
14276                                 tok::ObjCKeywordKind Visibility) {
14277 
14278   IdentifierInfo *II = D.getIdentifier();
14279   Expr *BitWidth = (Expr*)BitfieldWidth;
14280   SourceLocation Loc = DeclStart;
14281   if (II) Loc = D.getIdentifierLoc();
14282 
14283   // FIXME: Unnamed fields can be handled in various different ways, for
14284   // example, unnamed unions inject all members into the struct namespace!
14285 
14286   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14287   QualType T = TInfo->getType();
14288 
14289   if (BitWidth) {
14290     // 6.7.2.1p3, 6.7.2.1p4
14291     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14292     if (!BitWidth)
14293       D.setInvalidType();
14294   } else {
14295     // Not a bitfield.
14296 
14297     // validate II.
14298 
14299   }
14300   if (T->isReferenceType()) {
14301     Diag(Loc, diag::err_ivar_reference_type);
14302     D.setInvalidType();
14303   }
14304   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14305   // than a variably modified type.
14306   else if (T->isVariablyModifiedType()) {
14307     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14308     D.setInvalidType();
14309   }
14310 
14311   // Get the visibility (access control) for this ivar.
14312   ObjCIvarDecl::AccessControl ac =
14313     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14314                                         : ObjCIvarDecl::None;
14315   // Must set ivar's DeclContext to its enclosing interface.
14316   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14317   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14318     return nullptr;
14319   ObjCContainerDecl *EnclosingContext;
14320   if (ObjCImplementationDecl *IMPDecl =
14321       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14322     if (LangOpts.ObjCRuntime.isFragile()) {
14323     // Case of ivar declared in an implementation. Context is that of its class.
14324       EnclosingContext = IMPDecl->getClassInterface();
14325       assert(EnclosingContext && "Implementation has no class interface!");
14326     }
14327     else
14328       EnclosingContext = EnclosingDecl;
14329   } else {
14330     if (ObjCCategoryDecl *CDecl =
14331         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14332       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14333         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14334         return nullptr;
14335       }
14336     }
14337     EnclosingContext = EnclosingDecl;
14338   }
14339 
14340   // Construct the decl.
14341   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14342                                              DeclStart, Loc, II, T,
14343                                              TInfo, ac, (Expr *)BitfieldWidth);
14344 
14345   if (II) {
14346     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14347                                            ForRedeclaration);
14348     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14349         && !isa<TagDecl>(PrevDecl)) {
14350       Diag(Loc, diag::err_duplicate_member) << II;
14351       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14352       NewID->setInvalidDecl();
14353     }
14354   }
14355 
14356   // Process attributes attached to the ivar.
14357   ProcessDeclAttributes(S, NewID, D);
14358 
14359   if (D.isInvalidType())
14360     NewID->setInvalidDecl();
14361 
14362   // In ARC, infer 'retaining' for ivars of retainable type.
14363   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14364     NewID->setInvalidDecl();
14365 
14366   if (D.getDeclSpec().isModulePrivateSpecified())
14367     NewID->setModulePrivate();
14368 
14369   if (II) {
14370     // FIXME: When interfaces are DeclContexts, we'll need to add
14371     // these to the interface.
14372     S->AddDecl(NewID);
14373     IdResolver.AddDecl(NewID);
14374   }
14375 
14376   if (LangOpts.ObjCRuntime.isNonFragile() &&
14377       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14378     Diag(Loc, diag::warn_ivars_in_interface);
14379 
14380   return NewID;
14381 }
14382 
14383 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14384 /// class and class extensions. For every class \@interface and class
14385 /// extension \@interface, if the last ivar is a bitfield of any type,
14386 /// then add an implicit `char :0` ivar to the end of that interface.
14387 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14388                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14389   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14390     return;
14391 
14392   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14393   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14394 
14395   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14396     return;
14397   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14398   if (!ID) {
14399     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14400       if (!CD->IsClassExtension())
14401         return;
14402     }
14403     // No need to add this to end of @implementation.
14404     else
14405       return;
14406   }
14407   // All conditions are met. Add a new bitfield to the tail end of ivars.
14408   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14409   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14410 
14411   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14412                               DeclLoc, DeclLoc, nullptr,
14413                               Context.CharTy,
14414                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14415                                                                DeclLoc),
14416                               ObjCIvarDecl::Private, BW,
14417                               true);
14418   AllIvarDecls.push_back(Ivar);
14419 }
14420 
14421 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14422                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14423                        SourceLocation RBrac, AttributeList *Attr) {
14424   assert(EnclosingDecl && "missing record or interface decl");
14425 
14426   // If this is an Objective-C @implementation or category and we have
14427   // new fields here we should reset the layout of the interface since
14428   // it will now change.
14429   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14430     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14431     switch (DC->getKind()) {
14432     default: break;
14433     case Decl::ObjCCategory:
14434       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14435       break;
14436     case Decl::ObjCImplementation:
14437       Context.
14438         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14439       break;
14440     }
14441   }
14442 
14443   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14444 
14445   // Start counting up the number of named members; make sure to include
14446   // members of anonymous structs and unions in the total.
14447   unsigned NumNamedMembers = 0;
14448   if (Record) {
14449     for (const auto *I : Record->decls()) {
14450       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14451         if (IFD->getDeclName())
14452           ++NumNamedMembers;
14453     }
14454   }
14455 
14456   // Verify that all the fields are okay.
14457   SmallVector<FieldDecl*, 32> RecFields;
14458 
14459   bool ARCErrReported = false;
14460   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14461        i != end; ++i) {
14462     FieldDecl *FD = cast<FieldDecl>(*i);
14463 
14464     // Get the type for the field.
14465     const Type *FDTy = FD->getType().getTypePtr();
14466 
14467     if (!FD->isAnonymousStructOrUnion()) {
14468       // Remember all fields written by the user.
14469       RecFields.push_back(FD);
14470     }
14471 
14472     // If the field is already invalid for some reason, don't emit more
14473     // diagnostics about it.
14474     if (FD->isInvalidDecl()) {
14475       EnclosingDecl->setInvalidDecl();
14476       continue;
14477     }
14478 
14479     // C99 6.7.2.1p2:
14480     //   A structure or union shall not contain a member with
14481     //   incomplete or function type (hence, a structure shall not
14482     //   contain an instance of itself, but may contain a pointer to
14483     //   an instance of itself), except that the last member of a
14484     //   structure with more than one named member may have incomplete
14485     //   array type; such a structure (and any union containing,
14486     //   possibly recursively, a member that is such a structure)
14487     //   shall not be a member of a structure or an element of an
14488     //   array.
14489     if (FDTy->isFunctionType()) {
14490       // Field declared as a function.
14491       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14492         << FD->getDeclName();
14493       FD->setInvalidDecl();
14494       EnclosingDecl->setInvalidDecl();
14495       continue;
14496     } else if (FDTy->isIncompleteArrayType() && Record &&
14497                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14498                 ((getLangOpts().MicrosoftExt ||
14499                   getLangOpts().CPlusPlus) &&
14500                  (i + 1 == Fields.end() || Record->isUnion())))) {
14501       // Flexible array member.
14502       // Microsoft and g++ is more permissive regarding flexible array.
14503       // It will accept flexible array in union and also
14504       // as the sole element of a struct/class.
14505       unsigned DiagID = 0;
14506       if (Record->isUnion())
14507         DiagID = getLangOpts().MicrosoftExt
14508                      ? diag::ext_flexible_array_union_ms
14509                      : getLangOpts().CPlusPlus
14510                            ? diag::ext_flexible_array_union_gnu
14511                            : diag::err_flexible_array_union;
14512       else if (NumNamedMembers < 1)
14513         DiagID = getLangOpts().MicrosoftExt
14514                      ? diag::ext_flexible_array_empty_aggregate_ms
14515                      : getLangOpts().CPlusPlus
14516                            ? diag::ext_flexible_array_empty_aggregate_gnu
14517                            : diag::err_flexible_array_empty_aggregate;
14518 
14519       if (DiagID)
14520         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14521                                         << Record->getTagKind();
14522       // While the layout of types that contain virtual bases is not specified
14523       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14524       // virtual bases after the derived members.  This would make a flexible
14525       // array member declared at the end of an object not adjacent to the end
14526       // of the type.
14527       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14528         if (RD->getNumVBases() != 0)
14529           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14530             << FD->getDeclName() << Record->getTagKind();
14531       if (!getLangOpts().C99)
14532         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14533           << FD->getDeclName() << Record->getTagKind();
14534 
14535       // If the element type has a non-trivial destructor, we would not
14536       // implicitly destroy the elements, so disallow it for now.
14537       //
14538       // FIXME: GCC allows this. We should probably either implicitly delete
14539       // the destructor of the containing class, or just allow this.
14540       QualType BaseElem = Context.getBaseElementType(FD->getType());
14541       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14542         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14543           << FD->getDeclName() << FD->getType();
14544         FD->setInvalidDecl();
14545         EnclosingDecl->setInvalidDecl();
14546         continue;
14547       }
14548       // Okay, we have a legal flexible array member at the end of the struct.
14549       Record->setHasFlexibleArrayMember(true);
14550     } else if (!FDTy->isDependentType() &&
14551                RequireCompleteType(FD->getLocation(), FD->getType(),
14552                                    diag::err_field_incomplete)) {
14553       // Incomplete type
14554       FD->setInvalidDecl();
14555       EnclosingDecl->setInvalidDecl();
14556       continue;
14557     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14558       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14559         // A type which contains a flexible array member is considered to be a
14560         // flexible array member.
14561         Record->setHasFlexibleArrayMember(true);
14562         if (!Record->isUnion()) {
14563           // If this is a struct/class and this is not the last element, reject
14564           // it.  Note that GCC supports variable sized arrays in the middle of
14565           // structures.
14566           if (i + 1 != Fields.end())
14567             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14568               << FD->getDeclName() << FD->getType();
14569           else {
14570             // We support flexible arrays at the end of structs in
14571             // other structs as an extension.
14572             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14573               << FD->getDeclName();
14574           }
14575         }
14576       }
14577       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14578           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14579                                  diag::err_abstract_type_in_decl,
14580                                  AbstractIvarType)) {
14581         // Ivars can not have abstract class types
14582         FD->setInvalidDecl();
14583       }
14584       if (Record && FDTTy->getDecl()->hasObjectMember())
14585         Record->setHasObjectMember(true);
14586       if (Record && FDTTy->getDecl()->hasVolatileMember())
14587         Record->setHasVolatileMember(true);
14588     } else if (FDTy->isObjCObjectType()) {
14589       /// A field cannot be an Objective-c object
14590       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14591         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14592       QualType T = Context.getObjCObjectPointerType(FD->getType());
14593       FD->setType(T);
14594     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14595                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14596       // It's an error in ARC if a field has lifetime.
14597       // We don't want to report this in a system header, though,
14598       // so we just make the field unavailable.
14599       // FIXME: that's really not sufficient; we need to make the type
14600       // itself invalid to, say, initialize or copy.
14601       QualType T = FD->getType();
14602       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14603       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14604         SourceLocation loc = FD->getLocation();
14605         if (getSourceManager().isInSystemHeader(loc)) {
14606           if (!FD->hasAttr<UnavailableAttr>()) {
14607             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14608                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14609           }
14610         } else {
14611           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14612             << T->isBlockPointerType() << Record->getTagKind();
14613         }
14614         ARCErrReported = true;
14615       }
14616     } else if (getLangOpts().ObjC1 &&
14617                getLangOpts().getGC() != LangOptions::NonGC &&
14618                Record && !Record->hasObjectMember()) {
14619       if (FD->getType()->isObjCObjectPointerType() ||
14620           FD->getType().isObjCGCStrong())
14621         Record->setHasObjectMember(true);
14622       else if (Context.getAsArrayType(FD->getType())) {
14623         QualType BaseType = Context.getBaseElementType(FD->getType());
14624         if (BaseType->isRecordType() &&
14625             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14626           Record->setHasObjectMember(true);
14627         else if (BaseType->isObjCObjectPointerType() ||
14628                  BaseType.isObjCGCStrong())
14629                Record->setHasObjectMember(true);
14630       }
14631     }
14632     if (Record && FD->getType().isVolatileQualified())
14633       Record->setHasVolatileMember(true);
14634     // Keep track of the number of named members.
14635     if (FD->getIdentifier())
14636       ++NumNamedMembers;
14637   }
14638 
14639   // Okay, we successfully defined 'Record'.
14640   if (Record) {
14641     bool Completed = false;
14642     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14643       if (!CXXRecord->isInvalidDecl()) {
14644         // Set access bits correctly on the directly-declared conversions.
14645         for (CXXRecordDecl::conversion_iterator
14646                I = CXXRecord->conversion_begin(),
14647                E = CXXRecord->conversion_end(); I != E; ++I)
14648           I.setAccess((*I)->getAccess());
14649       }
14650 
14651       if (!CXXRecord->isDependentType()) {
14652         if (CXXRecord->hasUserDeclaredDestructor()) {
14653           // Adjust user-defined destructor exception spec.
14654           if (getLangOpts().CPlusPlus11)
14655             AdjustDestructorExceptionSpec(CXXRecord,
14656                                           CXXRecord->getDestructor());
14657         }
14658 
14659         if (!CXXRecord->isInvalidDecl()) {
14660           // Add any implicitly-declared members to this class.
14661           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14662 
14663           // If we have virtual base classes, we may end up finding multiple
14664           // final overriders for a given virtual function. Check for this
14665           // problem now.
14666           if (CXXRecord->getNumVBases()) {
14667             CXXFinalOverriderMap FinalOverriders;
14668             CXXRecord->getFinalOverriders(FinalOverriders);
14669 
14670             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14671                                              MEnd = FinalOverriders.end();
14672                  M != MEnd; ++M) {
14673               for (OverridingMethods::iterator SO = M->second.begin(),
14674                                             SOEnd = M->second.end();
14675                    SO != SOEnd; ++SO) {
14676                 assert(SO->second.size() > 0 &&
14677                        "Virtual function without overridding functions?");
14678                 if (SO->second.size() == 1)
14679                   continue;
14680 
14681                 // C++ [class.virtual]p2:
14682                 //   In a derived class, if a virtual member function of a base
14683                 //   class subobject has more than one final overrider the
14684                 //   program is ill-formed.
14685                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14686                   << (const NamedDecl *)M->first << Record;
14687                 Diag(M->first->getLocation(),
14688                      diag::note_overridden_virtual_function);
14689                 for (OverridingMethods::overriding_iterator
14690                           OM = SO->second.begin(),
14691                        OMEnd = SO->second.end();
14692                      OM != OMEnd; ++OM)
14693                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14694                     << (const NamedDecl *)M->first << OM->Method->getParent();
14695 
14696                 Record->setInvalidDecl();
14697               }
14698             }
14699             CXXRecord->completeDefinition(&FinalOverriders);
14700             Completed = true;
14701           }
14702         }
14703       }
14704     }
14705 
14706     if (!Completed)
14707       Record->completeDefinition();
14708 
14709     // We may have deferred checking for a deleted destructor. Check now.
14710     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14711       auto *Dtor = CXXRecord->getDestructor();
14712       if (Dtor && Dtor->isImplicit() &&
14713           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14714         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14715     }
14716 
14717     if (Record->hasAttrs()) {
14718       CheckAlignasUnderalignment(Record);
14719 
14720       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14721         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14722                                            IA->getRange(), IA->getBestCase(),
14723                                            IA->getSemanticSpelling());
14724     }
14725 
14726     // Check if the structure/union declaration is a type that can have zero
14727     // size in C. For C this is a language extension, for C++ it may cause
14728     // compatibility problems.
14729     bool CheckForZeroSize;
14730     if (!getLangOpts().CPlusPlus) {
14731       CheckForZeroSize = true;
14732     } else {
14733       // For C++ filter out types that cannot be referenced in C code.
14734       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14735       CheckForZeroSize =
14736           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14737           !CXXRecord->isDependentType() &&
14738           CXXRecord->isCLike();
14739     }
14740     if (CheckForZeroSize) {
14741       bool ZeroSize = true;
14742       bool IsEmpty = true;
14743       unsigned NonBitFields = 0;
14744       for (RecordDecl::field_iterator I = Record->field_begin(),
14745                                       E = Record->field_end();
14746            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14747         IsEmpty = false;
14748         if (I->isUnnamedBitfield()) {
14749           if (I->getBitWidthValue(Context) > 0)
14750             ZeroSize = false;
14751         } else {
14752           ++NonBitFields;
14753           QualType FieldType = I->getType();
14754           if (FieldType->isIncompleteType() ||
14755               !Context.getTypeSizeInChars(FieldType).isZero())
14756             ZeroSize = false;
14757         }
14758       }
14759 
14760       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14761       // allowed in C++, but warn if its declaration is inside
14762       // extern "C" block.
14763       if (ZeroSize) {
14764         Diag(RecLoc, getLangOpts().CPlusPlus ?
14765                          diag::warn_zero_size_struct_union_in_extern_c :
14766                          diag::warn_zero_size_struct_union_compat)
14767           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14768       }
14769 
14770       // Structs without named members are extension in C (C99 6.7.2.1p7),
14771       // but are accepted by GCC.
14772       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14773         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14774                                diag::ext_no_named_members_in_struct_union)
14775           << Record->isUnion();
14776       }
14777     }
14778   } else {
14779     ObjCIvarDecl **ClsFields =
14780       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14781     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14782       ID->setEndOfDefinitionLoc(RBrac);
14783       // Add ivar's to class's DeclContext.
14784       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14785         ClsFields[i]->setLexicalDeclContext(ID);
14786         ID->addDecl(ClsFields[i]);
14787       }
14788       // Must enforce the rule that ivars in the base classes may not be
14789       // duplicates.
14790       if (ID->getSuperClass())
14791         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14792     } else if (ObjCImplementationDecl *IMPDecl =
14793                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14794       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14795       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14796         // Ivar declared in @implementation never belongs to the implementation.
14797         // Only it is in implementation's lexical context.
14798         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14799       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14800       IMPDecl->setIvarLBraceLoc(LBrac);
14801       IMPDecl->setIvarRBraceLoc(RBrac);
14802     } else if (ObjCCategoryDecl *CDecl =
14803                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14804       // case of ivars in class extension; all other cases have been
14805       // reported as errors elsewhere.
14806       // FIXME. Class extension does not have a LocEnd field.
14807       // CDecl->setLocEnd(RBrac);
14808       // Add ivar's to class extension's DeclContext.
14809       // Diagnose redeclaration of private ivars.
14810       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14811       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14812         if (IDecl) {
14813           if (const ObjCIvarDecl *ClsIvar =
14814               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14815             Diag(ClsFields[i]->getLocation(),
14816                  diag::err_duplicate_ivar_declaration);
14817             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14818             continue;
14819           }
14820           for (const auto *Ext : IDecl->known_extensions()) {
14821             if (const ObjCIvarDecl *ClsExtIvar
14822                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14823               Diag(ClsFields[i]->getLocation(),
14824                    diag::err_duplicate_ivar_declaration);
14825               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14826               continue;
14827             }
14828           }
14829         }
14830         ClsFields[i]->setLexicalDeclContext(CDecl);
14831         CDecl->addDecl(ClsFields[i]);
14832       }
14833       CDecl->setIvarLBraceLoc(LBrac);
14834       CDecl->setIvarRBraceLoc(RBrac);
14835     }
14836   }
14837 
14838   if (Attr)
14839     ProcessDeclAttributeList(S, Record, Attr);
14840 }
14841 
14842 /// \brief Determine whether the given integral value is representable within
14843 /// the given type T.
14844 static bool isRepresentableIntegerValue(ASTContext &Context,
14845                                         llvm::APSInt &Value,
14846                                         QualType T) {
14847   assert(T->isIntegralType(Context) && "Integral type required!");
14848   unsigned BitWidth = Context.getIntWidth(T);
14849 
14850   if (Value.isUnsigned() || Value.isNonNegative()) {
14851     if (T->isSignedIntegerOrEnumerationType())
14852       --BitWidth;
14853     return Value.getActiveBits() <= BitWidth;
14854   }
14855   return Value.getMinSignedBits() <= BitWidth;
14856 }
14857 
14858 // \brief Given an integral type, return the next larger integral type
14859 // (or a NULL type of no such type exists).
14860 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14861   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14862   // enum checking below.
14863   assert(T->isIntegralType(Context) && "Integral type required!");
14864   const unsigned NumTypes = 4;
14865   QualType SignedIntegralTypes[NumTypes] = {
14866     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14867   };
14868   QualType UnsignedIntegralTypes[NumTypes] = {
14869     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14870     Context.UnsignedLongLongTy
14871   };
14872 
14873   unsigned BitWidth = Context.getTypeSize(T);
14874   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14875                                                         : UnsignedIntegralTypes;
14876   for (unsigned I = 0; I != NumTypes; ++I)
14877     if (Context.getTypeSize(Types[I]) > BitWidth)
14878       return Types[I];
14879 
14880   return QualType();
14881 }
14882 
14883 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14884                                           EnumConstantDecl *LastEnumConst,
14885                                           SourceLocation IdLoc,
14886                                           IdentifierInfo *Id,
14887                                           Expr *Val) {
14888   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14889   llvm::APSInt EnumVal(IntWidth);
14890   QualType EltTy;
14891 
14892   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14893     Val = nullptr;
14894 
14895   if (Val)
14896     Val = DefaultLvalueConversion(Val).get();
14897 
14898   if (Val) {
14899     if (Enum->isDependentType() || Val->isTypeDependent())
14900       EltTy = Context.DependentTy;
14901     else {
14902       SourceLocation ExpLoc;
14903       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14904           !getLangOpts().MSVCCompat) {
14905         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14906         // constant-expression in the enumerator-definition shall be a converted
14907         // constant expression of the underlying type.
14908         EltTy = Enum->getIntegerType();
14909         ExprResult Converted =
14910           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14911                                            CCEK_Enumerator);
14912         if (Converted.isInvalid())
14913           Val = nullptr;
14914         else
14915           Val = Converted.get();
14916       } else if (!Val->isValueDependent() &&
14917                  !(Val = VerifyIntegerConstantExpression(Val,
14918                                                          &EnumVal).get())) {
14919         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14920       } else {
14921         if (Enum->isFixed()) {
14922           EltTy = Enum->getIntegerType();
14923 
14924           // In Obj-C and Microsoft mode, require the enumeration value to be
14925           // representable in the underlying type of the enumeration. In C++11,
14926           // we perform a non-narrowing conversion as part of converted constant
14927           // expression checking.
14928           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14929             if (getLangOpts().MSVCCompat) {
14930               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14931               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14932             } else
14933               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14934           } else
14935             Val = ImpCastExprToType(Val, EltTy,
14936                                     EltTy->isBooleanType() ?
14937                                     CK_IntegralToBoolean : CK_IntegralCast)
14938                     .get();
14939         } else if (getLangOpts().CPlusPlus) {
14940           // C++11 [dcl.enum]p5:
14941           //   If the underlying type is not fixed, the type of each enumerator
14942           //   is the type of its initializing value:
14943           //     - If an initializer is specified for an enumerator, the
14944           //       initializing value has the same type as the expression.
14945           EltTy = Val->getType();
14946         } else {
14947           // C99 6.7.2.2p2:
14948           //   The expression that defines the value of an enumeration constant
14949           //   shall be an integer constant expression that has a value
14950           //   representable as an int.
14951 
14952           // Complain if the value is not representable in an int.
14953           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14954             Diag(IdLoc, diag::ext_enum_value_not_int)
14955               << EnumVal.toString(10) << Val->getSourceRange()
14956               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14957           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14958             // Force the type of the expression to 'int'.
14959             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14960           }
14961           EltTy = Val->getType();
14962         }
14963       }
14964     }
14965   }
14966 
14967   if (!Val) {
14968     if (Enum->isDependentType())
14969       EltTy = Context.DependentTy;
14970     else if (!LastEnumConst) {
14971       // C++0x [dcl.enum]p5:
14972       //   If the underlying type is not fixed, the type of each enumerator
14973       //   is the type of its initializing value:
14974       //     - If no initializer is specified for the first enumerator, the
14975       //       initializing value has an unspecified integral type.
14976       //
14977       // GCC uses 'int' for its unspecified integral type, as does
14978       // C99 6.7.2.2p3.
14979       if (Enum->isFixed()) {
14980         EltTy = Enum->getIntegerType();
14981       }
14982       else {
14983         EltTy = Context.IntTy;
14984       }
14985     } else {
14986       // Assign the last value + 1.
14987       EnumVal = LastEnumConst->getInitVal();
14988       ++EnumVal;
14989       EltTy = LastEnumConst->getType();
14990 
14991       // Check for overflow on increment.
14992       if (EnumVal < LastEnumConst->getInitVal()) {
14993         // C++0x [dcl.enum]p5:
14994         //   If the underlying type is not fixed, the type of each enumerator
14995         //   is the type of its initializing value:
14996         //
14997         //     - Otherwise the type of the initializing value is the same as
14998         //       the type of the initializing value of the preceding enumerator
14999         //       unless the incremented value is not representable in that type,
15000         //       in which case the type is an unspecified integral type
15001         //       sufficient to contain the incremented value. If no such type
15002         //       exists, the program is ill-formed.
15003         QualType T = getNextLargerIntegralType(Context, EltTy);
15004         if (T.isNull() || Enum->isFixed()) {
15005           // There is no integral type larger enough to represent this
15006           // value. Complain, then allow the value to wrap around.
15007           EnumVal = LastEnumConst->getInitVal();
15008           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15009           ++EnumVal;
15010           if (Enum->isFixed())
15011             // When the underlying type is fixed, this is ill-formed.
15012             Diag(IdLoc, diag::err_enumerator_wrapped)
15013               << EnumVal.toString(10)
15014               << EltTy;
15015           else
15016             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15017               << EnumVal.toString(10);
15018         } else {
15019           EltTy = T;
15020         }
15021 
15022         // Retrieve the last enumerator's value, extent that type to the
15023         // type that is supposed to be large enough to represent the incremented
15024         // value, then increment.
15025         EnumVal = LastEnumConst->getInitVal();
15026         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15027         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15028         ++EnumVal;
15029 
15030         // If we're not in C++, diagnose the overflow of enumerator values,
15031         // which in C99 means that the enumerator value is not representable in
15032         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15033         // permits enumerator values that are representable in some larger
15034         // integral type.
15035         if (!getLangOpts().CPlusPlus && !T.isNull())
15036           Diag(IdLoc, diag::warn_enum_value_overflow);
15037       } else if (!getLangOpts().CPlusPlus &&
15038                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15039         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15040         Diag(IdLoc, diag::ext_enum_value_not_int)
15041           << EnumVal.toString(10) << 1;
15042       }
15043     }
15044   }
15045 
15046   if (!EltTy->isDependentType()) {
15047     // Make the enumerator value match the signedness and size of the
15048     // enumerator's type.
15049     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15050     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15051   }
15052 
15053   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15054                                   Val, EnumVal);
15055 }
15056 
15057 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15058                                                 SourceLocation IILoc) {
15059   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15060       !getLangOpts().CPlusPlus)
15061     return SkipBodyInfo();
15062 
15063   // We have an anonymous enum definition. Look up the first enumerator to
15064   // determine if we should merge the definition with an existing one and
15065   // skip the body.
15066   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15067                                          ForRedeclaration);
15068   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15069   if (!PrevECD)
15070     return SkipBodyInfo();
15071 
15072   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15073   NamedDecl *Hidden;
15074   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15075     SkipBodyInfo Skip;
15076     Skip.Previous = Hidden;
15077     return Skip;
15078   }
15079 
15080   return SkipBodyInfo();
15081 }
15082 
15083 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15084                               SourceLocation IdLoc, IdentifierInfo *Id,
15085                               AttributeList *Attr,
15086                               SourceLocation EqualLoc, Expr *Val) {
15087   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15088   EnumConstantDecl *LastEnumConst =
15089     cast_or_null<EnumConstantDecl>(lastEnumConst);
15090 
15091   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15092   // we find one that is.
15093   S = getNonFieldDeclScope(S);
15094 
15095   // Verify that there isn't already something declared with this name in this
15096   // scope.
15097   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15098                                          ForRedeclaration);
15099   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15100     // Maybe we will complain about the shadowed template parameter.
15101     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15102     // Just pretend that we didn't see the previous declaration.
15103     PrevDecl = nullptr;
15104   }
15105 
15106   // C++ [class.mem]p15:
15107   // If T is the name of a class, then each of the following shall have a name
15108   // different from T:
15109   // - every enumerator of every member of class T that is an unscoped
15110   // enumerated type
15111   if (!TheEnumDecl->isScoped())
15112     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15113                             DeclarationNameInfo(Id, IdLoc));
15114 
15115   EnumConstantDecl *New =
15116     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15117   if (!New)
15118     return nullptr;
15119 
15120   if (PrevDecl) {
15121     // When in C++, we may get a TagDecl with the same name; in this case the
15122     // enum constant will 'hide' the tag.
15123     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15124            "Received TagDecl when not in C++!");
15125     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15126         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15127       if (isa<EnumConstantDecl>(PrevDecl))
15128         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15129       else
15130         Diag(IdLoc, diag::err_redefinition) << Id;
15131       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15132       return nullptr;
15133     }
15134   }
15135 
15136   // Process attributes.
15137   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15138 
15139   // Register this decl in the current scope stack.
15140   New->setAccess(TheEnumDecl->getAccess());
15141   PushOnScopeChains(New, S);
15142 
15143   ActOnDocumentableDecl(New);
15144 
15145   return New;
15146 }
15147 
15148 // Returns true when the enum initial expression does not trigger the
15149 // duplicate enum warning.  A few common cases are exempted as follows:
15150 // Element2 = Element1
15151 // Element2 = Element1 + 1
15152 // Element2 = Element1 - 1
15153 // Where Element2 and Element1 are from the same enum.
15154 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15155   Expr *InitExpr = ECD->getInitExpr();
15156   if (!InitExpr)
15157     return true;
15158   InitExpr = InitExpr->IgnoreImpCasts();
15159 
15160   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15161     if (!BO->isAdditiveOp())
15162       return true;
15163     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15164     if (!IL)
15165       return true;
15166     if (IL->getValue() != 1)
15167       return true;
15168 
15169     InitExpr = BO->getLHS();
15170   }
15171 
15172   // This checks if the elements are from the same enum.
15173   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15174   if (!DRE)
15175     return true;
15176 
15177   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15178   if (!EnumConstant)
15179     return true;
15180 
15181   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15182       Enum)
15183     return true;
15184 
15185   return false;
15186 }
15187 
15188 namespace {
15189 struct DupKey {
15190   int64_t val;
15191   bool isTombstoneOrEmptyKey;
15192   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15193     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15194 };
15195 
15196 static DupKey GetDupKey(const llvm::APSInt& Val) {
15197   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15198                 false);
15199 }
15200 
15201 struct DenseMapInfoDupKey {
15202   static DupKey getEmptyKey() { return DupKey(0, true); }
15203   static DupKey getTombstoneKey() { return DupKey(1, true); }
15204   static unsigned getHashValue(const DupKey Key) {
15205     return (unsigned)(Key.val * 37);
15206   }
15207   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15208     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15209            LHS.val == RHS.val;
15210   }
15211 };
15212 } // end anonymous namespace
15213 
15214 // Emits a warning when an element is implicitly set a value that
15215 // a previous element has already been set to.
15216 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15217                                         EnumDecl *Enum,
15218                                         QualType EnumType) {
15219   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15220     return;
15221   // Avoid anonymous enums
15222   if (!Enum->getIdentifier())
15223     return;
15224 
15225   // Only check for small enums.
15226   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15227     return;
15228 
15229   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15230   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15231 
15232   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15233   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15234           ValueToVectorMap;
15235 
15236   DuplicatesVector DupVector;
15237   ValueToVectorMap EnumMap;
15238 
15239   // Populate the EnumMap with all values represented by enum constants without
15240   // an initialier.
15241   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15242     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15243 
15244     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15245     // this constant.  Skip this enum since it may be ill-formed.
15246     if (!ECD) {
15247       return;
15248     }
15249 
15250     if (ECD->getInitExpr())
15251       continue;
15252 
15253     DupKey Key = GetDupKey(ECD->getInitVal());
15254     DeclOrVector &Entry = EnumMap[Key];
15255 
15256     // First time encountering this value.
15257     if (Entry.isNull())
15258       Entry = ECD;
15259   }
15260 
15261   // Create vectors for any values that has duplicates.
15262   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15263     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15264     if (!ValidDuplicateEnum(ECD, Enum))
15265       continue;
15266 
15267     DupKey Key = GetDupKey(ECD->getInitVal());
15268 
15269     DeclOrVector& Entry = EnumMap[Key];
15270     if (Entry.isNull())
15271       continue;
15272 
15273     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15274       // Ensure constants are different.
15275       if (D == ECD)
15276         continue;
15277 
15278       // Create new vector and push values onto it.
15279       ECDVector *Vec = new ECDVector();
15280       Vec->push_back(D);
15281       Vec->push_back(ECD);
15282 
15283       // Update entry to point to the duplicates vector.
15284       Entry = Vec;
15285 
15286       // Store the vector somewhere we can consult later for quick emission of
15287       // diagnostics.
15288       DupVector.push_back(Vec);
15289       continue;
15290     }
15291 
15292     ECDVector *Vec = Entry.get<ECDVector*>();
15293     // Make sure constants are not added more than once.
15294     if (*Vec->begin() == ECD)
15295       continue;
15296 
15297     Vec->push_back(ECD);
15298   }
15299 
15300   // Emit diagnostics.
15301   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15302                                   DupVectorEnd = DupVector.end();
15303        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15304     ECDVector *Vec = *DupVectorIter;
15305     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15306 
15307     // Emit warning for one enum constant.
15308     ECDVector::iterator I = Vec->begin();
15309     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15310       << (*I)->getName() << (*I)->getInitVal().toString(10)
15311       << (*I)->getSourceRange();
15312     ++I;
15313 
15314     // Emit one note for each of the remaining enum constants with
15315     // the same value.
15316     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15317       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15318         << (*I)->getName() << (*I)->getInitVal().toString(10)
15319         << (*I)->getSourceRange();
15320     delete Vec;
15321   }
15322 }
15323 
15324 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15325                              bool AllowMask) const {
15326   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15327   assert(ED->isCompleteDefinition() && "expected enum definition");
15328 
15329   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15330   llvm::APInt &FlagBits = R.first->second;
15331 
15332   if (R.second) {
15333     for (auto *E : ED->enumerators()) {
15334       const auto &EVal = E->getInitVal();
15335       // Only single-bit enumerators introduce new flag values.
15336       if (EVal.isPowerOf2())
15337         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15338     }
15339   }
15340 
15341   // A value is in a flag enum if either its bits are a subset of the enum's
15342   // flag bits (the first condition) or we are allowing masks and the same is
15343   // true of its complement (the second condition). When masks are allowed, we
15344   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15345   //
15346   // While it's true that any value could be used as a mask, the assumption is
15347   // that a mask will have all of the insignificant bits set. Anything else is
15348   // likely a logic error.
15349   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15350   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15351 }
15352 
15353 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15354                          Decl *EnumDeclX,
15355                          ArrayRef<Decl *> Elements,
15356                          Scope *S, AttributeList *Attr) {
15357   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15358   QualType EnumType = Context.getTypeDeclType(Enum);
15359 
15360   if (Attr)
15361     ProcessDeclAttributeList(S, Enum, Attr);
15362 
15363   if (Enum->isDependentType()) {
15364     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15365       EnumConstantDecl *ECD =
15366         cast_or_null<EnumConstantDecl>(Elements[i]);
15367       if (!ECD) continue;
15368 
15369       ECD->setType(EnumType);
15370     }
15371 
15372     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15373     return;
15374   }
15375 
15376   // TODO: If the result value doesn't fit in an int, it must be a long or long
15377   // long value.  ISO C does not support this, but GCC does as an extension,
15378   // emit a warning.
15379   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15380   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15381   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15382 
15383   // Verify that all the values are okay, compute the size of the values, and
15384   // reverse the list.
15385   unsigned NumNegativeBits = 0;
15386   unsigned NumPositiveBits = 0;
15387 
15388   // Keep track of whether all elements have type int.
15389   bool AllElementsInt = true;
15390 
15391   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15392     EnumConstantDecl *ECD =
15393       cast_or_null<EnumConstantDecl>(Elements[i]);
15394     if (!ECD) continue;  // Already issued a diagnostic.
15395 
15396     const llvm::APSInt &InitVal = ECD->getInitVal();
15397 
15398     // Keep track of the size of positive and negative values.
15399     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15400       NumPositiveBits = std::max(NumPositiveBits,
15401                                  (unsigned)InitVal.getActiveBits());
15402     else
15403       NumNegativeBits = std::max(NumNegativeBits,
15404                                  (unsigned)InitVal.getMinSignedBits());
15405 
15406     // Keep track of whether every enum element has type int (very commmon).
15407     if (AllElementsInt)
15408       AllElementsInt = ECD->getType() == Context.IntTy;
15409   }
15410 
15411   // Figure out the type that should be used for this enum.
15412   QualType BestType;
15413   unsigned BestWidth;
15414 
15415   // C++0x N3000 [conv.prom]p3:
15416   //   An rvalue of an unscoped enumeration type whose underlying
15417   //   type is not fixed can be converted to an rvalue of the first
15418   //   of the following types that can represent all the values of
15419   //   the enumeration: int, unsigned int, long int, unsigned long
15420   //   int, long long int, or unsigned long long int.
15421   // C99 6.4.4.3p2:
15422   //   An identifier declared as an enumeration constant has type int.
15423   // The C99 rule is modified by a gcc extension
15424   QualType BestPromotionType;
15425 
15426   bool Packed = Enum->hasAttr<PackedAttr>();
15427   // -fshort-enums is the equivalent to specifying the packed attribute on all
15428   // enum definitions.
15429   if (LangOpts.ShortEnums)
15430     Packed = true;
15431 
15432   if (Enum->isFixed()) {
15433     BestType = Enum->getIntegerType();
15434     if (BestType->isPromotableIntegerType())
15435       BestPromotionType = Context.getPromotedIntegerType(BestType);
15436     else
15437       BestPromotionType = BestType;
15438 
15439     BestWidth = Context.getIntWidth(BestType);
15440   }
15441   else if (NumNegativeBits) {
15442     // If there is a negative value, figure out the smallest integer type (of
15443     // int/long/longlong) that fits.
15444     // If it's packed, check also if it fits a char or a short.
15445     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15446       BestType = Context.SignedCharTy;
15447       BestWidth = CharWidth;
15448     } else if (Packed && NumNegativeBits <= ShortWidth &&
15449                NumPositiveBits < ShortWidth) {
15450       BestType = Context.ShortTy;
15451       BestWidth = ShortWidth;
15452     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15453       BestType = Context.IntTy;
15454       BestWidth = IntWidth;
15455     } else {
15456       BestWidth = Context.getTargetInfo().getLongWidth();
15457 
15458       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15459         BestType = Context.LongTy;
15460       } else {
15461         BestWidth = Context.getTargetInfo().getLongLongWidth();
15462 
15463         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15464           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15465         BestType = Context.LongLongTy;
15466       }
15467     }
15468     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15469   } else {
15470     // If there is no negative value, figure out the smallest type that fits
15471     // all of the enumerator values.
15472     // If it's packed, check also if it fits a char or a short.
15473     if (Packed && NumPositiveBits <= CharWidth) {
15474       BestType = Context.UnsignedCharTy;
15475       BestPromotionType = Context.IntTy;
15476       BestWidth = CharWidth;
15477     } else if (Packed && NumPositiveBits <= ShortWidth) {
15478       BestType = Context.UnsignedShortTy;
15479       BestPromotionType = Context.IntTy;
15480       BestWidth = ShortWidth;
15481     } else if (NumPositiveBits <= IntWidth) {
15482       BestType = Context.UnsignedIntTy;
15483       BestWidth = IntWidth;
15484       BestPromotionType
15485         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15486                            ? Context.UnsignedIntTy : Context.IntTy;
15487     } else if (NumPositiveBits <=
15488                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15489       BestType = Context.UnsignedLongTy;
15490       BestPromotionType
15491         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15492                            ? Context.UnsignedLongTy : Context.LongTy;
15493     } else {
15494       BestWidth = Context.getTargetInfo().getLongLongWidth();
15495       assert(NumPositiveBits <= BestWidth &&
15496              "How could an initializer get larger than ULL?");
15497       BestType = Context.UnsignedLongLongTy;
15498       BestPromotionType
15499         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15500                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15501     }
15502   }
15503 
15504   // Loop over all of the enumerator constants, changing their types to match
15505   // the type of the enum if needed.
15506   for (auto *D : Elements) {
15507     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15508     if (!ECD) continue;  // Already issued a diagnostic.
15509 
15510     // Standard C says the enumerators have int type, but we allow, as an
15511     // extension, the enumerators to be larger than int size.  If each
15512     // enumerator value fits in an int, type it as an int, otherwise type it the
15513     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15514     // that X has type 'int', not 'unsigned'.
15515 
15516     // Determine whether the value fits into an int.
15517     llvm::APSInt InitVal = ECD->getInitVal();
15518 
15519     // If it fits into an integer type, force it.  Otherwise force it to match
15520     // the enum decl type.
15521     QualType NewTy;
15522     unsigned NewWidth;
15523     bool NewSign;
15524     if (!getLangOpts().CPlusPlus &&
15525         !Enum->isFixed() &&
15526         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15527       NewTy = Context.IntTy;
15528       NewWidth = IntWidth;
15529       NewSign = true;
15530     } else if (ECD->getType() == BestType) {
15531       // Already the right type!
15532       if (getLangOpts().CPlusPlus)
15533         // C++ [dcl.enum]p4: Following the closing brace of an
15534         // enum-specifier, each enumerator has the type of its
15535         // enumeration.
15536         ECD->setType(EnumType);
15537       continue;
15538     } else {
15539       NewTy = BestType;
15540       NewWidth = BestWidth;
15541       NewSign = BestType->isSignedIntegerOrEnumerationType();
15542     }
15543 
15544     // Adjust the APSInt value.
15545     InitVal = InitVal.extOrTrunc(NewWidth);
15546     InitVal.setIsSigned(NewSign);
15547     ECD->setInitVal(InitVal);
15548 
15549     // Adjust the Expr initializer and type.
15550     if (ECD->getInitExpr() &&
15551         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15552       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15553                                                 CK_IntegralCast,
15554                                                 ECD->getInitExpr(),
15555                                                 /*base paths*/ nullptr,
15556                                                 VK_RValue));
15557     if (getLangOpts().CPlusPlus)
15558       // C++ [dcl.enum]p4: Following the closing brace of an
15559       // enum-specifier, each enumerator has the type of its
15560       // enumeration.
15561       ECD->setType(EnumType);
15562     else
15563       ECD->setType(NewTy);
15564   }
15565 
15566   Enum->completeDefinition(BestType, BestPromotionType,
15567                            NumPositiveBits, NumNegativeBits);
15568 
15569   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15570 
15571   if (Enum->hasAttr<FlagEnumAttr>()) {
15572     for (Decl *D : Elements) {
15573       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15574       if (!ECD) continue;  // Already issued a diagnostic.
15575 
15576       llvm::APSInt InitVal = ECD->getInitVal();
15577       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15578           !IsValueInFlagEnum(Enum, InitVal, true))
15579         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15580           << ECD << Enum;
15581     }
15582   }
15583 
15584   // Now that the enum type is defined, ensure it's not been underaligned.
15585   if (Enum->hasAttrs())
15586     CheckAlignasUnderalignment(Enum);
15587 }
15588 
15589 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15590                                   SourceLocation StartLoc,
15591                                   SourceLocation EndLoc) {
15592   StringLiteral *AsmString = cast<StringLiteral>(expr);
15593 
15594   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15595                                                    AsmString, StartLoc,
15596                                                    EndLoc);
15597   CurContext->addDecl(New);
15598   return New;
15599 }
15600 
15601 static void checkModuleImportContext(Sema &S, Module *M,
15602                                      SourceLocation ImportLoc, DeclContext *DC,
15603                                      bool FromInclude = false) {
15604   SourceLocation ExternCLoc;
15605 
15606   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15607     switch (LSD->getLanguage()) {
15608     case LinkageSpecDecl::lang_c:
15609       if (ExternCLoc.isInvalid())
15610         ExternCLoc = LSD->getLocStart();
15611       break;
15612     case LinkageSpecDecl::lang_cxx:
15613       break;
15614     }
15615     DC = LSD->getParent();
15616   }
15617 
15618   while (isa<LinkageSpecDecl>(DC))
15619     DC = DC->getParent();
15620 
15621   if (!isa<TranslationUnitDecl>(DC)) {
15622     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15623                           ? diag::ext_module_import_not_at_top_level_noop
15624                           : diag::err_module_import_not_at_top_level_fatal)
15625         << M->getFullModuleName() << DC;
15626     S.Diag(cast<Decl>(DC)->getLocStart(),
15627            diag::note_module_import_not_at_top_level) << DC;
15628   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15629     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15630       << M->getFullModuleName();
15631     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15632   }
15633 }
15634 
15635 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15636                                            ModuleDeclKind MDK,
15637                                            ModuleIdPath Path) {
15638   // 'module implementation' requires that we are not compiling a module of any
15639   // kind. 'module' and 'module partition' require that we are compiling a
15640   // module inteface (not a module map).
15641   auto CMK = getLangOpts().getCompilingModule();
15642   if (MDK == ModuleDeclKind::Implementation
15643           ? CMK != LangOptions::CMK_None
15644           : CMK != LangOptions::CMK_ModuleInterface) {
15645     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15646       << (unsigned)MDK;
15647     return nullptr;
15648   }
15649 
15650   // FIXME: Create a ModuleDecl and return it.
15651 
15652   // FIXME: Most of this work should be done by the preprocessor rather than
15653   // here, in case we look ahead across something where the current
15654   // module matters (eg a #include).
15655 
15656   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15657   // hierarchical module map modules, the dots here are just another character
15658   // that can appear in a module name. Flatten down to the actual module name.
15659   std::string ModuleName;
15660   for (auto &Piece : Path) {
15661     if (!ModuleName.empty())
15662       ModuleName += ".";
15663     ModuleName += Piece.first->getName();
15664   }
15665 
15666   // If a module name was explicitly specified on the command line, it must be
15667   // correct.
15668   if (!getLangOpts().CurrentModule.empty() &&
15669       getLangOpts().CurrentModule != ModuleName) {
15670     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15671         << SourceRange(Path.front().second, Path.back().second)
15672         << getLangOpts().CurrentModule;
15673     return nullptr;
15674   }
15675   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15676 
15677   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15678 
15679   switch (MDK) {
15680   case ModuleDeclKind::Module: {
15681     // FIXME: Check we're not in a submodule.
15682 
15683     // We can't have imported a definition of this module or parsed a module
15684     // map defining it already.
15685     if (auto *M = Map.findModule(ModuleName)) {
15686       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15687       if (M->DefinitionLoc.isValid())
15688         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15689       else if (const auto *FE = M->getASTFile())
15690         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15691             << FE->getName();
15692       return nullptr;
15693     }
15694 
15695     // Create a Module for the module that we're defining.
15696     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15697     assert(Mod && "module creation should not fail");
15698 
15699     // Enter the semantic scope of the module.
15700     ActOnModuleBegin(ModuleLoc, Mod);
15701     return nullptr;
15702   }
15703 
15704   case ModuleDeclKind::Partition:
15705     // FIXME: Check we are in a submodule of the named module.
15706     return nullptr;
15707 
15708   case ModuleDeclKind::Implementation:
15709     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15710         PP.getIdentifierInfo(ModuleName), Path[0].second);
15711 
15712     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15713     if (Import.isInvalid())
15714       return nullptr;
15715     return ConvertDeclToDeclGroup(Import.get());
15716   }
15717 
15718   llvm_unreachable("unexpected module decl kind");
15719 }
15720 
15721 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15722                                    SourceLocation ImportLoc,
15723                                    ModuleIdPath Path) {
15724   Module *Mod =
15725       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15726                                    /*IsIncludeDirective=*/false);
15727   if (!Mod)
15728     return true;
15729 
15730   VisibleModules.setVisible(Mod, ImportLoc);
15731 
15732   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15733 
15734   // FIXME: we should support importing a submodule within a different submodule
15735   // of the same top-level module. Until we do, make it an error rather than
15736   // silently ignoring the import.
15737   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15738   // warn on a redundant import of the current module?
15739   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15740       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15741     Diag(ImportLoc, getLangOpts().isCompilingModule()
15742                         ? diag::err_module_self_import
15743                         : diag::err_module_import_in_implementation)
15744         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15745 
15746   SmallVector<SourceLocation, 2> IdentifierLocs;
15747   Module *ModCheck = Mod;
15748   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15749     // If we've run out of module parents, just drop the remaining identifiers.
15750     // We need the length to be consistent.
15751     if (!ModCheck)
15752       break;
15753     ModCheck = ModCheck->Parent;
15754 
15755     IdentifierLocs.push_back(Path[I].second);
15756   }
15757 
15758   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15759   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15760                                           Mod, IdentifierLocs);
15761   if (!ModuleScopes.empty())
15762     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15763   TU->addDecl(Import);
15764   return Import;
15765 }
15766 
15767 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15768   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15769   BuildModuleInclude(DirectiveLoc, Mod);
15770 }
15771 
15772 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15773   // Determine whether we're in the #include buffer for a module. The #includes
15774   // in that buffer do not qualify as module imports; they're just an
15775   // implementation detail of us building the module.
15776   //
15777   // FIXME: Should we even get ActOnModuleInclude calls for those?
15778   bool IsInModuleIncludes =
15779       TUKind == TU_Module &&
15780       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15781 
15782   bool ShouldAddImport = !IsInModuleIncludes;
15783 
15784   // If this module import was due to an inclusion directive, create an
15785   // implicit import declaration to capture it in the AST.
15786   if (ShouldAddImport) {
15787     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15788     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15789                                                      DirectiveLoc, Mod,
15790                                                      DirectiveLoc);
15791     if (!ModuleScopes.empty())
15792       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15793     TU->addDecl(ImportD);
15794     Consumer.HandleImplicitImportDecl(ImportD);
15795   }
15796 
15797   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15798   VisibleModules.setVisible(Mod, DirectiveLoc);
15799 }
15800 
15801 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15802   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15803 
15804   ModuleScopes.push_back({});
15805   ModuleScopes.back().Module = Mod;
15806   if (getLangOpts().ModulesLocalVisibility)
15807     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15808 
15809   VisibleModules.setVisible(Mod, DirectiveLoc);
15810 }
15811 
15812 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15813   if (getLangOpts().ModulesLocalVisibility) {
15814     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15815     // Leaving a module hides namespace names, so our visible namespace cache
15816     // is now out of date.
15817     VisibleNamespaceCache.clear();
15818   }
15819 
15820   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15821          "left the wrong module scope");
15822   ModuleScopes.pop_back();
15823 
15824   // We got to the end of processing a #include of a local module. Create an
15825   // ImportDecl as we would for an imported module.
15826   FileID File = getSourceManager().getFileID(EofLoc);
15827   assert(File != getSourceManager().getMainFileID() &&
15828          "end of submodule in main source file");
15829   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15830   BuildModuleInclude(DirectiveLoc, Mod);
15831 }
15832 
15833 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15834                                                       Module *Mod) {
15835   // Bail if we're not allowed to implicitly import a module here.
15836   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15837     return;
15838 
15839   // Create the implicit import declaration.
15840   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15841   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15842                                                    Loc, Mod, Loc);
15843   TU->addDecl(ImportD);
15844   Consumer.HandleImplicitImportDecl(ImportD);
15845 
15846   // Make the module visible.
15847   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15848   VisibleModules.setVisible(Mod, Loc);
15849 }
15850 
15851 /// We have parsed the start of an export declaration, including the '{'
15852 /// (if present).
15853 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15854                                  SourceLocation LBraceLoc) {
15855   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15856 
15857   // C++ Modules TS draft:
15858   //   An export-declaration [...] shall not contain more than one
15859   //   export keyword.
15860   //
15861   // The intent here is that an export-declaration cannot appear within another
15862   // export-declaration.
15863   if (D->isExported())
15864     Diag(ExportLoc, diag::err_export_within_export);
15865 
15866   CurContext->addDecl(D);
15867   PushDeclContext(S, D);
15868   return D;
15869 }
15870 
15871 /// Complete the definition of an export declaration.
15872 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15873   auto *ED = cast<ExportDecl>(D);
15874   if (RBraceLoc.isValid())
15875     ED->setRBraceLoc(RBraceLoc);
15876 
15877   // FIXME: Diagnose export of internal-linkage declaration (including
15878   // anonymous namespace).
15879 
15880   PopDeclContext();
15881   return D;
15882 }
15883 
15884 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15885                                       IdentifierInfo* AliasName,
15886                                       SourceLocation PragmaLoc,
15887                                       SourceLocation NameLoc,
15888                                       SourceLocation AliasNameLoc) {
15889   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15890                                          LookupOrdinaryName);
15891   AsmLabelAttr *Attr =
15892       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15893 
15894   // If a declaration that:
15895   // 1) declares a function or a variable
15896   // 2) has external linkage
15897   // already exists, add a label attribute to it.
15898   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15899     if (isDeclExternC(PrevDecl))
15900       PrevDecl->addAttr(Attr);
15901     else
15902       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15903           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15904   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15905   } else
15906     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15907 }
15908 
15909 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15910                              SourceLocation PragmaLoc,
15911                              SourceLocation NameLoc) {
15912   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15913 
15914   if (PrevDecl) {
15915     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15916   } else {
15917     (void)WeakUndeclaredIdentifiers.insert(
15918       std::pair<IdentifierInfo*,WeakInfo>
15919         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15920   }
15921 }
15922 
15923 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15924                                 IdentifierInfo* AliasName,
15925                                 SourceLocation PragmaLoc,
15926                                 SourceLocation NameLoc,
15927                                 SourceLocation AliasNameLoc) {
15928   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15929                                     LookupOrdinaryName);
15930   WeakInfo W = WeakInfo(Name, NameLoc);
15931 
15932   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15933     if (!PrevDecl->hasAttr<AliasAttr>())
15934       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15935         DeclApplyPragmaWeak(TUScope, ND, W);
15936   } else {
15937     (void)WeakUndeclaredIdentifiers.insert(
15938       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15939   }
15940 }
15941 
15942 Decl *Sema::getObjCDeclContext() const {
15943   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15944 }
15945