1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              IdentifierInfo **CorrectedII) {
256   // Determine where we will perform name lookup.
257   DeclContext *LookupCtx = nullptr;
258   if (ObjectTypePtr) {
259     QualType ObjectType = ObjectTypePtr.get();
260     if (ObjectType->isRecordType())
261       LookupCtx = computeDeclContext(ObjectType);
262   } else if (SS && SS->isNotEmpty()) {
263     LookupCtx = computeDeclContext(*SS, false);
264 
265     if (!LookupCtx) {
266       if (isDependentScopeSpecifier(*SS)) {
267         // C++ [temp.res]p3:
268         //   A qualified-id that refers to a type and in which the
269         //   nested-name-specifier depends on a template-parameter (14.6.2)
270         //   shall be prefixed by the keyword typename to indicate that the
271         //   qualified-id denotes a type, forming an
272         //   elaborated-type-specifier (7.1.5.3).
273         //
274         // We therefore do not perform any name lookup if the result would
275         // refer to a member of an unknown specialization.
276         if (!isClassName && !IsCtorOrDtorName)
277           return nullptr;
278 
279         // We know from the grammar that this name refers to a type,
280         // so build a dependent node to describe the type.
281         if (WantNontrivialTypeSourceInfo)
282           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283 
284         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286                                        II, NameLoc);
287         return ParsedType::make(T);
288       }
289 
290       return nullptr;
291     }
292 
293     if (!LookupCtx->isDependentContext() &&
294         RequireCompleteDeclContext(*SS, LookupCtx))
295       return nullptr;
296   }
297 
298   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299   // lookup for class-names.
300   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301                                       LookupOrdinaryName;
302   LookupResult Result(*this, &II, NameLoc, Kind);
303   if (LookupCtx) {
304     // Perform "qualified" name lookup into the declaration context we
305     // computed, which is either the type of the base of a member access
306     // expression or the declaration context associated with a prior
307     // nested-name-specifier.
308     LookupQualifiedName(Result, LookupCtx);
309 
310     if (ObjectTypePtr && Result.empty()) {
311       // C++ [basic.lookup.classref]p3:
312       //   If the unqualified-id is ~type-name, the type-name is looked up
313       //   in the context of the entire postfix-expression. If the type T of
314       //   the object expression is of a class type C, the type-name is also
315       //   looked up in the scope of class C. At least one of the lookups shall
316       //   find a name that refers to (possibly cv-qualified) T.
317       LookupName(Result, S);
318     }
319   } else {
320     // Perform unqualified name lookup.
321     LookupName(Result, S);
322 
323     // For unqualified lookup in a class template in MSVC mode, look into
324     // dependent base classes where the primary class template is known.
325     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326       if (ParsedType TypeInBase =
327               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328         return TypeInBase;
329     }
330   }
331 
332   NamedDecl *IIDecl = nullptr;
333   switch (Result.getResultKind()) {
334   case LookupResult::NotFound:
335   case LookupResult::NotFoundInCurrentInstantiation:
336     if (CorrectedII) {
337       TypoCorrection Correction = CorrectTypo(
338           Result.getLookupNameInfo(), Kind, S, SS,
339           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340           CTK_ErrorRecovery);
341       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342       TemplateTy Template;
343       bool MemberOfUnknownSpecialization;
344       UnqualifiedId TemplateName;
345       TemplateName.setIdentifier(NewII, NameLoc);
346       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347       CXXScopeSpec NewSS, *NewSSPtr = SS;
348       if (SS && NNS) {
349         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350         NewSSPtr = &NewSS;
351       }
352       if (Correction && (NNS || NewII != &II) &&
353           // Ignore a correction to a template type as the to-be-corrected
354           // identifier is not a template (typo correction for template names
355           // is handled elsewhere).
356           !(getLangOpts().CPlusPlus && NewSSPtr &&
357             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358                            Template, MemberOfUnknownSpecialization))) {
359         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360                                     isClassName, HasTrailingDot, ObjectTypePtr,
361                                     IsCtorOrDtorName,
362                                     WantNontrivialTypeSourceInfo);
363         if (Ty) {
364           diagnoseTypo(Correction,
365                        PDiag(diag::err_unknown_type_or_class_name_suggest)
366                          << Result.getLookupName() << isClassName);
367           if (SS && NNS)
368             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369           *CorrectedII = NewII;
370           return Ty;
371         }
372       }
373     }
374     // If typo correction failed or was not performed, fall through
375   case LookupResult::FoundOverloaded:
376   case LookupResult::FoundUnresolvedValue:
377     Result.suppressDiagnostics();
378     return nullptr;
379 
380   case LookupResult::Ambiguous:
381     // Recover from type-hiding ambiguities by hiding the type.  We'll
382     // do the lookup again when looking for an object, and we can
383     // diagnose the error then.  If we don't do this, then the error
384     // about hiding the type will be immediately followed by an error
385     // that only makes sense if the identifier was treated like a type.
386     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387       Result.suppressDiagnostics();
388       return nullptr;
389     }
390 
391     // Look to see if we have a type anywhere in the list of results.
392     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393          Res != ResEnd; ++Res) {
394       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395         if (!IIDecl ||
396             (*Res)->getLocation().getRawEncoding() <
397               IIDecl->getLocation().getRawEncoding())
398           IIDecl = *Res;
399       }
400     }
401 
402     if (!IIDecl) {
403       // None of the entities we found is a type, so there is no way
404       // to even assume that the result is a type. In this case, don't
405       // complain about the ambiguity. The parser will either try to
406       // perform this lookup again (e.g., as an object name), which
407       // will produce the ambiguity, or will complain that it expected
408       // a type name.
409       Result.suppressDiagnostics();
410       return nullptr;
411     }
412 
413     // We found a type within the ambiguous lookup; diagnose the
414     // ambiguity and then return that type. This might be the right
415     // answer, or it might not be, but it suppresses any attempt to
416     // perform the name lookup again.
417     break;
418 
419   case LookupResult::Found:
420     IIDecl = Result.getFoundDecl();
421     break;
422   }
423 
424   assert(IIDecl && "Didn't find decl");
425 
426   QualType T;
427   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428     DiagnoseUseOfDecl(IIDecl, NameLoc);
429 
430     T = Context.getTypeDeclType(TD);
431     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432 
433     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434     // constructor or destructor name (in such a case, the scope specifier
435     // will be attached to the enclosing Expr or Decl node).
436     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437       if (WantNontrivialTypeSourceInfo) {
438         // Construct a type with type-source information.
439         TypeLocBuilder Builder;
440         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441 
442         T = getElaboratedType(ETK_None, *SS, T);
443         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444         ElabTL.setElaboratedKeywordLoc(SourceLocation());
445         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447       } else {
448         T = getElaboratedType(ETK_None, *SS, T);
449       }
450     }
451   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453     if (!HasTrailingDot)
454       T = Context.getObjCInterfaceType(IDecl);
455   }
456 
457   if (T.isNull()) {
458     // If it's not plausibly a type, suppress diagnostics.
459     Result.suppressDiagnostics();
460     return nullptr;
461   }
462   return ParsedType::make(T);
463 }
464 
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468   for (;; DC = DC->getLookupParent()) {
469     DC = DC->getPrimaryContext();
470     auto *ND = dyn_cast<NamespaceDecl>(DC);
471     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472       return NestedNameSpecifier::Create(Context, nullptr, ND);
473     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475                                          RD->getTypeForDecl());
476     else if (isa<TranslationUnitDecl>(DC))
477       return NestedNameSpecifier::GlobalSpecifier(Context);
478   }
479   llvm_unreachable("something isn't in TU scope?");
480 }
481 
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489     DC = DC->getPrimaryContext();
490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491       if (MD->getParent()->hasAnyDependentBases())
492         return MD->getParent();
493   }
494   return nullptr;
495 }
496 
497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498                                           SourceLocation NameLoc,
499                                           bool IsTemplateTypeArg) {
500   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501 
502   NestedNameSpecifier *NNS = nullptr;
503   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504     // If we weren't able to parse a default template argument, delay lookup
505     // until instantiation time by making a non-dependent DependentTypeName. We
506     // pretend we saw a NestedNameSpecifier referring to the current scope, and
507     // lookup is retried.
508     // FIXME: This hurts our diagnostic quality, since we get errors like "no
509     // type named 'Foo' in 'current_namespace'" when the user didn't write any
510     // name specifiers.
511     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513   } else if (const CXXRecordDecl *RD =
514                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515     // Build a DependentNameType that will perform lookup into RD at
516     // instantiation time.
517     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518                                       RD->getTypeForDecl());
519 
520     // Diagnose that this identifier was undeclared, and retry the lookup during
521     // template instantiation.
522     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523                                                                       << RD;
524   } else {
525     // This is not a situation that we should recover from.
526     return ParsedType();
527   }
528 
529   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530 
531   // Build type location information.  We synthesized the qualifier, so we have
532   // to build a fake NestedNameSpecifierLoc.
533   NestedNameSpecifierLocBuilder NNSLocBuilder;
534   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536 
537   TypeLocBuilder Builder;
538   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539   DepTL.setNameLoc(NameLoc);
540   DepTL.setElaboratedKeywordLoc(SourceLocation());
541   DepTL.setQualifierLoc(QualifierLoc);
542   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543 }
544 
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo").  If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551   // Do a tag name lookup in this scope.
552   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553   LookupName(R, S, false);
554   R.suppressDiagnostics();
555   if (R.getResultKind() == LookupResult::Found)
556     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557       switch (TD->getTagKind()) {
558       case TTK_Struct: return DeclSpec::TST_struct;
559       case TTK_Interface: return DeclSpec::TST_interface;
560       case TTK_Union:  return DeclSpec::TST_union;
561       case TTK_Class:  return DeclSpec::TST_class;
562       case TTK_Enum:   return DeclSpec::TST_enum;
563       }
564     }
565 
566   return DeclSpec::TST_unspecified;
567 }
568 
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
573 /// @code
574 /// template<class T> class A {
575 /// public:
576 ///   typedef int TYPE;
577 /// };
578 /// template<class T> class B : public A<T> {
579 /// public:
580 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
581 /// };
582 /// @endcode
583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584   if (CurContext->isRecord()) {
585     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586       return true;
587 
588     const Type *Ty = SS->getScopeRep()->getAsType();
589 
590     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591     for (const auto &Base : RD->bases())
592       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593         return true;
594     return S->isFunctionPrototypeScope();
595   }
596   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597 }
598 
599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600                                    SourceLocation IILoc,
601                                    Scope *S,
602                                    CXXScopeSpec *SS,
603                                    ParsedType &SuggestedType,
604                                    bool AllowClassTemplates) {
605   // We don't have anything to suggest (yet).
606   SuggestedType = nullptr;
607 
608   // There may have been a typo in the name of the type. Look up typo
609   // results, in case we have something that we can suggest.
610   if (TypoCorrection Corrected =
611           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612                       llvm::make_unique<TypeNameValidatorCCC>(
613                           false, false, AllowClassTemplates),
614                       CTK_ErrorRecovery)) {
615     if (Corrected.isKeyword()) {
616       // We corrected to a keyword.
617       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618       II = Corrected.getCorrectionAsIdentifierInfo();
619     } else {
620       // We found a similarly-named type or interface; suggest that.
621       if (!SS || !SS->isSet()) {
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_typename_suggest) << II);
624       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627                                 II->getName().equals(CorrectedStr);
628         diagnoseTypo(Corrected,
629                      PDiag(diag::err_unknown_nested_typename_suggest)
630                        << II << DC << DroppedSpecifier << SS->getRange());
631       } else {
632         llvm_unreachable("could not have corrected a typo here");
633       }
634 
635       CXXScopeSpec tmpSS;
636       if (Corrected.getCorrectionSpecifier())
637         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638                           SourceRange(IILoc));
639       SuggestedType =
640           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642                       /*IsCtorOrDtorName=*/false,
643                       /*NonTrivialTypeSourceInfo=*/true);
644     }
645     return;
646   }
647 
648   if (getLangOpts().CPlusPlus) {
649     // See if II is a class template that the user forgot to pass arguments to.
650     UnqualifiedId Name;
651     Name.setIdentifier(II, IILoc);
652     CXXScopeSpec EmptySS;
653     TemplateTy TemplateResult;
654     bool MemberOfUnknownSpecialization;
655     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656                        Name, nullptr, true, TemplateResult,
657                        MemberOfUnknownSpecialization) == TNK_Type_template) {
658       TemplateName TplName = TemplateResult.get();
659       Diag(IILoc, diag::err_template_missing_args) << TplName;
660       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662           << TplDecl->getTemplateParameters()->getSourceRange();
663       }
664       return;
665     }
666   }
667 
668   // FIXME: Should we move the logic that tries to recover from a missing tag
669   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670 
671   if (!SS || (!SS->isSet() && !SS->isInvalid()))
672     Diag(IILoc, diag::err_unknown_typename) << II;
673   else if (DeclContext *DC = computeDeclContext(*SS, false))
674     Diag(IILoc, diag::err_typename_nested_not_found)
675       << II << DC << SS->getRange();
676   else if (isDependentScopeSpecifier(*SS)) {
677     unsigned DiagID = diag::err_typename_missing;
678     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679       DiagID = diag::ext_typename_missing;
680 
681     Diag(SS->getRange().getBegin(), DiagID)
682       << SS->getScopeRep() << II->getName()
683       << SourceRange(SS->getRange().getBegin(), IILoc)
684       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685     SuggestedType = ActOnTypenameType(S, SourceLocation(),
686                                       *SS, *II, IILoc).get();
687   } else {
688     assert(SS && SS->isInvalid() &&
689            "Invalid scope specifier has already been diagnosed");
690   }
691 }
692 
693 /// \brief Determine whether the given result set contains either a type name
694 /// or
695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697                        NextToken.is(tok::less);
698 
699   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701       return true;
702 
703     if (CheckTemplate && isa<TemplateDecl>(*I))
704       return true;
705   }
706 
707   return false;
708 }
709 
710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711                                     Scope *S, CXXScopeSpec &SS,
712                                     IdentifierInfo *&Name,
713                                     SourceLocation NameLoc) {
714   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715   SemaRef.LookupParsedName(R, S, &SS);
716   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717     StringRef FixItTagName;
718     switch (Tag->getTagKind()) {
719       case TTK_Class:
720         FixItTagName = "class ";
721         break;
722 
723       case TTK_Enum:
724         FixItTagName = "enum ";
725         break;
726 
727       case TTK_Struct:
728         FixItTagName = "struct ";
729         break;
730 
731       case TTK_Interface:
732         FixItTagName = "__interface ";
733         break;
734 
735       case TTK_Union:
736         FixItTagName = "union ";
737         break;
738     }
739 
740     StringRef TagName = FixItTagName.drop_back();
741     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744 
745     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746          I != IEnd; ++I)
747       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748         << Name << TagName;
749 
750     // Replace lookup results with just the tag decl.
751     Result.clear(Sema::LookupTagName);
752     SemaRef.LookupParsedName(Result, S, &SS);
753     return true;
754   }
755 
756   return false;
757 }
758 
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761                                   QualType T, SourceLocation NameLoc) {
762   ASTContext &Context = S.Context;
763 
764   TypeLocBuilder Builder;
765   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766 
767   T = S.getElaboratedType(ETK_None, SS, T);
768   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769   ElabTL.setElaboratedKeywordLoc(SourceLocation());
770   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772 }
773 
774 Sema::NameClassification
775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776                    SourceLocation NameLoc, const Token &NextToken,
777                    bool IsAddressOfOperand,
778                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
779   DeclarationNameInfo NameInfo(Name, NameLoc);
780   ObjCMethodDecl *CurMethod = getCurMethodDecl();
781 
782   if (NextToken.is(tok::coloncolon)) {
783     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
784                                 QualType(), false, SS, nullptr, false);
785   }
786 
787   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788   LookupParsedName(Result, S, &SS, !CurMethod);
789 
790   // For unqualified lookup in a class template in MSVC mode, look into
791   // dependent base classes where the primary class template is known.
792   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793     if (ParsedType TypeInBase =
794             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795       return TypeInBase;
796   }
797 
798   // Perform lookup for Objective-C instance variables (including automatically
799   // synthesized instance variables), if we're in an Objective-C method.
800   // FIXME: This lookup really, really needs to be folded in to the normal
801   // unqualified lookup mechanism.
802   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804     if (E.get() || E.isInvalid())
805       return E;
806   }
807 
808   bool SecondTry = false;
809   bool IsFilteredTemplateName = false;
810 
811 Corrected:
812   switch (Result.getResultKind()) {
813   case LookupResult::NotFound:
814     // If an unqualified-id is followed by a '(', then we have a function
815     // call.
816     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817       // In C++, this is an ADL-only call.
818       // FIXME: Reference?
819       if (getLangOpts().CPlusPlus)
820         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821 
822       // C90 6.3.2.2:
823       //   If the expression that precedes the parenthesized argument list in a
824       //   function call consists solely of an identifier, and if no
825       //   declaration is visible for this identifier, the identifier is
826       //   implicitly declared exactly as if, in the innermost block containing
827       //   the function call, the declaration
828       //
829       //     extern int identifier ();
830       //
831       //   appeared.
832       //
833       // We also allow this in C99 as an extension.
834       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835         Result.addDecl(D);
836         Result.resolveKind();
837         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838       }
839     }
840 
841     // In C, we first see whether there is a tag type by the same name, in
842     // which case it's likely that the user just forgot to write "enum",
843     // "struct", or "union".
844     if (!getLangOpts().CPlusPlus && !SecondTry &&
845         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846       break;
847     }
848 
849     // Perform typo correction to determine if there is another name that is
850     // close to this name.
851     if (!SecondTry && CCC) {
852       SecondTry = true;
853       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854                                                  Result.getLookupKind(), S,
855                                                  &SS, std::move(CCC),
856                                                  CTK_ErrorRecovery)) {
857         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858         unsigned QualifiedDiag = diag::err_no_member_suggest;
859 
860         NamedDecl *FirstDecl = Corrected.getFoundDecl();
861         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864           UnqualifiedDiag = diag::err_no_template_suggest;
865           QualifiedDiag = diag::err_no_member_template_suggest;
866         } else if (UnderlyingFirstDecl &&
867                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
868                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870           UnqualifiedDiag = diag::err_unknown_typename_suggest;
871           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872         }
873 
874         if (SS.isEmpty()) {
875           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876         } else {// FIXME: is this even reachable? Test it.
877           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879                                   Name->getName().equals(CorrectedStr);
880           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881                                     << Name << computeDeclContext(SS, false)
882                                     << DroppedSpecifier << SS.getRange());
883         }
884 
885         // Update the name, so that the caller has the new name.
886         Name = Corrected.getCorrectionAsIdentifierInfo();
887 
888         // Typo correction corrected to a keyword.
889         if (Corrected.isKeyword())
890           return Name;
891 
892         // Also update the LookupResult...
893         // FIXME: This should probably go away at some point
894         Result.clear();
895         Result.setLookupName(Corrected.getCorrection());
896         if (FirstDecl)
897           Result.addDecl(FirstDecl);
898 
899         // If we found an Objective-C instance variable, let
900         // LookupInObjCMethod build the appropriate expression to
901         // reference the ivar.
902         // FIXME: This is a gross hack.
903         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904           Result.clear();
905           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906           return E;
907         }
908 
909         goto Corrected;
910       }
911     }
912 
913     // We failed to correct; just fall through and let the parser deal with it.
914     Result.suppressDiagnostics();
915     return NameClassification::Unknown();
916 
917   case LookupResult::NotFoundInCurrentInstantiation: {
918     // We performed name lookup into the current instantiation, and there were
919     // dependent bases, so we treat this result the same way as any other
920     // dependent nested-name-specifier.
921 
922     // C++ [temp.res]p2:
923     //   A name used in a template declaration or definition and that is
924     //   dependent on a template-parameter is assumed not to name a type
925     //   unless the applicable name lookup finds a type name or the name is
926     //   qualified by the keyword typename.
927     //
928     // FIXME: If the next token is '<', we might want to ask the parser to
929     // perform some heroics to see if we actually have a
930     // template-argument-list, which would indicate a missing 'template'
931     // keyword here.
932     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933                                       NameInfo, IsAddressOfOperand,
934                                       /*TemplateArgs=*/nullptr);
935   }
936 
937   case LookupResult::Found:
938   case LookupResult::FoundOverloaded:
939   case LookupResult::FoundUnresolvedValue:
940     break;
941 
942   case LookupResult::Ambiguous:
943     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944         hasAnyAcceptableTemplateNames(Result)) {
945       // C++ [temp.local]p3:
946       //   A lookup that finds an injected-class-name (10.2) can result in an
947       //   ambiguity in certain cases (for example, if it is found in more than
948       //   one base class). If all of the injected-class-names that are found
949       //   refer to specializations of the same class template, and if the name
950       //   is followed by a template-argument-list, the reference refers to the
951       //   class template itself and not a specialization thereof, and is not
952       //   ambiguous.
953       //
954       // This filtering can make an ambiguous result into an unambiguous one,
955       // so try again after filtering out template names.
956       FilterAcceptableTemplateNames(Result);
957       if (!Result.isAmbiguous()) {
958         IsFilteredTemplateName = true;
959         break;
960       }
961     }
962 
963     // Diagnose the ambiguity and return an error.
964     return NameClassification::Error();
965   }
966 
967   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969     // C++ [temp.names]p3:
970     //   After name lookup (3.4) finds that a name is a template-name or that
971     //   an operator-function-id or a literal- operator-id refers to a set of
972     //   overloaded functions any member of which is a function template if
973     //   this is followed by a <, the < is always taken as the delimiter of a
974     //   template-argument-list and never as the less-than operator.
975     if (!IsFilteredTemplateName)
976       FilterAcceptableTemplateNames(Result);
977 
978     if (!Result.empty()) {
979       bool IsFunctionTemplate;
980       bool IsVarTemplate;
981       TemplateName Template;
982       if (Result.end() - Result.begin() > 1) {
983         IsFunctionTemplate = true;
984         Template = Context.getOverloadedTemplateName(Result.begin(),
985                                                      Result.end());
986       } else {
987         TemplateDecl *TD
988           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990         IsVarTemplate = isa<VarTemplateDecl>(TD);
991 
992         if (SS.isSet() && !SS.isInvalid())
993           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994                                                     /*TemplateKeyword=*/false,
995                                                       TD);
996         else
997           Template = TemplateName(TD);
998       }
999 
1000       if (IsFunctionTemplate) {
1001         // Function templates always go through overload resolution, at which
1002         // point we'll perform the various checks (e.g., accessibility) we need
1003         // to based on which function we selected.
1004         Result.suppressDiagnostics();
1005 
1006         return NameClassification::FunctionTemplate(Template);
1007       }
1008 
1009       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010                            : NameClassification::TypeTemplate(Template);
1011     }
1012   }
1013 
1014   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023 
1024   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025   if (!Class) {
1026     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027     if (ObjCCompatibleAliasDecl *Alias =
1028             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029       Class = Alias->getClassInterface();
1030   }
1031 
1032   if (Class) {
1033     DiagnoseUseOfDecl(Class, NameLoc);
1034 
1035     if (NextToken.is(tok::period)) {
1036       // Interface. <something> is parsed as a property reference expression.
1037       // Just return "unknown" as a fall-through for now.
1038       Result.suppressDiagnostics();
1039       return NameClassification::Unknown();
1040     }
1041 
1042     QualType T = Context.getObjCInterfaceType(Class);
1043     return ParsedType::make(T);
1044   }
1045 
1046   // We can have a type template here if we're classifying a template argument.
1047   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048     return NameClassification::TypeTemplate(
1049         TemplateName(cast<TemplateDecl>(FirstDecl)));
1050 
1051   // Check for a tag type hidden by a non-type decl in a few cases where it
1052   // seems likely a type is wanted instead of the non-type that was found.
1053   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054   if ((NextToken.is(tok::identifier) ||
1055        (NextIsOp &&
1056         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059     DiagnoseUseOfDecl(Type, NameLoc);
1060     QualType T = Context.getTypeDeclType(Type);
1061     if (SS.isNotEmpty())
1062       return buildNestedType(*this, SS, T, NameLoc);
1063     return ParsedType::make(T);
1064   }
1065 
1066   if (FirstDecl->isCXXClassMember())
1067     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068                                            nullptr, S);
1069 
1070   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071   return BuildDeclarationNameExpr(SS, Result, ADL);
1072 }
1073 
1074 // Determines the context to return to after temporarily entering a
1075 // context.  This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078 
1079   // Functions defined inline within classes aren't parsed until we've
1080   // finished parsing the top-level class, so the top-level class is
1081   // the context we'll need to return to.
1082   // A Lambda call operator whose parent is a class must not be treated
1083   // as an inline member function.  A Lambda can be used legally
1084   // either as an in-class member initializer or a default argument.  These
1085   // are parsed once the class has been marked complete and so the containing
1086   // context would be the nested class (when the lambda is defined in one);
1087   // If the class is not complete, then the lambda is being used in an
1088   // ill-formed fashion (such as to specify the width of a bit-field, or
1089   // in an array-bound) - in which case we still want to return the
1090   // lexically containing DC (which could be a nested class).
1091   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092     DC = DC->getLexicalParent();
1093 
1094     // A function not defined within a class will always return to its
1095     // lexical context.
1096     if (!isa<CXXRecordDecl>(DC))
1097       return DC;
1098 
1099     // A C++ inline method/friend is parsed *after* the topmost class
1100     // it was declared in is fully parsed ("complete");  the topmost
1101     // class is the context we need to return to.
1102     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103       DC = RD;
1104 
1105     // Return the declaration context of the topmost class the inline method is
1106     // declared in.
1107     return DC;
1108   }
1109 
1110   return DC->getLexicalParent();
1111 }
1112 
1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114   assert(getContainingDC(DC) == CurContext &&
1115       "The next DeclContext should be lexically contained in the current one.");
1116   CurContext = DC;
1117   S->setEntity(DC);
1118 }
1119 
1120 void Sema::PopDeclContext() {
1121   assert(CurContext && "DeclContext imbalance!");
1122 
1123   CurContext = getContainingDC(CurContext);
1124   assert(CurContext && "Popped translation unit!");
1125 }
1126 
1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128                                                                     Decl *D) {
1129   // Unlike PushDeclContext, the context to which we return is not necessarily
1130   // the containing DC of TD, because the new context will be some pre-existing
1131   // TagDecl definition instead of a fresh one.
1132   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133   CurContext = cast<TagDecl>(D)->getDefinition();
1134   assert(CurContext && "skipping definition of undefined tag");
1135   // Start lookups from the parent of the current context; we don't want to look
1136   // into the pre-existing complete definition.
1137   S->setEntity(CurContext->getLookupParent());
1138   return Result;
1139 }
1140 
1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142   CurContext = static_cast<decltype(CurContext)>(Context);
1143 }
1144 
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1147 ///
1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149   // C++0x [basic.lookup.unqual]p13:
1150   //   A name used in the definition of a static data member of class
1151   //   X (after the qualified-id of the static member) is looked up as
1152   //   if the name was used in a member function of X.
1153   // C++0x [basic.lookup.unqual]p14:
1154   //   If a variable member of a namespace is defined outside of the
1155   //   scope of its namespace then any name used in the definition of
1156   //   the variable member (after the declarator-id) is looked up as
1157   //   if the definition of the variable member occurred in its
1158   //   namespace.
1159   // Both of these imply that we should push a scope whose context
1160   // is the semantic context of the declaration.  We can't use
1161   // PushDeclContext here because that context is not necessarily
1162   // lexically contained in the current context.  Fortunately,
1163   // the containing scope should have the appropriate information.
1164 
1165   assert(!S->getEntity() && "scope already has entity");
1166 
1167 #ifndef NDEBUG
1168   Scope *Ancestor = S->getParent();
1169   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171 #endif
1172 
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176 
1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178   assert(S->getEntity() == CurContext && "Context imbalance!");
1179 
1180   // Switch back to the lexical context.  The safety of this is
1181   // enforced by an assert in EnterDeclaratorContext.
1182   Scope *Ancestor = S->getParent();
1183   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184   CurContext = Ancestor->getEntity();
1185 
1186   // We don't need to do anything with the scope, which is going to
1187   // disappear.
1188 }
1189 
1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191   // We assume that the caller has already called
1192   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193   FunctionDecl *FD = D->getAsFunction();
1194   if (!FD)
1195     return;
1196 
1197   // Same implementation as PushDeclContext, but enters the context
1198   // from the lexical parent, rather than the top-level class.
1199   assert(CurContext == FD->getLexicalParent() &&
1200     "The next DeclContext should be lexically contained in the current one.");
1201   CurContext = FD;
1202   S->setEntity(CurContext);
1203 
1204   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205     ParmVarDecl *Param = FD->getParamDecl(P);
1206     // If the parameter has an identifier, then add it to the scope
1207     if (Param->getIdentifier()) {
1208       S->AddDecl(Param);
1209       IdResolver.AddDecl(Param);
1210     }
1211   }
1212 }
1213 
1214 void Sema::ActOnExitFunctionContext() {
1215   // Same implementation as PopDeclContext, but returns to the lexical parent,
1216   // rather than the top-level class.
1217   assert(CurContext && "DeclContext imbalance!");
1218   CurContext = CurContext->getLexicalParent();
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221 
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1224 ///
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1230 /// attribute.
1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232                                        ASTContext &Context) {
1233   if (Context.getLangOpts().CPlusPlus)
1234     return true;
1235 
1236   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237     return true;
1238 
1239   return (Previous.getResultKind() == LookupResult::Found
1240           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241 }
1242 
1243 /// Add this decl to the scope shadowed decl chains.
1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245   // Move up the scope chain until we find the nearest enclosing
1246   // non-transparent context. The declaration will be introduced into this
1247   // scope.
1248   while (S->getEntity() && S->getEntity()->isTransparentContext())
1249     S = S->getParent();
1250 
1251   // Add scoped declarations into their context, so that they can be
1252   // found later. Declarations without a context won't be inserted
1253   // into any context.
1254   if (AddToContext)
1255     CurContext->addDecl(D);
1256 
1257   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258   // are function-local declarations.
1259   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260       !D->getDeclContext()->getRedeclContext()->Equals(
1261         D->getLexicalDeclContext()->getRedeclContext()) &&
1262       !D->getLexicalDeclContext()->isFunctionOrMethod())
1263     return;
1264 
1265   // Template instantiations should also not be pushed into scope.
1266   if (isa<FunctionDecl>(D) &&
1267       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268     return;
1269 
1270   // If this replaces anything in the current scope,
1271   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272                                IEnd = IdResolver.end();
1273   for (; I != IEnd; ++I) {
1274     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275       S->RemoveDecl(*I);
1276       IdResolver.RemoveDecl(*I);
1277 
1278       // Should only need to replace one decl.
1279       break;
1280     }
1281   }
1282 
1283   S->AddDecl(D);
1284 
1285   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286     // Implicitly-generated labels may end up getting generated in an order that
1287     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288     // the label at the appropriate place in the identifier chain.
1289     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291       if (IDC == CurContext) {
1292         if (!S->isDeclScope(*I))
1293           continue;
1294       } else if (IDC->Encloses(CurContext))
1295         break;
1296     }
1297 
1298     IdResolver.InsertDeclAfter(I, D);
1299   } else {
1300     IdResolver.AddDecl(D);
1301   }
1302 }
1303 
1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306     TUScope->AddDecl(D);
1307 }
1308 
1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310                          bool AllowInlineNamespace) {
1311   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312 }
1313 
1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315   DeclContext *TargetDC = DC->getPrimaryContext();
1316   do {
1317     if (DeclContext *ScopeDC = S->getEntity())
1318       if (ScopeDC->getPrimaryContext() == TargetDC)
1319         return S;
1320   } while ((S = S->getParent()));
1321 
1322   return nullptr;
1323 }
1324 
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326                                             DeclContext*,
1327                                             ASTContext&);
1328 
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332                                 bool ConsiderLinkage,
1333                                 bool AllowInlineNamespace) {
1334   LookupResult::Filter F = R.makeFilter();
1335   while (F.hasNext()) {
1336     NamedDecl *D = F.next();
1337 
1338     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339       continue;
1340 
1341     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342       continue;
1343 
1344     F.erase();
1345   }
1346 
1347   F.done();
1348 }
1349 
1350 static bool isUsingDecl(NamedDecl *D) {
1351   return isa<UsingShadowDecl>(D) ||
1352          isa<UnresolvedUsingTypenameDecl>(D) ||
1353          isa<UnresolvedUsingValueDecl>(D);
1354 }
1355 
1356 /// Removes using shadow declarations from the lookup results.
1357 static void RemoveUsingDecls(LookupResult &R) {
1358   LookupResult::Filter F = R.makeFilter();
1359   while (F.hasNext())
1360     if (isUsingDecl(F.next()))
1361       F.erase();
1362 
1363   F.done();
1364 }
1365 
1366 /// \brief Check for this common pattern:
1367 /// @code
1368 /// class S {
1369 ///   S(const S&); // DO NOT IMPLEMENT
1370 ///   void operator=(const S&); // DO NOT IMPLEMENT
1371 /// };
1372 /// @endcode
1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374   // FIXME: Should check for private access too but access is set after we get
1375   // the decl here.
1376   if (D->doesThisDeclarationHaveABody())
1377     return false;
1378 
1379   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380     return CD->isCopyConstructor();
1381   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382     return Method->isCopyAssignmentOperator();
1383   return false;
1384 }
1385 
1386 // We need this to handle
1387 //
1388 // typedef struct {
1389 //   void *foo() { return 0; }
1390 // } A;
1391 //
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1397 // not.
1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399   const DeclContext *DC = D->getDeclContext();
1400   while (!DC->isTranslationUnit()) {
1401     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402       if (!RD->hasNameForLinkage())
1403         return true;
1404     }
1405     DC = DC->getParent();
1406   }
1407 
1408   return !D->isExternallyVisible();
1409 }
1410 
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1412 // these semantics.
1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414   if (S.TUKind != TU_Complete)
1415     return false;
1416   return S.SourceMgr.isInMainFile(Loc);
1417 }
1418 
1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420   assert(D);
1421 
1422   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423     return false;
1424 
1425   // Ignore all entities declared within templates, and out-of-line definitions
1426   // of members of class templates.
1427   if (D->getDeclContext()->isDependentContext() ||
1428       D->getLexicalDeclContext()->isDependentContext())
1429     return false;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433       return false;
1434 
1435     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437         return false;
1438     } else {
1439       // 'static inline' functions are defined in headers; don't warn.
1440       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441         return false;
1442     }
1443 
1444     if (FD->doesThisDeclarationHaveABody() &&
1445         Context.DeclMustBeEmitted(FD))
1446       return false;
1447   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448     // Constants and utility variables are defined in headers with internal
1449     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1450     // like "inline".)
1451     if (!isMainFileLoc(*this, VD->getLocation()))
1452       return false;
1453 
1454     if (Context.DeclMustBeEmitted(VD))
1455       return false;
1456 
1457     if (VD->isStaticDataMember() &&
1458         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459       return false;
1460 
1461     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1462       return false;
1463   } else {
1464     return false;
1465   }
1466 
1467   // Only warn for unused decls internal to the translation unit.
1468   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469   // for inline functions defined in the main source file, for instance.
1470   return mightHaveNonExternalLinkage(D);
1471 }
1472 
1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1474   if (!D)
1475     return;
1476 
1477   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478     const FunctionDecl *First = FD->getFirstDecl();
1479     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480       return; // First should already be in the vector.
1481   }
1482 
1483   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484     const VarDecl *First = VD->getFirstDecl();
1485     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486       return; // First should already be in the vector.
1487   }
1488 
1489   if (ShouldWarnIfUnusedFileScopedDecl(D))
1490     UnusedFileScopedDecls.push_back(D);
1491 }
1492 
1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494   if (D->isInvalidDecl())
1495     return false;
1496 
1497   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498       D->hasAttr<ObjCPreciseLifetimeAttr>())
1499     return false;
1500 
1501   if (isa<LabelDecl>(D))
1502     return true;
1503 
1504   // Except for labels, we only care about unused decls that are local to
1505   // functions.
1506   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508     // For dependent types, the diagnostic is deferred.
1509     WithinFunction =
1510         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511   if (!WithinFunction)
1512     return false;
1513 
1514   if (isa<TypedefNameDecl>(D))
1515     return true;
1516 
1517   // White-list anything that isn't a local variable.
1518   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1519     return false;
1520 
1521   // Types of valid local variables should be complete, so this should succeed.
1522   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523 
1524     // White-list anything with an __attribute__((unused)) type.
1525     QualType Ty = VD->getType();
1526 
1527     // Only look at the outermost level of typedef.
1528     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529       if (TT->getDecl()->hasAttr<UnusedAttr>())
1530         return false;
1531     }
1532 
1533     // If we failed to complete the type for some reason, or if the type is
1534     // dependent, don't diagnose the variable.
1535     if (Ty->isIncompleteType() || Ty->isDependentType())
1536       return false;
1537 
1538     if (const TagType *TT = Ty->getAs<TagType>()) {
1539       const TagDecl *Tag = TT->getDecl();
1540       if (Tag->hasAttr<UnusedAttr>())
1541         return false;
1542 
1543       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1544         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1545           return false;
1546 
1547         if (const Expr *Init = VD->getInit()) {
1548           if (const ExprWithCleanups *Cleanups =
1549                   dyn_cast<ExprWithCleanups>(Init))
1550             Init = Cleanups->getSubExpr();
1551           const CXXConstructExpr *Construct =
1552             dyn_cast<CXXConstructExpr>(Init);
1553           if (Construct && !Construct->isElidable()) {
1554             CXXConstructorDecl *CD = Construct->getConstructor();
1555             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1556               return false;
1557           }
1558         }
1559       }
1560     }
1561 
1562     // TODO: __attribute__((unused)) templates?
1563   }
1564 
1565   return true;
1566 }
1567 
1568 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1569                                      FixItHint &Hint) {
1570   if (isa<LabelDecl>(D)) {
1571     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1572                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1573     if (AfterColon.isInvalid())
1574       return;
1575     Hint = FixItHint::CreateRemoval(CharSourceRange::
1576                                     getCharRange(D->getLocStart(), AfterColon));
1577   }
1578 }
1579 
1580 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1581   if (D->getTypeForDecl()->isDependentType())
1582     return;
1583 
1584   for (auto *TmpD : D->decls()) {
1585     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1586       DiagnoseUnusedDecl(T);
1587     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1588       DiagnoseUnusedNestedTypedefs(R);
1589   }
1590 }
1591 
1592 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1593 /// unless they are marked attr(unused).
1594 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1595   if (!ShouldDiagnoseUnusedDecl(D))
1596     return;
1597 
1598   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1599     // typedefs can be referenced later on, so the diagnostics are emitted
1600     // at end-of-translation-unit.
1601     UnusedLocalTypedefNameCandidates.insert(TD);
1602     return;
1603   }
1604 
1605   FixItHint Hint;
1606   GenerateFixForUnusedDecl(D, Context, Hint);
1607 
1608   unsigned DiagID;
1609   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1610     DiagID = diag::warn_unused_exception_param;
1611   else if (isa<LabelDecl>(D))
1612     DiagID = diag::warn_unused_label;
1613   else
1614     DiagID = diag::warn_unused_variable;
1615 
1616   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1617 }
1618 
1619 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1620   // Verify that we have no forward references left.  If so, there was a goto
1621   // or address of a label taken, but no definition of it.  Label fwd
1622   // definitions are indicated with a null substmt which is also not a resolved
1623   // MS inline assembly label name.
1624   bool Diagnose = false;
1625   if (L->isMSAsmLabel())
1626     Diagnose = !L->isResolvedMSAsmLabel();
1627   else
1628     Diagnose = L->getStmt() == nullptr;
1629   if (Diagnose)
1630     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1631 }
1632 
1633 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1634   S->mergeNRVOIntoParent();
1635 
1636   if (S->decl_empty()) return;
1637   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1638          "Scope shouldn't contain decls!");
1639 
1640   for (auto *TmpD : S->decls()) {
1641     assert(TmpD && "This decl didn't get pushed??");
1642 
1643     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1644     NamedDecl *D = cast<NamedDecl>(TmpD);
1645 
1646     if (!D->getDeclName()) continue;
1647 
1648     // Diagnose unused variables in this scope.
1649     if (!S->hasUnrecoverableErrorOccurred()) {
1650       DiagnoseUnusedDecl(D);
1651       if (const auto *RD = dyn_cast<RecordDecl>(D))
1652         DiagnoseUnusedNestedTypedefs(RD);
1653     }
1654 
1655     // If this was a forward reference to a label, verify it was defined.
1656     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1657       CheckPoppedLabel(LD, *this);
1658 
1659     // Remove this name from our lexical scope, and warn on it if we haven't
1660     // already.
1661     IdResolver.RemoveDecl(D);
1662     auto ShadowI = ShadowingDecls.find(D);
1663     if (ShadowI != ShadowingDecls.end()) {
1664       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1665         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1666             << D << FD << FD->getParent();
1667         Diag(FD->getLocation(), diag::note_previous_declaration);
1668       }
1669       ShadowingDecls.erase(ShadowI);
1670     }
1671   }
1672 }
1673 
1674 /// \brief Look for an Objective-C class in the translation unit.
1675 ///
1676 /// \param Id The name of the Objective-C class we're looking for. If
1677 /// typo-correction fixes this name, the Id will be updated
1678 /// to the fixed name.
1679 ///
1680 /// \param IdLoc The location of the name in the translation unit.
1681 ///
1682 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1683 /// if there is no class with the given name.
1684 ///
1685 /// \returns The declaration of the named Objective-C class, or NULL if the
1686 /// class could not be found.
1687 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1688                                               SourceLocation IdLoc,
1689                                               bool DoTypoCorrection) {
1690   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1691   // creation from this context.
1692   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1693 
1694   if (!IDecl && DoTypoCorrection) {
1695     // Perform typo correction at the given location, but only if we
1696     // find an Objective-C class name.
1697     if (TypoCorrection C = CorrectTypo(
1698             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1699             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1700             CTK_ErrorRecovery)) {
1701       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1702       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1703       Id = IDecl->getIdentifier();
1704     }
1705   }
1706   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1707   // This routine must always return a class definition, if any.
1708   if (Def && Def->getDefinition())
1709       Def = Def->getDefinition();
1710   return Def;
1711 }
1712 
1713 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1714 /// from S, where a non-field would be declared. This routine copes
1715 /// with the difference between C and C++ scoping rules in structs and
1716 /// unions. For example, the following code is well-formed in C but
1717 /// ill-formed in C++:
1718 /// @code
1719 /// struct S6 {
1720 ///   enum { BAR } e;
1721 /// };
1722 ///
1723 /// void test_S6() {
1724 ///   struct S6 a;
1725 ///   a.e = BAR;
1726 /// }
1727 /// @endcode
1728 /// For the declaration of BAR, this routine will return a different
1729 /// scope. The scope S will be the scope of the unnamed enumeration
1730 /// within S6. In C++, this routine will return the scope associated
1731 /// with S6, because the enumeration's scope is a transparent
1732 /// context but structures can contain non-field names. In C, this
1733 /// routine will return the translation unit scope, since the
1734 /// enumeration's scope is a transparent context and structures cannot
1735 /// contain non-field names.
1736 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1737   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1738          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1739          (S->isClassScope() && !getLangOpts().CPlusPlus))
1740     S = S->getParent();
1741   return S;
1742 }
1743 
1744 /// \brief Looks up the declaration of "struct objc_super" and
1745 /// saves it for later use in building builtin declaration of
1746 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1747 /// pre-existing declaration exists no action takes place.
1748 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1749                                         IdentifierInfo *II) {
1750   if (!II->isStr("objc_msgSendSuper"))
1751     return;
1752   ASTContext &Context = ThisSema.Context;
1753 
1754   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1755                       SourceLocation(), Sema::LookupTagName);
1756   ThisSema.LookupName(Result, S);
1757   if (Result.getResultKind() == LookupResult::Found)
1758     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1759       Context.setObjCSuperType(Context.getTagDeclType(TD));
1760 }
1761 
1762 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1763   switch (Error) {
1764   case ASTContext::GE_None:
1765     return "";
1766   case ASTContext::GE_Missing_stdio:
1767     return "stdio.h";
1768   case ASTContext::GE_Missing_setjmp:
1769     return "setjmp.h";
1770   case ASTContext::GE_Missing_ucontext:
1771     return "ucontext.h";
1772   }
1773   llvm_unreachable("unhandled error kind");
1774 }
1775 
1776 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1777 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1778 /// if we're creating this built-in in anticipation of redeclaring the
1779 /// built-in.
1780 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1781                                      Scope *S, bool ForRedeclaration,
1782                                      SourceLocation Loc) {
1783   LookupPredefedObjCSuperType(*this, S, II);
1784 
1785   ASTContext::GetBuiltinTypeError Error;
1786   QualType R = Context.GetBuiltinType(ID, Error);
1787   if (Error) {
1788     if (ForRedeclaration)
1789       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1790           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1791     return nullptr;
1792   }
1793 
1794   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1795     Diag(Loc, diag::ext_implicit_lib_function_decl)
1796         << Context.BuiltinInfo.getName(ID) << R;
1797     if (Context.BuiltinInfo.getHeaderName(ID) &&
1798         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1799       Diag(Loc, diag::note_include_header_or_declare)
1800           << Context.BuiltinInfo.getHeaderName(ID)
1801           << Context.BuiltinInfo.getName(ID);
1802   }
1803 
1804   if (R.isNull())
1805     return nullptr;
1806 
1807   DeclContext *Parent = Context.getTranslationUnitDecl();
1808   if (getLangOpts().CPlusPlus) {
1809     LinkageSpecDecl *CLinkageDecl =
1810         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1811                                 LinkageSpecDecl::lang_c, false);
1812     CLinkageDecl->setImplicit();
1813     Parent->addDecl(CLinkageDecl);
1814     Parent = CLinkageDecl;
1815   }
1816 
1817   FunctionDecl *New = FunctionDecl::Create(Context,
1818                                            Parent,
1819                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1820                                            SC_Extern,
1821                                            false,
1822                                            R->isFunctionProtoType());
1823   New->setImplicit();
1824 
1825   // Create Decl objects for each parameter, adding them to the
1826   // FunctionDecl.
1827   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1828     SmallVector<ParmVarDecl*, 16> Params;
1829     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1830       ParmVarDecl *parm =
1831           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1832                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1833                               SC_None, nullptr);
1834       parm->setScopeInfo(0, i);
1835       Params.push_back(parm);
1836     }
1837     New->setParams(Params);
1838   }
1839 
1840   AddKnownFunctionAttributes(New);
1841   RegisterLocallyScopedExternCDecl(New, S);
1842 
1843   // TUScope is the translation-unit scope to insert this function into.
1844   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1845   // relate Scopes to DeclContexts, and probably eliminate CurContext
1846   // entirely, but we're not there yet.
1847   DeclContext *SavedContext = CurContext;
1848   CurContext = Parent;
1849   PushOnScopeChains(New, TUScope);
1850   CurContext = SavedContext;
1851   return New;
1852 }
1853 
1854 /// Typedef declarations don't have linkage, but they still denote the same
1855 /// entity if their types are the same.
1856 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1857 /// isSameEntity.
1858 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1859                                                      TypedefNameDecl *Decl,
1860                                                      LookupResult &Previous) {
1861   // This is only interesting when modules are enabled.
1862   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1863     return;
1864 
1865   // Empty sets are uninteresting.
1866   if (Previous.empty())
1867     return;
1868 
1869   LookupResult::Filter Filter = Previous.makeFilter();
1870   while (Filter.hasNext()) {
1871     NamedDecl *Old = Filter.next();
1872 
1873     // Non-hidden declarations are never ignored.
1874     if (S.isVisible(Old))
1875       continue;
1876 
1877     // Declarations of the same entity are not ignored, even if they have
1878     // different linkages.
1879     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1880       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1881                                 Decl->getUnderlyingType()))
1882         continue;
1883 
1884       // If both declarations give a tag declaration a typedef name for linkage
1885       // purposes, then they declare the same entity.
1886       if (S.getLangOpts().CPlusPlus &&
1887           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1888           Decl->getAnonDeclWithTypedefName())
1889         continue;
1890     }
1891 
1892     Filter.erase();
1893   }
1894 
1895   Filter.done();
1896 }
1897 
1898 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1899   QualType OldType;
1900   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1901     OldType = OldTypedef->getUnderlyingType();
1902   else
1903     OldType = Context.getTypeDeclType(Old);
1904   QualType NewType = New->getUnderlyingType();
1905 
1906   if (NewType->isVariablyModifiedType()) {
1907     // Must not redefine a typedef with a variably-modified type.
1908     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1909     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1910       << Kind << NewType;
1911     if (Old->getLocation().isValid())
1912       Diag(Old->getLocation(), diag::note_previous_definition);
1913     New->setInvalidDecl();
1914     return true;
1915   }
1916 
1917   if (OldType != NewType &&
1918       !OldType->isDependentType() &&
1919       !NewType->isDependentType() &&
1920       !Context.hasSameType(OldType, NewType)) {
1921     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1922     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1923       << Kind << NewType << OldType;
1924     if (Old->getLocation().isValid())
1925       Diag(Old->getLocation(), diag::note_previous_definition);
1926     New->setInvalidDecl();
1927     return true;
1928   }
1929   return false;
1930 }
1931 
1932 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1933 /// same name and scope as a previous declaration 'Old'.  Figure out
1934 /// how to resolve this situation, merging decls or emitting
1935 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1936 ///
1937 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1938                                 LookupResult &OldDecls) {
1939   // If the new decl is known invalid already, don't bother doing any
1940   // merging checks.
1941   if (New->isInvalidDecl()) return;
1942 
1943   // Allow multiple definitions for ObjC built-in typedefs.
1944   // FIXME: Verify the underlying types are equivalent!
1945   if (getLangOpts().ObjC1) {
1946     const IdentifierInfo *TypeID = New->getIdentifier();
1947     switch (TypeID->getLength()) {
1948     default: break;
1949     case 2:
1950       {
1951         if (!TypeID->isStr("id"))
1952           break;
1953         QualType T = New->getUnderlyingType();
1954         if (!T->isPointerType())
1955           break;
1956         if (!T->isVoidPointerType()) {
1957           QualType PT = T->getAs<PointerType>()->getPointeeType();
1958           if (!PT->isStructureType())
1959             break;
1960         }
1961         Context.setObjCIdRedefinitionType(T);
1962         // Install the built-in type for 'id', ignoring the current definition.
1963         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1964         return;
1965       }
1966     case 5:
1967       if (!TypeID->isStr("Class"))
1968         break;
1969       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1970       // Install the built-in type for 'Class', ignoring the current definition.
1971       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1972       return;
1973     case 3:
1974       if (!TypeID->isStr("SEL"))
1975         break;
1976       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1977       // Install the built-in type for 'SEL', ignoring the current definition.
1978       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1979       return;
1980     }
1981     // Fall through - the typedef name was not a builtin type.
1982   }
1983 
1984   // Verify the old decl was also a type.
1985   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1986   if (!Old) {
1987     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1988       << New->getDeclName();
1989 
1990     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1991     if (OldD->getLocation().isValid())
1992       Diag(OldD->getLocation(), diag::note_previous_definition);
1993 
1994     return New->setInvalidDecl();
1995   }
1996 
1997   // If the old declaration is invalid, just give up here.
1998   if (Old->isInvalidDecl())
1999     return New->setInvalidDecl();
2000 
2001   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2002     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2003     auto *NewTag = New->getAnonDeclWithTypedefName();
2004     NamedDecl *Hidden = nullptr;
2005     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2006         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2007         !hasVisibleDefinition(OldTag, &Hidden)) {
2008       // There is a definition of this tag, but it is not visible. Use it
2009       // instead of our tag.
2010       New->setTypeForDecl(OldTD->getTypeForDecl());
2011       if (OldTD->isModed())
2012         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2013                                     OldTD->getUnderlyingType());
2014       else
2015         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2016 
2017       // Make the old tag definition visible.
2018       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2019 
2020       // If this was an unscoped enumeration, yank all of its enumerators
2021       // out of the scope.
2022       if (isa<EnumDecl>(NewTag)) {
2023         Scope *EnumScope = getNonFieldDeclScope(S);
2024         for (auto *D : NewTag->decls()) {
2025           auto *ED = cast<EnumConstantDecl>(D);
2026           assert(EnumScope->isDeclScope(ED));
2027           EnumScope->RemoveDecl(ED);
2028           IdResolver.RemoveDecl(ED);
2029           ED->getLexicalDeclContext()->removeDecl(ED);
2030         }
2031       }
2032     }
2033   }
2034 
2035   // If the typedef types are not identical, reject them in all languages and
2036   // with any extensions enabled.
2037   if (isIncompatibleTypedef(Old, New))
2038     return;
2039 
2040   // The types match.  Link up the redeclaration chain and merge attributes if
2041   // the old declaration was a typedef.
2042   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2043     New->setPreviousDecl(Typedef);
2044     mergeDeclAttributes(New, Old);
2045   }
2046 
2047   if (getLangOpts().MicrosoftExt)
2048     return;
2049 
2050   if (getLangOpts().CPlusPlus) {
2051     // C++ [dcl.typedef]p2:
2052     //   In a given non-class scope, a typedef specifier can be used to
2053     //   redefine the name of any type declared in that scope to refer
2054     //   to the type to which it already refers.
2055     if (!isa<CXXRecordDecl>(CurContext))
2056       return;
2057 
2058     // C++0x [dcl.typedef]p4:
2059     //   In a given class scope, a typedef specifier can be used to redefine
2060     //   any class-name declared in that scope that is not also a typedef-name
2061     //   to refer to the type to which it already refers.
2062     //
2063     // This wording came in via DR424, which was a correction to the
2064     // wording in DR56, which accidentally banned code like:
2065     //
2066     //   struct S {
2067     //     typedef struct A { } A;
2068     //   };
2069     //
2070     // in the C++03 standard. We implement the C++0x semantics, which
2071     // allow the above but disallow
2072     //
2073     //   struct S {
2074     //     typedef int I;
2075     //     typedef int I;
2076     //   };
2077     //
2078     // since that was the intent of DR56.
2079     if (!isa<TypedefNameDecl>(Old))
2080       return;
2081 
2082     Diag(New->getLocation(), diag::err_redefinition)
2083       << New->getDeclName();
2084     Diag(Old->getLocation(), diag::note_previous_definition);
2085     return New->setInvalidDecl();
2086   }
2087 
2088   // Modules always permit redefinition of typedefs, as does C11.
2089   if (getLangOpts().Modules || getLangOpts().C11)
2090     return;
2091 
2092   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2093   // is normally mapped to an error, but can be controlled with
2094   // -Wtypedef-redefinition.  If either the original or the redefinition is
2095   // in a system header, don't emit this for compatibility with GCC.
2096   if (getDiagnostics().getSuppressSystemWarnings() &&
2097       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2098        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2099     return;
2100 
2101   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2102     << New->getDeclName();
2103   Diag(Old->getLocation(), diag::note_previous_definition);
2104 }
2105 
2106 /// DeclhasAttr - returns true if decl Declaration already has the target
2107 /// attribute.
2108 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2109   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2110   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2111   for (const auto *i : D->attrs())
2112     if (i->getKind() == A->getKind()) {
2113       if (Ann) {
2114         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2115           return true;
2116         continue;
2117       }
2118       // FIXME: Don't hardcode this check
2119       if (OA && isa<OwnershipAttr>(i))
2120         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2121       return true;
2122     }
2123 
2124   return false;
2125 }
2126 
2127 static bool isAttributeTargetADefinition(Decl *D) {
2128   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2129     return VD->isThisDeclarationADefinition();
2130   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2131     return TD->isCompleteDefinition() || TD->isBeingDefined();
2132   return true;
2133 }
2134 
2135 /// Merge alignment attributes from \p Old to \p New, taking into account the
2136 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2137 ///
2138 /// \return \c true if any attributes were added to \p New.
2139 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2140   // Look for alignas attributes on Old, and pick out whichever attribute
2141   // specifies the strictest alignment requirement.
2142   AlignedAttr *OldAlignasAttr = nullptr;
2143   AlignedAttr *OldStrictestAlignAttr = nullptr;
2144   unsigned OldAlign = 0;
2145   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2146     // FIXME: We have no way of representing inherited dependent alignments
2147     // in a case like:
2148     //   template<int A, int B> struct alignas(A) X;
2149     //   template<int A, int B> struct alignas(B) X {};
2150     // For now, we just ignore any alignas attributes which are not on the
2151     // definition in such a case.
2152     if (I->isAlignmentDependent())
2153       return false;
2154 
2155     if (I->isAlignas())
2156       OldAlignasAttr = I;
2157 
2158     unsigned Align = I->getAlignment(S.Context);
2159     if (Align > OldAlign) {
2160       OldAlign = Align;
2161       OldStrictestAlignAttr = I;
2162     }
2163   }
2164 
2165   // Look for alignas attributes on New.
2166   AlignedAttr *NewAlignasAttr = nullptr;
2167   unsigned NewAlign = 0;
2168   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2169     if (I->isAlignmentDependent())
2170       return false;
2171 
2172     if (I->isAlignas())
2173       NewAlignasAttr = I;
2174 
2175     unsigned Align = I->getAlignment(S.Context);
2176     if (Align > NewAlign)
2177       NewAlign = Align;
2178   }
2179 
2180   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2181     // Both declarations have 'alignas' attributes. We require them to match.
2182     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2183     // fall short. (If two declarations both have alignas, they must both match
2184     // every definition, and so must match each other if there is a definition.)
2185 
2186     // If either declaration only contains 'alignas(0)' specifiers, then it
2187     // specifies the natural alignment for the type.
2188     if (OldAlign == 0 || NewAlign == 0) {
2189       QualType Ty;
2190       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2191         Ty = VD->getType();
2192       else
2193         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2194 
2195       if (OldAlign == 0)
2196         OldAlign = S.Context.getTypeAlign(Ty);
2197       if (NewAlign == 0)
2198         NewAlign = S.Context.getTypeAlign(Ty);
2199     }
2200 
2201     if (OldAlign != NewAlign) {
2202       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2203         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2204         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2205       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2206     }
2207   }
2208 
2209   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2210     // C++11 [dcl.align]p6:
2211     //   if any declaration of an entity has an alignment-specifier,
2212     //   every defining declaration of that entity shall specify an
2213     //   equivalent alignment.
2214     // C11 6.7.5/7:
2215     //   If the definition of an object does not have an alignment
2216     //   specifier, any other declaration of that object shall also
2217     //   have no alignment specifier.
2218     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2219       << OldAlignasAttr;
2220     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2221       << OldAlignasAttr;
2222   }
2223 
2224   bool AnyAdded = false;
2225 
2226   // Ensure we have an attribute representing the strictest alignment.
2227   if (OldAlign > NewAlign) {
2228     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2229     Clone->setInherited(true);
2230     New->addAttr(Clone);
2231     AnyAdded = true;
2232   }
2233 
2234   // Ensure we have an alignas attribute if the old declaration had one.
2235   if (OldAlignasAttr && !NewAlignasAttr &&
2236       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2237     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2238     Clone->setInherited(true);
2239     New->addAttr(Clone);
2240     AnyAdded = true;
2241   }
2242 
2243   return AnyAdded;
2244 }
2245 
2246 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2247                                const InheritableAttr *Attr,
2248                                Sema::AvailabilityMergeKind AMK) {
2249   InheritableAttr *NewAttr = nullptr;
2250   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2251   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2252     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2253                                       AA->isImplicit(), AA->getIntroduced(),
2254                                       AA->getDeprecated(),
2255                                       AA->getObsoleted(), AA->getUnavailable(),
2256                                       AA->getMessage(), AA->getStrict(),
2257                                       AA->getReplacement(), AMK,
2258                                       AttrSpellingListIndex);
2259   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2260     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2261                                     AttrSpellingListIndex);
2262   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2263     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2264                                         AttrSpellingListIndex);
2265   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2266     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2267                                    AttrSpellingListIndex);
2268   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2269     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2270                                    AttrSpellingListIndex);
2271   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2272     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2273                                 FA->getFormatIdx(), FA->getFirstArg(),
2274                                 AttrSpellingListIndex);
2275   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2276     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2277                                  AttrSpellingListIndex);
2278   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2279     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2280                                        AttrSpellingListIndex,
2281                                        IA->getSemanticSpelling());
2282   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2283     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2284                                       &S.Context.Idents.get(AA->getSpelling()),
2285                                       AttrSpellingListIndex);
2286   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2287     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2288   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2289     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2290   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2291     NewAttr = S.mergeInternalLinkageAttr(
2292         D, InternalLinkageA->getRange(),
2293         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2294         AttrSpellingListIndex);
2295   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2296     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2297                                 &S.Context.Idents.get(CommonA->getSpelling()),
2298                                 AttrSpellingListIndex);
2299   else if (isa<AlignedAttr>(Attr))
2300     // AlignedAttrs are handled separately, because we need to handle all
2301     // such attributes on a declaration at the same time.
2302     NewAttr = nullptr;
2303   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2304            (AMK == Sema::AMK_Override ||
2305             AMK == Sema::AMK_ProtocolImplementation))
2306     NewAttr = nullptr;
2307   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2308     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2309 
2310   if (NewAttr) {
2311     NewAttr->setInherited(true);
2312     D->addAttr(NewAttr);
2313     if (isa<MSInheritanceAttr>(NewAttr))
2314       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2315     return true;
2316   }
2317 
2318   return false;
2319 }
2320 
2321 static const Decl *getDefinition(const Decl *D) {
2322   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2323     return TD->getDefinition();
2324   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2325     const VarDecl *Def = VD->getDefinition();
2326     if (Def)
2327       return Def;
2328     return VD->getActingDefinition();
2329   }
2330   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2331     const FunctionDecl* Def;
2332     if (FD->isDefined(Def))
2333       return Def;
2334   }
2335   return nullptr;
2336 }
2337 
2338 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2339   for (const auto *Attribute : D->attrs())
2340     if (Attribute->getKind() == Kind)
2341       return true;
2342   return false;
2343 }
2344 
2345 /// checkNewAttributesAfterDef - If we already have a definition, check that
2346 /// there are no new attributes in this declaration.
2347 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2348   if (!New->hasAttrs())
2349     return;
2350 
2351   const Decl *Def = getDefinition(Old);
2352   if (!Def || Def == New)
2353     return;
2354 
2355   AttrVec &NewAttributes = New->getAttrs();
2356   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2357     const Attr *NewAttribute = NewAttributes[I];
2358 
2359     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2360       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2361         Sema::SkipBodyInfo SkipBody;
2362         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2363 
2364         // If we're skipping this definition, drop the "alias" attribute.
2365         if (SkipBody.ShouldSkip) {
2366           NewAttributes.erase(NewAttributes.begin() + I);
2367           --E;
2368           continue;
2369         }
2370       } else {
2371         VarDecl *VD = cast<VarDecl>(New);
2372         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2373                                 VarDecl::TentativeDefinition
2374                             ? diag::err_alias_after_tentative
2375                             : diag::err_redefinition;
2376         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2377         S.Diag(Def->getLocation(), diag::note_previous_definition);
2378         VD->setInvalidDecl();
2379       }
2380       ++I;
2381       continue;
2382     }
2383 
2384     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2385       // Tentative definitions are only interesting for the alias check above.
2386       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2387         ++I;
2388         continue;
2389       }
2390     }
2391 
2392     if (hasAttribute(Def, NewAttribute->getKind())) {
2393       ++I;
2394       continue; // regular attr merging will take care of validating this.
2395     }
2396 
2397     if (isa<C11NoReturnAttr>(NewAttribute)) {
2398       // C's _Noreturn is allowed to be added to a function after it is defined.
2399       ++I;
2400       continue;
2401     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2402       if (AA->isAlignas()) {
2403         // C++11 [dcl.align]p6:
2404         //   if any declaration of an entity has an alignment-specifier,
2405         //   every defining declaration of that entity shall specify an
2406         //   equivalent alignment.
2407         // C11 6.7.5/7:
2408         //   If the definition of an object does not have an alignment
2409         //   specifier, any other declaration of that object shall also
2410         //   have no alignment specifier.
2411         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2412           << AA;
2413         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2414           << AA;
2415         NewAttributes.erase(NewAttributes.begin() + I);
2416         --E;
2417         continue;
2418       }
2419     }
2420 
2421     S.Diag(NewAttribute->getLocation(),
2422            diag::warn_attribute_precede_definition);
2423     S.Diag(Def->getLocation(), diag::note_previous_definition);
2424     NewAttributes.erase(NewAttributes.begin() + I);
2425     --E;
2426   }
2427 }
2428 
2429 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2430 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2431                                AvailabilityMergeKind AMK) {
2432   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2433     UsedAttr *NewAttr = OldAttr->clone(Context);
2434     NewAttr->setInherited(true);
2435     New->addAttr(NewAttr);
2436   }
2437 
2438   if (!Old->hasAttrs() && !New->hasAttrs())
2439     return;
2440 
2441   // Attributes declared post-definition are currently ignored.
2442   checkNewAttributesAfterDef(*this, New, Old);
2443 
2444   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2445     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2446       if (OldA->getLabel() != NewA->getLabel()) {
2447         // This redeclaration changes __asm__ label.
2448         Diag(New->getLocation(), diag::err_different_asm_label);
2449         Diag(OldA->getLocation(), diag::note_previous_declaration);
2450       }
2451     } else if (Old->isUsed()) {
2452       // This redeclaration adds an __asm__ label to a declaration that has
2453       // already been ODR-used.
2454       Diag(New->getLocation(), diag::err_late_asm_label_name)
2455         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2456     }
2457   }
2458 
2459   // Re-declaration cannot add abi_tag's.
2460   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2461     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2462       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2463         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2464                       NewTag) == OldAbiTagAttr->tags_end()) {
2465           Diag(NewAbiTagAttr->getLocation(),
2466                diag::err_new_abi_tag_on_redeclaration)
2467               << NewTag;
2468           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2469         }
2470       }
2471     } else {
2472       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2473       Diag(Old->getLocation(), diag::note_previous_declaration);
2474     }
2475   }
2476 
2477   if (!Old->hasAttrs())
2478     return;
2479 
2480   bool foundAny = New->hasAttrs();
2481 
2482   // Ensure that any moving of objects within the allocated map is done before
2483   // we process them.
2484   if (!foundAny) New->setAttrs(AttrVec());
2485 
2486   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2487     // Ignore deprecated/unavailable/availability attributes if requested.
2488     AvailabilityMergeKind LocalAMK = AMK_None;
2489     if (isa<DeprecatedAttr>(I) ||
2490         isa<UnavailableAttr>(I) ||
2491         isa<AvailabilityAttr>(I)) {
2492       switch (AMK) {
2493       case AMK_None:
2494         continue;
2495 
2496       case AMK_Redeclaration:
2497       case AMK_Override:
2498       case AMK_ProtocolImplementation:
2499         LocalAMK = AMK;
2500         break;
2501       }
2502     }
2503 
2504     // Already handled.
2505     if (isa<UsedAttr>(I))
2506       continue;
2507 
2508     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2509       foundAny = true;
2510   }
2511 
2512   if (mergeAlignedAttrs(*this, New, Old))
2513     foundAny = true;
2514 
2515   if (!foundAny) New->dropAttrs();
2516 }
2517 
2518 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2519 /// to the new one.
2520 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2521                                      const ParmVarDecl *oldDecl,
2522                                      Sema &S) {
2523   // C++11 [dcl.attr.depend]p2:
2524   //   The first declaration of a function shall specify the
2525   //   carries_dependency attribute for its declarator-id if any declaration
2526   //   of the function specifies the carries_dependency attribute.
2527   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2528   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2529     S.Diag(CDA->getLocation(),
2530            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2531     // Find the first declaration of the parameter.
2532     // FIXME: Should we build redeclaration chains for function parameters?
2533     const FunctionDecl *FirstFD =
2534       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2535     const ParmVarDecl *FirstVD =
2536       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2537     S.Diag(FirstVD->getLocation(),
2538            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2539   }
2540 
2541   if (!oldDecl->hasAttrs())
2542     return;
2543 
2544   bool foundAny = newDecl->hasAttrs();
2545 
2546   // Ensure that any moving of objects within the allocated map is
2547   // done before we process them.
2548   if (!foundAny) newDecl->setAttrs(AttrVec());
2549 
2550   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2551     if (!DeclHasAttr(newDecl, I)) {
2552       InheritableAttr *newAttr =
2553         cast<InheritableParamAttr>(I->clone(S.Context));
2554       newAttr->setInherited(true);
2555       newDecl->addAttr(newAttr);
2556       foundAny = true;
2557     }
2558   }
2559 
2560   if (!foundAny) newDecl->dropAttrs();
2561 }
2562 
2563 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2564                                 const ParmVarDecl *OldParam,
2565                                 Sema &S) {
2566   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2567     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2568       if (*Oldnullability != *Newnullability) {
2569         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2570           << DiagNullabilityKind(
2571                *Newnullability,
2572                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2573                 != 0))
2574           << DiagNullabilityKind(
2575                *Oldnullability,
2576                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2577                 != 0));
2578         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2579       }
2580     } else {
2581       QualType NewT = NewParam->getType();
2582       NewT = S.Context.getAttributedType(
2583                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2584                          NewT, NewT);
2585       NewParam->setType(NewT);
2586     }
2587   }
2588 }
2589 
2590 namespace {
2591 
2592 /// Used in MergeFunctionDecl to keep track of function parameters in
2593 /// C.
2594 struct GNUCompatibleParamWarning {
2595   ParmVarDecl *OldParm;
2596   ParmVarDecl *NewParm;
2597   QualType PromotedType;
2598 };
2599 
2600 } // end anonymous namespace
2601 
2602 /// getSpecialMember - get the special member enum for a method.
2603 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2604   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2605     if (Ctor->isDefaultConstructor())
2606       return Sema::CXXDefaultConstructor;
2607 
2608     if (Ctor->isCopyConstructor())
2609       return Sema::CXXCopyConstructor;
2610 
2611     if (Ctor->isMoveConstructor())
2612       return Sema::CXXMoveConstructor;
2613   } else if (isa<CXXDestructorDecl>(MD)) {
2614     return Sema::CXXDestructor;
2615   } else if (MD->isCopyAssignmentOperator()) {
2616     return Sema::CXXCopyAssignment;
2617   } else if (MD->isMoveAssignmentOperator()) {
2618     return Sema::CXXMoveAssignment;
2619   }
2620 
2621   return Sema::CXXInvalid;
2622 }
2623 
2624 // Determine whether the previous declaration was a definition, implicit
2625 // declaration, or a declaration.
2626 template <typename T>
2627 static std::pair<diag::kind, SourceLocation>
2628 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2629   diag::kind PrevDiag;
2630   SourceLocation OldLocation = Old->getLocation();
2631   if (Old->isThisDeclarationADefinition())
2632     PrevDiag = diag::note_previous_definition;
2633   else if (Old->isImplicit()) {
2634     PrevDiag = diag::note_previous_implicit_declaration;
2635     if (OldLocation.isInvalid())
2636       OldLocation = New->getLocation();
2637   } else
2638     PrevDiag = diag::note_previous_declaration;
2639   return std::make_pair(PrevDiag, OldLocation);
2640 }
2641 
2642 /// canRedefineFunction - checks if a function can be redefined. Currently,
2643 /// only extern inline functions can be redefined, and even then only in
2644 /// GNU89 mode.
2645 static bool canRedefineFunction(const FunctionDecl *FD,
2646                                 const LangOptions& LangOpts) {
2647   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2648           !LangOpts.CPlusPlus &&
2649           FD->isInlineSpecified() &&
2650           FD->getStorageClass() == SC_Extern);
2651 }
2652 
2653 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2654   const AttributedType *AT = T->getAs<AttributedType>();
2655   while (AT && !AT->isCallingConv())
2656     AT = AT->getModifiedType()->getAs<AttributedType>();
2657   return AT;
2658 }
2659 
2660 template <typename T>
2661 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2662   const DeclContext *DC = Old->getDeclContext();
2663   if (DC->isRecord())
2664     return false;
2665 
2666   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2667   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2668     return true;
2669   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2670     return true;
2671   return false;
2672 }
2673 
2674 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2675 static bool isExternC(VarTemplateDecl *) { return false; }
2676 
2677 /// \brief Check whether a redeclaration of an entity introduced by a
2678 /// using-declaration is valid, given that we know it's not an overload
2679 /// (nor a hidden tag declaration).
2680 template<typename ExpectedDecl>
2681 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2682                                    ExpectedDecl *New) {
2683   // C++11 [basic.scope.declarative]p4:
2684   //   Given a set of declarations in a single declarative region, each of
2685   //   which specifies the same unqualified name,
2686   //   -- they shall all refer to the same entity, or all refer to functions
2687   //      and function templates; or
2688   //   -- exactly one declaration shall declare a class name or enumeration
2689   //      name that is not a typedef name and the other declarations shall all
2690   //      refer to the same variable or enumerator, or all refer to functions
2691   //      and function templates; in this case the class name or enumeration
2692   //      name is hidden (3.3.10).
2693 
2694   // C++11 [namespace.udecl]p14:
2695   //   If a function declaration in namespace scope or block scope has the
2696   //   same name and the same parameter-type-list as a function introduced
2697   //   by a using-declaration, and the declarations do not declare the same
2698   //   function, the program is ill-formed.
2699 
2700   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2701   if (Old &&
2702       !Old->getDeclContext()->getRedeclContext()->Equals(
2703           New->getDeclContext()->getRedeclContext()) &&
2704       !(isExternC(Old) && isExternC(New)))
2705     Old = nullptr;
2706 
2707   if (!Old) {
2708     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2709     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2710     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2711     return true;
2712   }
2713   return false;
2714 }
2715 
2716 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2717                                             const FunctionDecl *B) {
2718   assert(A->getNumParams() == B->getNumParams());
2719 
2720   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2721     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2722     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2723     if (AttrA == AttrB)
2724       return true;
2725     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2726   };
2727 
2728   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2729 }
2730 
2731 /// MergeFunctionDecl - We just parsed a function 'New' from
2732 /// declarator D which has the same name and scope as a previous
2733 /// declaration 'Old'.  Figure out how to resolve this situation,
2734 /// merging decls or emitting diagnostics as appropriate.
2735 ///
2736 /// In C++, New and Old must be declarations that are not
2737 /// overloaded. Use IsOverload to determine whether New and Old are
2738 /// overloaded, and to select the Old declaration that New should be
2739 /// merged with.
2740 ///
2741 /// Returns true if there was an error, false otherwise.
2742 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2743                              Scope *S, bool MergeTypeWithOld) {
2744   // Verify the old decl was also a function.
2745   FunctionDecl *Old = OldD->getAsFunction();
2746   if (!Old) {
2747     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2748       if (New->getFriendObjectKind()) {
2749         Diag(New->getLocation(), diag::err_using_decl_friend);
2750         Diag(Shadow->getTargetDecl()->getLocation(),
2751              diag::note_using_decl_target);
2752         Diag(Shadow->getUsingDecl()->getLocation(),
2753              diag::note_using_decl) << 0;
2754         return true;
2755       }
2756 
2757       // Check whether the two declarations might declare the same function.
2758       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2759         return true;
2760       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2761     } else {
2762       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2763         << New->getDeclName();
2764       Diag(OldD->getLocation(), diag::note_previous_definition);
2765       return true;
2766     }
2767   }
2768 
2769   // If the old declaration is invalid, just give up here.
2770   if (Old->isInvalidDecl())
2771     return true;
2772 
2773   diag::kind PrevDiag;
2774   SourceLocation OldLocation;
2775   std::tie(PrevDiag, OldLocation) =
2776       getNoteDiagForInvalidRedeclaration(Old, New);
2777 
2778   // Don't complain about this if we're in GNU89 mode and the old function
2779   // is an extern inline function.
2780   // Don't complain about specializations. They are not supposed to have
2781   // storage classes.
2782   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2783       New->getStorageClass() == SC_Static &&
2784       Old->hasExternalFormalLinkage() &&
2785       !New->getTemplateSpecializationInfo() &&
2786       !canRedefineFunction(Old, getLangOpts())) {
2787     if (getLangOpts().MicrosoftExt) {
2788       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2789       Diag(OldLocation, PrevDiag);
2790     } else {
2791       Diag(New->getLocation(), diag::err_static_non_static) << New;
2792       Diag(OldLocation, PrevDiag);
2793       return true;
2794     }
2795   }
2796 
2797   if (New->hasAttr<InternalLinkageAttr>() &&
2798       !Old->hasAttr<InternalLinkageAttr>()) {
2799     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2800         << New->getDeclName();
2801     Diag(Old->getLocation(), diag::note_previous_definition);
2802     New->dropAttr<InternalLinkageAttr>();
2803   }
2804 
2805   // If a function is first declared with a calling convention, but is later
2806   // declared or defined without one, all following decls assume the calling
2807   // convention of the first.
2808   //
2809   // It's OK if a function is first declared without a calling convention,
2810   // but is later declared or defined with the default calling convention.
2811   //
2812   // To test if either decl has an explicit calling convention, we look for
2813   // AttributedType sugar nodes on the type as written.  If they are missing or
2814   // were canonicalized away, we assume the calling convention was implicit.
2815   //
2816   // Note also that we DO NOT return at this point, because we still have
2817   // other tests to run.
2818   QualType OldQType = Context.getCanonicalType(Old->getType());
2819   QualType NewQType = Context.getCanonicalType(New->getType());
2820   const FunctionType *OldType = cast<FunctionType>(OldQType);
2821   const FunctionType *NewType = cast<FunctionType>(NewQType);
2822   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2823   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2824   bool RequiresAdjustment = false;
2825 
2826   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2827     FunctionDecl *First = Old->getFirstDecl();
2828     const FunctionType *FT =
2829         First->getType().getCanonicalType()->castAs<FunctionType>();
2830     FunctionType::ExtInfo FI = FT->getExtInfo();
2831     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2832     if (!NewCCExplicit) {
2833       // Inherit the CC from the previous declaration if it was specified
2834       // there but not here.
2835       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2836       RequiresAdjustment = true;
2837     } else {
2838       // Calling conventions aren't compatible, so complain.
2839       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2840       Diag(New->getLocation(), diag::err_cconv_change)
2841         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2842         << !FirstCCExplicit
2843         << (!FirstCCExplicit ? "" :
2844             FunctionType::getNameForCallConv(FI.getCC()));
2845 
2846       // Put the note on the first decl, since it is the one that matters.
2847       Diag(First->getLocation(), diag::note_previous_declaration);
2848       return true;
2849     }
2850   }
2851 
2852   // FIXME: diagnose the other way around?
2853   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2854     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2855     RequiresAdjustment = true;
2856   }
2857 
2858   // Merge regparm attribute.
2859   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2860       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2861     if (NewTypeInfo.getHasRegParm()) {
2862       Diag(New->getLocation(), diag::err_regparm_mismatch)
2863         << NewType->getRegParmType()
2864         << OldType->getRegParmType();
2865       Diag(OldLocation, diag::note_previous_declaration);
2866       return true;
2867     }
2868 
2869     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2870     RequiresAdjustment = true;
2871   }
2872 
2873   // Merge ns_returns_retained attribute.
2874   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2875     if (NewTypeInfo.getProducesResult()) {
2876       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2877       Diag(OldLocation, diag::note_previous_declaration);
2878       return true;
2879     }
2880 
2881     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2882     RequiresAdjustment = true;
2883   }
2884 
2885   if (RequiresAdjustment) {
2886     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2887     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2888     New->setType(QualType(AdjustedType, 0));
2889     NewQType = Context.getCanonicalType(New->getType());
2890     NewType = cast<FunctionType>(NewQType);
2891   }
2892 
2893   // If this redeclaration makes the function inline, we may need to add it to
2894   // UndefinedButUsed.
2895   if (!Old->isInlined() && New->isInlined() &&
2896       !New->hasAttr<GNUInlineAttr>() &&
2897       !getLangOpts().GNUInline &&
2898       Old->isUsed(false) &&
2899       !Old->isDefined() && !New->isThisDeclarationADefinition())
2900     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2901                                            SourceLocation()));
2902 
2903   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2904   // about it.
2905   if (New->hasAttr<GNUInlineAttr>() &&
2906       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2907     UndefinedButUsed.erase(Old->getCanonicalDecl());
2908   }
2909 
2910   // If pass_object_size params don't match up perfectly, this isn't a valid
2911   // redeclaration.
2912   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2913       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2914     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2915         << New->getDeclName();
2916     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2917     return true;
2918   }
2919 
2920   if (getLangOpts().CPlusPlus) {
2921     // (C++98 13.1p2):
2922     //   Certain function declarations cannot be overloaded:
2923     //     -- Function declarations that differ only in the return type
2924     //        cannot be overloaded.
2925 
2926     // Go back to the type source info to compare the declared return types,
2927     // per C++1y [dcl.type.auto]p13:
2928     //   Redeclarations or specializations of a function or function template
2929     //   with a declared return type that uses a placeholder type shall also
2930     //   use that placeholder, not a deduced type.
2931     QualType OldDeclaredReturnType =
2932         (Old->getTypeSourceInfo()
2933              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2934              : OldType)->getReturnType();
2935     QualType NewDeclaredReturnType =
2936         (New->getTypeSourceInfo()
2937              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2938              : NewType)->getReturnType();
2939     QualType ResQT;
2940     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2941         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2942           New->isLocalExternDecl())) {
2943       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2944           OldDeclaredReturnType->isObjCObjectPointerType())
2945         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2946       if (ResQT.isNull()) {
2947         if (New->isCXXClassMember() && New->isOutOfLine())
2948           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2949               << New << New->getReturnTypeSourceRange();
2950         else
2951           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2952               << New->getReturnTypeSourceRange();
2953         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2954                                     << Old->getReturnTypeSourceRange();
2955         return true;
2956       }
2957       else
2958         NewQType = ResQT;
2959     }
2960 
2961     QualType OldReturnType = OldType->getReturnType();
2962     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2963     if (OldReturnType != NewReturnType) {
2964       // If this function has a deduced return type and has already been
2965       // defined, copy the deduced value from the old declaration.
2966       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2967       if (OldAT && OldAT->isDeduced()) {
2968         New->setType(
2969             SubstAutoType(New->getType(),
2970                           OldAT->isDependentType() ? Context.DependentTy
2971                                                    : OldAT->getDeducedType()));
2972         NewQType = Context.getCanonicalType(
2973             SubstAutoType(NewQType,
2974                           OldAT->isDependentType() ? Context.DependentTy
2975                                                    : OldAT->getDeducedType()));
2976       }
2977     }
2978 
2979     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2980     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2981     if (OldMethod && NewMethod) {
2982       // Preserve triviality.
2983       NewMethod->setTrivial(OldMethod->isTrivial());
2984 
2985       // MSVC allows explicit template specialization at class scope:
2986       // 2 CXXMethodDecls referring to the same function will be injected.
2987       // We don't want a redeclaration error.
2988       bool IsClassScopeExplicitSpecialization =
2989                               OldMethod->isFunctionTemplateSpecialization() &&
2990                               NewMethod->isFunctionTemplateSpecialization();
2991       bool isFriend = NewMethod->getFriendObjectKind();
2992 
2993       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2994           !IsClassScopeExplicitSpecialization) {
2995         //    -- Member function declarations with the same name and the
2996         //       same parameter types cannot be overloaded if any of them
2997         //       is a static member function declaration.
2998         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2999           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3000           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3001           return true;
3002         }
3003 
3004         // C++ [class.mem]p1:
3005         //   [...] A member shall not be declared twice in the
3006         //   member-specification, except that a nested class or member
3007         //   class template can be declared and then later defined.
3008         if (ActiveTemplateInstantiations.empty()) {
3009           unsigned NewDiag;
3010           if (isa<CXXConstructorDecl>(OldMethod))
3011             NewDiag = diag::err_constructor_redeclared;
3012           else if (isa<CXXDestructorDecl>(NewMethod))
3013             NewDiag = diag::err_destructor_redeclared;
3014           else if (isa<CXXConversionDecl>(NewMethod))
3015             NewDiag = diag::err_conv_function_redeclared;
3016           else
3017             NewDiag = diag::err_member_redeclared;
3018 
3019           Diag(New->getLocation(), NewDiag);
3020         } else {
3021           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3022             << New << New->getType();
3023         }
3024         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3025         return true;
3026 
3027       // Complain if this is an explicit declaration of a special
3028       // member that was initially declared implicitly.
3029       //
3030       // As an exception, it's okay to befriend such methods in order
3031       // to permit the implicit constructor/destructor/operator calls.
3032       } else if (OldMethod->isImplicit()) {
3033         if (isFriend) {
3034           NewMethod->setImplicit();
3035         } else {
3036           Diag(NewMethod->getLocation(),
3037                diag::err_definition_of_implicitly_declared_member)
3038             << New << getSpecialMember(OldMethod);
3039           return true;
3040         }
3041       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3042         Diag(NewMethod->getLocation(),
3043              diag::err_definition_of_explicitly_defaulted_member)
3044           << getSpecialMember(OldMethod);
3045         return true;
3046       }
3047     }
3048 
3049     // C++11 [dcl.attr.noreturn]p1:
3050     //   The first declaration of a function shall specify the noreturn
3051     //   attribute if any declaration of that function specifies the noreturn
3052     //   attribute.
3053     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3054     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3055       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3056       Diag(Old->getFirstDecl()->getLocation(),
3057            diag::note_noreturn_missing_first_decl);
3058     }
3059 
3060     // C++11 [dcl.attr.depend]p2:
3061     //   The first declaration of a function shall specify the
3062     //   carries_dependency attribute for its declarator-id if any declaration
3063     //   of the function specifies the carries_dependency attribute.
3064     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3065     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3066       Diag(CDA->getLocation(),
3067            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3068       Diag(Old->getFirstDecl()->getLocation(),
3069            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3070     }
3071 
3072     // (C++98 8.3.5p3):
3073     //   All declarations for a function shall agree exactly in both the
3074     //   return type and the parameter-type-list.
3075     // We also want to respect all the extended bits except noreturn.
3076 
3077     // noreturn should now match unless the old type info didn't have it.
3078     QualType OldQTypeForComparison = OldQType;
3079     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3080       assert(OldQType == QualType(OldType, 0));
3081       const FunctionType *OldTypeForComparison
3082         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3083       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3084       assert(OldQTypeForComparison.isCanonical());
3085     }
3086 
3087     if (haveIncompatibleLanguageLinkages(Old, New)) {
3088       // As a special case, retain the language linkage from previous
3089       // declarations of a friend function as an extension.
3090       //
3091       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3092       // and is useful because there's otherwise no way to specify language
3093       // linkage within class scope.
3094       //
3095       // Check cautiously as the friend object kind isn't yet complete.
3096       if (New->getFriendObjectKind() != Decl::FOK_None) {
3097         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3098         Diag(OldLocation, PrevDiag);
3099       } else {
3100         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3101         Diag(OldLocation, PrevDiag);
3102         return true;
3103       }
3104     }
3105 
3106     if (OldQTypeForComparison == NewQType)
3107       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3108 
3109     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3110         New->isLocalExternDecl()) {
3111       // It's OK if we couldn't merge types for a local function declaraton
3112       // if either the old or new type is dependent. We'll merge the types
3113       // when we instantiate the function.
3114       return false;
3115     }
3116 
3117     // Fall through for conflicting redeclarations and redefinitions.
3118   }
3119 
3120   // C: Function types need to be compatible, not identical. This handles
3121   // duplicate function decls like "void f(int); void f(enum X);" properly.
3122   if (!getLangOpts().CPlusPlus &&
3123       Context.typesAreCompatible(OldQType, NewQType)) {
3124     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3125     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3126     const FunctionProtoType *OldProto = nullptr;
3127     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3128         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3129       // The old declaration provided a function prototype, but the
3130       // new declaration does not. Merge in the prototype.
3131       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3132       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3133       NewQType =
3134           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3135                                   OldProto->getExtProtoInfo());
3136       New->setType(NewQType);
3137       New->setHasInheritedPrototype();
3138 
3139       // Synthesize parameters with the same types.
3140       SmallVector<ParmVarDecl*, 16> Params;
3141       for (const auto &ParamType : OldProto->param_types()) {
3142         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3143                                                  SourceLocation(), nullptr,
3144                                                  ParamType, /*TInfo=*/nullptr,
3145                                                  SC_None, nullptr);
3146         Param->setScopeInfo(0, Params.size());
3147         Param->setImplicit();
3148         Params.push_back(Param);
3149       }
3150 
3151       New->setParams(Params);
3152     }
3153 
3154     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3155   }
3156 
3157   // GNU C permits a K&R definition to follow a prototype declaration
3158   // if the declared types of the parameters in the K&R definition
3159   // match the types in the prototype declaration, even when the
3160   // promoted types of the parameters from the K&R definition differ
3161   // from the types in the prototype. GCC then keeps the types from
3162   // the prototype.
3163   //
3164   // If a variadic prototype is followed by a non-variadic K&R definition,
3165   // the K&R definition becomes variadic.  This is sort of an edge case, but
3166   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3167   // C99 6.9.1p8.
3168   if (!getLangOpts().CPlusPlus &&
3169       Old->hasPrototype() && !New->hasPrototype() &&
3170       New->getType()->getAs<FunctionProtoType>() &&
3171       Old->getNumParams() == New->getNumParams()) {
3172     SmallVector<QualType, 16> ArgTypes;
3173     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3174     const FunctionProtoType *OldProto
3175       = Old->getType()->getAs<FunctionProtoType>();
3176     const FunctionProtoType *NewProto
3177       = New->getType()->getAs<FunctionProtoType>();
3178 
3179     // Determine whether this is the GNU C extension.
3180     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3181                                                NewProto->getReturnType());
3182     bool LooseCompatible = !MergedReturn.isNull();
3183     for (unsigned Idx = 0, End = Old->getNumParams();
3184          LooseCompatible && Idx != End; ++Idx) {
3185       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3186       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3187       if (Context.typesAreCompatible(OldParm->getType(),
3188                                      NewProto->getParamType(Idx))) {
3189         ArgTypes.push_back(NewParm->getType());
3190       } else if (Context.typesAreCompatible(OldParm->getType(),
3191                                             NewParm->getType(),
3192                                             /*CompareUnqualified=*/true)) {
3193         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3194                                            NewProto->getParamType(Idx) };
3195         Warnings.push_back(Warn);
3196         ArgTypes.push_back(NewParm->getType());
3197       } else
3198         LooseCompatible = false;
3199     }
3200 
3201     if (LooseCompatible) {
3202       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3203         Diag(Warnings[Warn].NewParm->getLocation(),
3204              diag::ext_param_promoted_not_compatible_with_prototype)
3205           << Warnings[Warn].PromotedType
3206           << Warnings[Warn].OldParm->getType();
3207         if (Warnings[Warn].OldParm->getLocation().isValid())
3208           Diag(Warnings[Warn].OldParm->getLocation(),
3209                diag::note_previous_declaration);
3210       }
3211 
3212       if (MergeTypeWithOld)
3213         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3214                                              OldProto->getExtProtoInfo()));
3215       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3216     }
3217 
3218     // Fall through to diagnose conflicting types.
3219   }
3220 
3221   // A function that has already been declared has been redeclared or
3222   // defined with a different type; show an appropriate diagnostic.
3223 
3224   // If the previous declaration was an implicitly-generated builtin
3225   // declaration, then at the very least we should use a specialized note.
3226   unsigned BuiltinID;
3227   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3228     // If it's actually a library-defined builtin function like 'malloc'
3229     // or 'printf', just warn about the incompatible redeclaration.
3230     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3231       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3232       Diag(OldLocation, diag::note_previous_builtin_declaration)
3233         << Old << Old->getType();
3234 
3235       // If this is a global redeclaration, just forget hereafter
3236       // about the "builtin-ness" of the function.
3237       //
3238       // Doing this for local extern declarations is problematic.  If
3239       // the builtin declaration remains visible, a second invalid
3240       // local declaration will produce a hard error; if it doesn't
3241       // remain visible, a single bogus local redeclaration (which is
3242       // actually only a warning) could break all the downstream code.
3243       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3244         New->getIdentifier()->revertBuiltin();
3245 
3246       return false;
3247     }
3248 
3249     PrevDiag = diag::note_previous_builtin_declaration;
3250   }
3251 
3252   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3253   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3254   return true;
3255 }
3256 
3257 /// \brief Completes the merge of two function declarations that are
3258 /// known to be compatible.
3259 ///
3260 /// This routine handles the merging of attributes and other
3261 /// properties of function declarations from the old declaration to
3262 /// the new declaration, once we know that New is in fact a
3263 /// redeclaration of Old.
3264 ///
3265 /// \returns false
3266 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3267                                         Scope *S, bool MergeTypeWithOld) {
3268   // Merge the attributes
3269   mergeDeclAttributes(New, Old);
3270 
3271   // Merge "pure" flag.
3272   if (Old->isPure())
3273     New->setPure();
3274 
3275   // Merge "used" flag.
3276   if (Old->getMostRecentDecl()->isUsed(false))
3277     New->setIsUsed();
3278 
3279   // Merge attributes from the parameters.  These can mismatch with K&R
3280   // declarations.
3281   if (New->getNumParams() == Old->getNumParams())
3282       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3283         ParmVarDecl *NewParam = New->getParamDecl(i);
3284         ParmVarDecl *OldParam = Old->getParamDecl(i);
3285         mergeParamDeclAttributes(NewParam, OldParam, *this);
3286         mergeParamDeclTypes(NewParam, OldParam, *this);
3287       }
3288 
3289   if (getLangOpts().CPlusPlus)
3290     return MergeCXXFunctionDecl(New, Old, S);
3291 
3292   // Merge the function types so the we get the composite types for the return
3293   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3294   // was visible.
3295   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3296   if (!Merged.isNull() && MergeTypeWithOld)
3297     New->setType(Merged);
3298 
3299   return false;
3300 }
3301 
3302 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3303                                 ObjCMethodDecl *oldMethod) {
3304   // Merge the attributes, including deprecated/unavailable
3305   AvailabilityMergeKind MergeKind =
3306     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3307       ? AMK_ProtocolImplementation
3308       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3309                                                        : AMK_Override;
3310 
3311   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3312 
3313   // Merge attributes from the parameters.
3314   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3315                                        oe = oldMethod->param_end();
3316   for (ObjCMethodDecl::param_iterator
3317          ni = newMethod->param_begin(), ne = newMethod->param_end();
3318        ni != ne && oi != oe; ++ni, ++oi)
3319     mergeParamDeclAttributes(*ni, *oi, *this);
3320 
3321   CheckObjCMethodOverride(newMethod, oldMethod);
3322 }
3323 
3324 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3325   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3326 
3327   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3328          ? diag::err_redefinition_different_type
3329          : diag::err_redeclaration_different_type)
3330     << New->getDeclName() << New->getType() << Old->getType();
3331 
3332   diag::kind PrevDiag;
3333   SourceLocation OldLocation;
3334   std::tie(PrevDiag, OldLocation)
3335     = getNoteDiagForInvalidRedeclaration(Old, New);
3336   S.Diag(OldLocation, PrevDiag);
3337   New->setInvalidDecl();
3338 }
3339 
3340 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3341 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3342 /// emitting diagnostics as appropriate.
3343 ///
3344 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3345 /// to here in AddInitializerToDecl. We can't check them before the initializer
3346 /// is attached.
3347 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3348                              bool MergeTypeWithOld) {
3349   if (New->isInvalidDecl() || Old->isInvalidDecl())
3350     return;
3351 
3352   QualType MergedT;
3353   if (getLangOpts().CPlusPlus) {
3354     if (New->getType()->isUndeducedType()) {
3355       // We don't know what the new type is until the initializer is attached.
3356       return;
3357     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3358       // These could still be something that needs exception specs checked.
3359       return MergeVarDeclExceptionSpecs(New, Old);
3360     }
3361     // C++ [basic.link]p10:
3362     //   [...] the types specified by all declarations referring to a given
3363     //   object or function shall be identical, except that declarations for an
3364     //   array object can specify array types that differ by the presence or
3365     //   absence of a major array bound (8.3.4).
3366     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3367       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3368       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3369 
3370       // We are merging a variable declaration New into Old. If it has an array
3371       // bound, and that bound differs from Old's bound, we should diagnose the
3372       // mismatch.
3373       if (!NewArray->isIncompleteArrayType()) {
3374         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3375              PrevVD = PrevVD->getPreviousDecl()) {
3376           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3377           if (PrevVDTy->isIncompleteArrayType())
3378             continue;
3379 
3380           if (!Context.hasSameType(NewArray, PrevVDTy))
3381             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3382         }
3383       }
3384 
3385       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3386         if (Context.hasSameType(OldArray->getElementType(),
3387                                 NewArray->getElementType()))
3388           MergedT = New->getType();
3389       }
3390       // FIXME: Check visibility. New is hidden but has a complete type. If New
3391       // has no array bound, it should not inherit one from Old, if Old is not
3392       // visible.
3393       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3394         if (Context.hasSameType(OldArray->getElementType(),
3395                                 NewArray->getElementType()))
3396           MergedT = Old->getType();
3397       }
3398     }
3399     else if (New->getType()->isObjCObjectPointerType() &&
3400                Old->getType()->isObjCObjectPointerType()) {
3401       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3402                                               Old->getType());
3403     }
3404   } else {
3405     // C 6.2.7p2:
3406     //   All declarations that refer to the same object or function shall have
3407     //   compatible type.
3408     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3409   }
3410   if (MergedT.isNull()) {
3411     // It's OK if we couldn't merge types if either type is dependent, for a
3412     // block-scope variable. In other cases (static data members of class
3413     // templates, variable templates, ...), we require the types to be
3414     // equivalent.
3415     // FIXME: The C++ standard doesn't say anything about this.
3416     if ((New->getType()->isDependentType() ||
3417          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3418       // If the old type was dependent, we can't merge with it, so the new type
3419       // becomes dependent for now. We'll reproduce the original type when we
3420       // instantiate the TypeSourceInfo for the variable.
3421       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3422         New->setType(Context.DependentTy);
3423       return;
3424     }
3425     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3426   }
3427 
3428   // Don't actually update the type on the new declaration if the old
3429   // declaration was an extern declaration in a different scope.
3430   if (MergeTypeWithOld)
3431     New->setType(MergedT);
3432 }
3433 
3434 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3435                                   LookupResult &Previous) {
3436   // C11 6.2.7p4:
3437   //   For an identifier with internal or external linkage declared
3438   //   in a scope in which a prior declaration of that identifier is
3439   //   visible, if the prior declaration specifies internal or
3440   //   external linkage, the type of the identifier at the later
3441   //   declaration becomes the composite type.
3442   //
3443   // If the variable isn't visible, we do not merge with its type.
3444   if (Previous.isShadowed())
3445     return false;
3446 
3447   if (S.getLangOpts().CPlusPlus) {
3448     // C++11 [dcl.array]p3:
3449     //   If there is a preceding declaration of the entity in the same
3450     //   scope in which the bound was specified, an omitted array bound
3451     //   is taken to be the same as in that earlier declaration.
3452     return NewVD->isPreviousDeclInSameBlockScope() ||
3453            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3454             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3455   } else {
3456     // If the old declaration was function-local, don't merge with its
3457     // type unless we're in the same function.
3458     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3459            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3460   }
3461 }
3462 
3463 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3464 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3465 /// situation, merging decls or emitting diagnostics as appropriate.
3466 ///
3467 /// Tentative definition rules (C99 6.9.2p2) are checked by
3468 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3469 /// definitions here, since the initializer hasn't been attached.
3470 ///
3471 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3472   // If the new decl is already invalid, don't do any other checking.
3473   if (New->isInvalidDecl())
3474     return;
3475 
3476   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3477     return;
3478 
3479   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3480 
3481   // Verify the old decl was also a variable or variable template.
3482   VarDecl *Old = nullptr;
3483   VarTemplateDecl *OldTemplate = nullptr;
3484   if (Previous.isSingleResult()) {
3485     if (NewTemplate) {
3486       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3487       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3488 
3489       if (auto *Shadow =
3490               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3491         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3492           return New->setInvalidDecl();
3493     } else {
3494       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3495 
3496       if (auto *Shadow =
3497               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3498         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3499           return New->setInvalidDecl();
3500     }
3501   }
3502   if (!Old) {
3503     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3504       << New->getDeclName();
3505     Diag(Previous.getRepresentativeDecl()->getLocation(),
3506          diag::note_previous_definition);
3507     return New->setInvalidDecl();
3508   }
3509 
3510   // Ensure the template parameters are compatible.
3511   if (NewTemplate &&
3512       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3513                                       OldTemplate->getTemplateParameters(),
3514                                       /*Complain=*/true, TPL_TemplateMatch))
3515     return New->setInvalidDecl();
3516 
3517   // C++ [class.mem]p1:
3518   //   A member shall not be declared twice in the member-specification [...]
3519   //
3520   // Here, we need only consider static data members.
3521   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3522     Diag(New->getLocation(), diag::err_duplicate_member)
3523       << New->getIdentifier();
3524     Diag(Old->getLocation(), diag::note_previous_declaration);
3525     New->setInvalidDecl();
3526   }
3527 
3528   mergeDeclAttributes(New, Old);
3529   // Warn if an already-declared variable is made a weak_import in a subsequent
3530   // declaration
3531   if (New->hasAttr<WeakImportAttr>() &&
3532       Old->getStorageClass() == SC_None &&
3533       !Old->hasAttr<WeakImportAttr>()) {
3534     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3535     Diag(Old->getLocation(), diag::note_previous_definition);
3536     // Remove weak_import attribute on new declaration.
3537     New->dropAttr<WeakImportAttr>();
3538   }
3539 
3540   if (New->hasAttr<InternalLinkageAttr>() &&
3541       !Old->hasAttr<InternalLinkageAttr>()) {
3542     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3543         << New->getDeclName();
3544     Diag(Old->getLocation(), diag::note_previous_definition);
3545     New->dropAttr<InternalLinkageAttr>();
3546   }
3547 
3548   // Merge the types.
3549   VarDecl *MostRecent = Old->getMostRecentDecl();
3550   if (MostRecent != Old) {
3551     MergeVarDeclTypes(New, MostRecent,
3552                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3553     if (New->isInvalidDecl())
3554       return;
3555   }
3556 
3557   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3558   if (New->isInvalidDecl())
3559     return;
3560 
3561   diag::kind PrevDiag;
3562   SourceLocation OldLocation;
3563   std::tie(PrevDiag, OldLocation) =
3564       getNoteDiagForInvalidRedeclaration(Old, New);
3565 
3566   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3567   if (New->getStorageClass() == SC_Static &&
3568       !New->isStaticDataMember() &&
3569       Old->hasExternalFormalLinkage()) {
3570     if (getLangOpts().MicrosoftExt) {
3571       Diag(New->getLocation(), diag::ext_static_non_static)
3572           << New->getDeclName();
3573       Diag(OldLocation, PrevDiag);
3574     } else {
3575       Diag(New->getLocation(), diag::err_static_non_static)
3576           << New->getDeclName();
3577       Diag(OldLocation, PrevDiag);
3578       return New->setInvalidDecl();
3579     }
3580   }
3581   // C99 6.2.2p4:
3582   //   For an identifier declared with the storage-class specifier
3583   //   extern in a scope in which a prior declaration of that
3584   //   identifier is visible,23) if the prior declaration specifies
3585   //   internal or external linkage, the linkage of the identifier at
3586   //   the later declaration is the same as the linkage specified at
3587   //   the prior declaration. If no prior declaration is visible, or
3588   //   if the prior declaration specifies no linkage, then the
3589   //   identifier has external linkage.
3590   if (New->hasExternalStorage() && Old->hasLinkage())
3591     /* Okay */;
3592   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3593            !New->isStaticDataMember() &&
3594            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3595     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3596     Diag(OldLocation, PrevDiag);
3597     return New->setInvalidDecl();
3598   }
3599 
3600   // Check if extern is followed by non-extern and vice-versa.
3601   if (New->hasExternalStorage() &&
3602       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3603     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3604     Diag(OldLocation, PrevDiag);
3605     return New->setInvalidDecl();
3606   }
3607   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3608       !New->hasExternalStorage()) {
3609     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3610     Diag(OldLocation, PrevDiag);
3611     return New->setInvalidDecl();
3612   }
3613 
3614   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3615 
3616   // FIXME: The test for external storage here seems wrong? We still
3617   // need to check for mismatches.
3618   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3619       // Don't complain about out-of-line definitions of static members.
3620       !(Old->getLexicalDeclContext()->isRecord() &&
3621         !New->getLexicalDeclContext()->isRecord())) {
3622     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3623     Diag(OldLocation, PrevDiag);
3624     return New->setInvalidDecl();
3625   }
3626 
3627   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3628     if (VarDecl *Def = Old->getDefinition()) {
3629       // C++1z [dcl.fcn.spec]p4:
3630       //   If the definition of a variable appears in a translation unit before
3631       //   its first declaration as inline, the program is ill-formed.
3632       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3633       Diag(Def->getLocation(), diag::note_previous_definition);
3634     }
3635   }
3636 
3637   // If this redeclaration makes the function inline, we may need to add it to
3638   // UndefinedButUsed.
3639   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3640       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3641     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3642                                            SourceLocation()));
3643 
3644   if (New->getTLSKind() != Old->getTLSKind()) {
3645     if (!Old->getTLSKind()) {
3646       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3647       Diag(OldLocation, PrevDiag);
3648     } else if (!New->getTLSKind()) {
3649       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3650       Diag(OldLocation, PrevDiag);
3651     } else {
3652       // Do not allow redeclaration to change the variable between requiring
3653       // static and dynamic initialization.
3654       // FIXME: GCC allows this, but uses the TLS keyword on the first
3655       // declaration to determine the kind. Do we need to be compatible here?
3656       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3657         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3658       Diag(OldLocation, PrevDiag);
3659     }
3660   }
3661 
3662   // C++ doesn't have tentative definitions, so go right ahead and check here.
3663   VarDecl *Def;
3664   if (getLangOpts().CPlusPlus &&
3665       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3666       (Def = Old->getDefinition())) {
3667     NamedDecl *Hidden = nullptr;
3668     if (!hasVisibleDefinition(Def, &Hidden) &&
3669         (New->getFormalLinkage() == InternalLinkage ||
3670          New->getDescribedVarTemplate() ||
3671          New->getNumTemplateParameterLists() ||
3672          New->getDeclContext()->isDependentContext())) {
3673       // The previous definition is hidden, and multiple definitions are
3674       // permitted (in separate TUs). Form another definition of it.
3675     } else if (Old->isStaticDataMember() &&
3676                Old->getCanonicalDecl()->isInline() &&
3677                Old->getCanonicalDecl()->isConstexpr()) {
3678       // This definition won't be a definition any more once it's been merged.
3679       Diag(New->getLocation(),
3680            diag::warn_deprecated_redundant_constexpr_static_def);
3681     } else {
3682       Diag(New->getLocation(), diag::err_redefinition) << New;
3683       Diag(Def->getLocation(), diag::note_previous_definition);
3684       New->setInvalidDecl();
3685       return;
3686     }
3687   }
3688 
3689   if (haveIncompatibleLanguageLinkages(Old, New)) {
3690     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3691     Diag(OldLocation, PrevDiag);
3692     New->setInvalidDecl();
3693     return;
3694   }
3695 
3696   // Merge "used" flag.
3697   if (Old->getMostRecentDecl()->isUsed(false))
3698     New->setIsUsed();
3699 
3700   // Keep a chain of previous declarations.
3701   New->setPreviousDecl(Old);
3702   if (NewTemplate)
3703     NewTemplate->setPreviousDecl(OldTemplate);
3704 
3705   // Inherit access appropriately.
3706   New->setAccess(Old->getAccess());
3707   if (NewTemplate)
3708     NewTemplate->setAccess(New->getAccess());
3709 
3710   if (Old->isInline())
3711     New->setImplicitlyInline();
3712 }
3713 
3714 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3715 /// no declarator (e.g. "struct foo;") is parsed.
3716 Decl *
3717 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3718                                  RecordDecl *&AnonRecord) {
3719   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3720                                     AnonRecord);
3721 }
3722 
3723 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3724 // disambiguate entities defined in different scopes.
3725 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3726 // compatibility.
3727 // We will pick our mangling number depending on which version of MSVC is being
3728 // targeted.
3729 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3730   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3731              ? S->getMSCurManglingNumber()
3732              : S->getMSLastManglingNumber();
3733 }
3734 
3735 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3736   if (!Context.getLangOpts().CPlusPlus)
3737     return;
3738 
3739   if (isa<CXXRecordDecl>(Tag->getParent())) {
3740     // If this tag is the direct child of a class, number it if
3741     // it is anonymous.
3742     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3743       return;
3744     MangleNumberingContext &MCtx =
3745         Context.getManglingNumberContext(Tag->getParent());
3746     Context.setManglingNumber(
3747         Tag, MCtx.getManglingNumber(
3748                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3749     return;
3750   }
3751 
3752   // If this tag isn't a direct child of a class, number it if it is local.
3753   Decl *ManglingContextDecl;
3754   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3755           Tag->getDeclContext(), ManglingContextDecl)) {
3756     Context.setManglingNumber(
3757         Tag, MCtx->getManglingNumber(
3758                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3759   }
3760 }
3761 
3762 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3763                                         TypedefNameDecl *NewTD) {
3764   if (TagFromDeclSpec->isInvalidDecl())
3765     return;
3766 
3767   // Do nothing if the tag already has a name for linkage purposes.
3768   if (TagFromDeclSpec->hasNameForLinkage())
3769     return;
3770 
3771   // A well-formed anonymous tag must always be a TUK_Definition.
3772   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3773 
3774   // The type must match the tag exactly;  no qualifiers allowed.
3775   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3776                            Context.getTagDeclType(TagFromDeclSpec))) {
3777     if (getLangOpts().CPlusPlus)
3778       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3779     return;
3780   }
3781 
3782   // If we've already computed linkage for the anonymous tag, then
3783   // adding a typedef name for the anonymous decl can change that
3784   // linkage, which might be a serious problem.  Diagnose this as
3785   // unsupported and ignore the typedef name.  TODO: we should
3786   // pursue this as a language defect and establish a formal rule
3787   // for how to handle it.
3788   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3789     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3790 
3791     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3792     tagLoc = getLocForEndOfToken(tagLoc);
3793 
3794     llvm::SmallString<40> textToInsert;
3795     textToInsert += ' ';
3796     textToInsert += NewTD->getIdentifier()->getName();
3797     Diag(tagLoc, diag::note_typedef_changes_linkage)
3798         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3799     return;
3800   }
3801 
3802   // Otherwise, set this is the anon-decl typedef for the tag.
3803   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3804 }
3805 
3806 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3807   switch (T) {
3808   case DeclSpec::TST_class:
3809     return 0;
3810   case DeclSpec::TST_struct:
3811     return 1;
3812   case DeclSpec::TST_interface:
3813     return 2;
3814   case DeclSpec::TST_union:
3815     return 3;
3816   case DeclSpec::TST_enum:
3817     return 4;
3818   default:
3819     llvm_unreachable("unexpected type specifier");
3820   }
3821 }
3822 
3823 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3824 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3825 /// parameters to cope with template friend declarations.
3826 Decl *
3827 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3828                                  MultiTemplateParamsArg TemplateParams,
3829                                  bool IsExplicitInstantiation,
3830                                  RecordDecl *&AnonRecord) {
3831   Decl *TagD = nullptr;
3832   TagDecl *Tag = nullptr;
3833   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3834       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3835       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3836       DS.getTypeSpecType() == DeclSpec::TST_union ||
3837       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3838     TagD = DS.getRepAsDecl();
3839 
3840     if (!TagD) // We probably had an error
3841       return nullptr;
3842 
3843     // Note that the above type specs guarantee that the
3844     // type rep is a Decl, whereas in many of the others
3845     // it's a Type.
3846     if (isa<TagDecl>(TagD))
3847       Tag = cast<TagDecl>(TagD);
3848     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3849       Tag = CTD->getTemplatedDecl();
3850   }
3851 
3852   if (Tag) {
3853     handleTagNumbering(Tag, S);
3854     Tag->setFreeStanding();
3855     if (Tag->isInvalidDecl())
3856       return Tag;
3857   }
3858 
3859   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3860     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3861     // or incomplete types shall not be restrict-qualified."
3862     if (TypeQuals & DeclSpec::TQ_restrict)
3863       Diag(DS.getRestrictSpecLoc(),
3864            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3865            << DS.getSourceRange();
3866   }
3867 
3868   if (DS.isInlineSpecified())
3869     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3870         << getLangOpts().CPlusPlus1z;
3871 
3872   if (DS.isConstexprSpecified()) {
3873     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3874     // and definitions of functions and variables.
3875     if (Tag)
3876       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3877           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3878     else
3879       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3880     // Don't emit warnings after this error.
3881     return TagD;
3882   }
3883 
3884   if (DS.isConceptSpecified()) {
3885     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3886     // either a function concept and its definition or a variable concept and
3887     // its initializer.
3888     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3889     return TagD;
3890   }
3891 
3892   DiagnoseFunctionSpecifiers(DS);
3893 
3894   if (DS.isFriendSpecified()) {
3895     // If we're dealing with a decl but not a TagDecl, assume that
3896     // whatever routines created it handled the friendship aspect.
3897     if (TagD && !Tag)
3898       return nullptr;
3899     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3900   }
3901 
3902   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3903   bool IsExplicitSpecialization =
3904     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3905   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3906       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3907       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3908     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3909     // nested-name-specifier unless it is an explicit instantiation
3910     // or an explicit specialization.
3911     //
3912     // FIXME: We allow class template partial specializations here too, per the
3913     // obvious intent of DR1819.
3914     //
3915     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3916     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3917         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3918     return nullptr;
3919   }
3920 
3921   // Track whether this decl-specifier declares anything.
3922   bool DeclaresAnything = true;
3923 
3924   // Handle anonymous struct definitions.
3925   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3926     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3927         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3928       if (getLangOpts().CPlusPlus ||
3929           Record->getDeclContext()->isRecord()) {
3930         // If CurContext is a DeclContext that can contain statements,
3931         // RecursiveASTVisitor won't visit the decls that
3932         // BuildAnonymousStructOrUnion() will put into CurContext.
3933         // Also store them here so that they can be part of the
3934         // DeclStmt that gets created in this case.
3935         // FIXME: Also return the IndirectFieldDecls created by
3936         // BuildAnonymousStructOr union, for the same reason?
3937         if (CurContext->isFunctionOrMethod())
3938           AnonRecord = Record;
3939         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3940                                            Context.getPrintingPolicy());
3941       }
3942 
3943       DeclaresAnything = false;
3944     }
3945   }
3946 
3947   // C11 6.7.2.1p2:
3948   //   A struct-declaration that does not declare an anonymous structure or
3949   //   anonymous union shall contain a struct-declarator-list.
3950   //
3951   // This rule also existed in C89 and C99; the grammar for struct-declaration
3952   // did not permit a struct-declaration without a struct-declarator-list.
3953   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3954       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3955     // Check for Microsoft C extension: anonymous struct/union member.
3956     // Handle 2 kinds of anonymous struct/union:
3957     //   struct STRUCT;
3958     //   union UNION;
3959     // and
3960     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3961     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3962     if ((Tag && Tag->getDeclName()) ||
3963         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3964       RecordDecl *Record = nullptr;
3965       if (Tag)
3966         Record = dyn_cast<RecordDecl>(Tag);
3967       else if (const RecordType *RT =
3968                    DS.getRepAsType().get()->getAsStructureType())
3969         Record = RT->getDecl();
3970       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3971         Record = UT->getDecl();
3972 
3973       if (Record && getLangOpts().MicrosoftExt) {
3974         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3975           << Record->isUnion() << DS.getSourceRange();
3976         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3977       }
3978 
3979       DeclaresAnything = false;
3980     }
3981   }
3982 
3983   // Skip all the checks below if we have a type error.
3984   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3985       (TagD && TagD->isInvalidDecl()))
3986     return TagD;
3987 
3988   if (getLangOpts().CPlusPlus &&
3989       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3990     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3991       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3992           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3993         DeclaresAnything = false;
3994 
3995   if (!DS.isMissingDeclaratorOk()) {
3996     // Customize diagnostic for a typedef missing a name.
3997     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3998       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3999         << DS.getSourceRange();
4000     else
4001       DeclaresAnything = false;
4002   }
4003 
4004   if (DS.isModulePrivateSpecified() &&
4005       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4006     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4007       << Tag->getTagKind()
4008       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4009 
4010   ActOnDocumentableDecl(TagD);
4011 
4012   // C 6.7/2:
4013   //   A declaration [...] shall declare at least a declarator [...], a tag,
4014   //   or the members of an enumeration.
4015   // C++ [dcl.dcl]p3:
4016   //   [If there are no declarators], and except for the declaration of an
4017   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4018   //   names into the program, or shall redeclare a name introduced by a
4019   //   previous declaration.
4020   if (!DeclaresAnything) {
4021     // In C, we allow this as a (popular) extension / bug. Don't bother
4022     // producing further diagnostics for redundant qualifiers after this.
4023     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4024     return TagD;
4025   }
4026 
4027   // C++ [dcl.stc]p1:
4028   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4029   //   init-declarator-list of the declaration shall not be empty.
4030   // C++ [dcl.fct.spec]p1:
4031   //   If a cv-qualifier appears in a decl-specifier-seq, the
4032   //   init-declarator-list of the declaration shall not be empty.
4033   //
4034   // Spurious qualifiers here appear to be valid in C.
4035   unsigned DiagID = diag::warn_standalone_specifier;
4036   if (getLangOpts().CPlusPlus)
4037     DiagID = diag::ext_standalone_specifier;
4038 
4039   // Note that a linkage-specification sets a storage class, but
4040   // 'extern "C" struct foo;' is actually valid and not theoretically
4041   // useless.
4042   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4043     if (SCS == DeclSpec::SCS_mutable)
4044       // Since mutable is not a viable storage class specifier in C, there is
4045       // no reason to treat it as an extension. Instead, diagnose as an error.
4046       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4047     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4048       Diag(DS.getStorageClassSpecLoc(), DiagID)
4049         << DeclSpec::getSpecifierName(SCS);
4050   }
4051 
4052   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4053     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4054       << DeclSpec::getSpecifierName(TSCS);
4055   if (DS.getTypeQualifiers()) {
4056     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4057       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4058     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4059       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4060     // Restrict is covered above.
4061     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4062       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4063     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4064       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4065   }
4066 
4067   // Warn about ignored type attributes, for example:
4068   // __attribute__((aligned)) struct A;
4069   // Attributes should be placed after tag to apply to type declaration.
4070   if (!DS.getAttributes().empty()) {
4071     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4072     if (TypeSpecType == DeclSpec::TST_class ||
4073         TypeSpecType == DeclSpec::TST_struct ||
4074         TypeSpecType == DeclSpec::TST_interface ||
4075         TypeSpecType == DeclSpec::TST_union ||
4076         TypeSpecType == DeclSpec::TST_enum) {
4077       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4078            attrs = attrs->getNext())
4079         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4080             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4081     }
4082   }
4083 
4084   return TagD;
4085 }
4086 
4087 /// We are trying to inject an anonymous member into the given scope;
4088 /// check if there's an existing declaration that can't be overloaded.
4089 ///
4090 /// \return true if this is a forbidden redeclaration
4091 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4092                                          Scope *S,
4093                                          DeclContext *Owner,
4094                                          DeclarationName Name,
4095                                          SourceLocation NameLoc,
4096                                          bool IsUnion) {
4097   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4098                  Sema::ForRedeclaration);
4099   if (!SemaRef.LookupName(R, S)) return false;
4100 
4101   // Pick a representative declaration.
4102   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4103   assert(PrevDecl && "Expected a non-null Decl");
4104 
4105   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4106     return false;
4107 
4108   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4109     << IsUnion << Name;
4110   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4111 
4112   return true;
4113 }
4114 
4115 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4116 /// anonymous struct or union AnonRecord into the owning context Owner
4117 /// and scope S. This routine will be invoked just after we realize
4118 /// that an unnamed union or struct is actually an anonymous union or
4119 /// struct, e.g.,
4120 ///
4121 /// @code
4122 /// union {
4123 ///   int i;
4124 ///   float f;
4125 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4126 ///    // f into the surrounding scope.x
4127 /// @endcode
4128 ///
4129 /// This routine is recursive, injecting the names of nested anonymous
4130 /// structs/unions into the owning context and scope as well.
4131 static bool
4132 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4133                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4134                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4135   bool Invalid = false;
4136 
4137   // Look every FieldDecl and IndirectFieldDecl with a name.
4138   for (auto *D : AnonRecord->decls()) {
4139     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4140         cast<NamedDecl>(D)->getDeclName()) {
4141       ValueDecl *VD = cast<ValueDecl>(D);
4142       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4143                                        VD->getLocation(),
4144                                        AnonRecord->isUnion())) {
4145         // C++ [class.union]p2:
4146         //   The names of the members of an anonymous union shall be
4147         //   distinct from the names of any other entity in the
4148         //   scope in which the anonymous union is declared.
4149         Invalid = true;
4150       } else {
4151         // C++ [class.union]p2:
4152         //   For the purpose of name lookup, after the anonymous union
4153         //   definition, the members of the anonymous union are
4154         //   considered to have been defined in the scope in which the
4155         //   anonymous union is declared.
4156         unsigned OldChainingSize = Chaining.size();
4157         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4158           Chaining.append(IF->chain_begin(), IF->chain_end());
4159         else
4160           Chaining.push_back(VD);
4161 
4162         assert(Chaining.size() >= 2);
4163         NamedDecl **NamedChain =
4164           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4165         for (unsigned i = 0; i < Chaining.size(); i++)
4166           NamedChain[i] = Chaining[i];
4167 
4168         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4169             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4170             VD->getType(), {NamedChain, Chaining.size()});
4171 
4172         for (const auto *Attr : VD->attrs())
4173           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4174 
4175         IndirectField->setAccess(AS);
4176         IndirectField->setImplicit();
4177         SemaRef.PushOnScopeChains(IndirectField, S);
4178 
4179         // That includes picking up the appropriate access specifier.
4180         if (AS != AS_none) IndirectField->setAccess(AS);
4181 
4182         Chaining.resize(OldChainingSize);
4183       }
4184     }
4185   }
4186 
4187   return Invalid;
4188 }
4189 
4190 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4191 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4192 /// illegal input values are mapped to SC_None.
4193 static StorageClass
4194 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4195   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4196   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4197          "Parser allowed 'typedef' as storage class VarDecl.");
4198   switch (StorageClassSpec) {
4199   case DeclSpec::SCS_unspecified:    return SC_None;
4200   case DeclSpec::SCS_extern:
4201     if (DS.isExternInLinkageSpec())
4202       return SC_None;
4203     return SC_Extern;
4204   case DeclSpec::SCS_static:         return SC_Static;
4205   case DeclSpec::SCS_auto:           return SC_Auto;
4206   case DeclSpec::SCS_register:       return SC_Register;
4207   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4208     // Illegal SCSs map to None: error reporting is up to the caller.
4209   case DeclSpec::SCS_mutable:        // Fall through.
4210   case DeclSpec::SCS_typedef:        return SC_None;
4211   }
4212   llvm_unreachable("unknown storage class specifier");
4213 }
4214 
4215 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4216   assert(Record->hasInClassInitializer());
4217 
4218   for (const auto *I : Record->decls()) {
4219     const auto *FD = dyn_cast<FieldDecl>(I);
4220     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4221       FD = IFD->getAnonField();
4222     if (FD && FD->hasInClassInitializer())
4223       return FD->getLocation();
4224   }
4225 
4226   llvm_unreachable("couldn't find in-class initializer");
4227 }
4228 
4229 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4230                                       SourceLocation DefaultInitLoc) {
4231   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4232     return;
4233 
4234   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4235   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4236 }
4237 
4238 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4239                                       CXXRecordDecl *AnonUnion) {
4240   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4241     return;
4242 
4243   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4244 }
4245 
4246 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4247 /// anonymous structure or union. Anonymous unions are a C++ feature
4248 /// (C++ [class.union]) and a C11 feature; anonymous structures
4249 /// are a C11 feature and GNU C++ extension.
4250 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4251                                         AccessSpecifier AS,
4252                                         RecordDecl *Record,
4253                                         const PrintingPolicy &Policy) {
4254   DeclContext *Owner = Record->getDeclContext();
4255 
4256   // Diagnose whether this anonymous struct/union is an extension.
4257   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4258     Diag(Record->getLocation(), diag::ext_anonymous_union);
4259   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4260     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4261   else if (!Record->isUnion() && !getLangOpts().C11)
4262     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4263 
4264   // C and C++ require different kinds of checks for anonymous
4265   // structs/unions.
4266   bool Invalid = false;
4267   if (getLangOpts().CPlusPlus) {
4268     const char *PrevSpec = nullptr;
4269     unsigned DiagID;
4270     if (Record->isUnion()) {
4271       // C++ [class.union]p6:
4272       //   Anonymous unions declared in a named namespace or in the
4273       //   global namespace shall be declared static.
4274       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4275           (isa<TranslationUnitDecl>(Owner) ||
4276            (isa<NamespaceDecl>(Owner) &&
4277             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4278         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4279           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4280 
4281         // Recover by adding 'static'.
4282         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4283                                PrevSpec, DiagID, Policy);
4284       }
4285       // C++ [class.union]p6:
4286       //   A storage class is not allowed in a declaration of an
4287       //   anonymous union in a class scope.
4288       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4289                isa<RecordDecl>(Owner)) {
4290         Diag(DS.getStorageClassSpecLoc(),
4291              diag::err_anonymous_union_with_storage_spec)
4292           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4293 
4294         // Recover by removing the storage specifier.
4295         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4296                                SourceLocation(),
4297                                PrevSpec, DiagID, Context.getPrintingPolicy());
4298       }
4299     }
4300 
4301     // Ignore const/volatile/restrict qualifiers.
4302     if (DS.getTypeQualifiers()) {
4303       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4304         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4305           << Record->isUnion() << "const"
4306           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4307       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4308         Diag(DS.getVolatileSpecLoc(),
4309              diag::ext_anonymous_struct_union_qualified)
4310           << Record->isUnion() << "volatile"
4311           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4312       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4313         Diag(DS.getRestrictSpecLoc(),
4314              diag::ext_anonymous_struct_union_qualified)
4315           << Record->isUnion() << "restrict"
4316           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4317       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4318         Diag(DS.getAtomicSpecLoc(),
4319              diag::ext_anonymous_struct_union_qualified)
4320           << Record->isUnion() << "_Atomic"
4321           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4322       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4323         Diag(DS.getUnalignedSpecLoc(),
4324              diag::ext_anonymous_struct_union_qualified)
4325           << Record->isUnion() << "__unaligned"
4326           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4327 
4328       DS.ClearTypeQualifiers();
4329     }
4330 
4331     // C++ [class.union]p2:
4332     //   The member-specification of an anonymous union shall only
4333     //   define non-static data members. [Note: nested types and
4334     //   functions cannot be declared within an anonymous union. ]
4335     for (auto *Mem : Record->decls()) {
4336       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4337         // C++ [class.union]p3:
4338         //   An anonymous union shall not have private or protected
4339         //   members (clause 11).
4340         assert(FD->getAccess() != AS_none);
4341         if (FD->getAccess() != AS_public) {
4342           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4343             << Record->isUnion() << (FD->getAccess() == AS_protected);
4344           Invalid = true;
4345         }
4346 
4347         // C++ [class.union]p1
4348         //   An object of a class with a non-trivial constructor, a non-trivial
4349         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4350         //   assignment operator cannot be a member of a union, nor can an
4351         //   array of such objects.
4352         if (CheckNontrivialField(FD))
4353           Invalid = true;
4354       } else if (Mem->isImplicit()) {
4355         // Any implicit members are fine.
4356       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4357         // This is a type that showed up in an
4358         // elaborated-type-specifier inside the anonymous struct or
4359         // union, but which actually declares a type outside of the
4360         // anonymous struct or union. It's okay.
4361       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4362         if (!MemRecord->isAnonymousStructOrUnion() &&
4363             MemRecord->getDeclName()) {
4364           // Visual C++ allows type definition in anonymous struct or union.
4365           if (getLangOpts().MicrosoftExt)
4366             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4367               << Record->isUnion();
4368           else {
4369             // This is a nested type declaration.
4370             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4371               << Record->isUnion();
4372             Invalid = true;
4373           }
4374         } else {
4375           // This is an anonymous type definition within another anonymous type.
4376           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4377           // not part of standard C++.
4378           Diag(MemRecord->getLocation(),
4379                diag::ext_anonymous_record_with_anonymous_type)
4380             << Record->isUnion();
4381         }
4382       } else if (isa<AccessSpecDecl>(Mem)) {
4383         // Any access specifier is fine.
4384       } else if (isa<StaticAssertDecl>(Mem)) {
4385         // In C++1z, static_assert declarations are also fine.
4386       } else {
4387         // We have something that isn't a non-static data
4388         // member. Complain about it.
4389         unsigned DK = diag::err_anonymous_record_bad_member;
4390         if (isa<TypeDecl>(Mem))
4391           DK = diag::err_anonymous_record_with_type;
4392         else if (isa<FunctionDecl>(Mem))
4393           DK = diag::err_anonymous_record_with_function;
4394         else if (isa<VarDecl>(Mem))
4395           DK = diag::err_anonymous_record_with_static;
4396 
4397         // Visual C++ allows type definition in anonymous struct or union.
4398         if (getLangOpts().MicrosoftExt &&
4399             DK == diag::err_anonymous_record_with_type)
4400           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4401             << Record->isUnion();
4402         else {
4403           Diag(Mem->getLocation(), DK) << Record->isUnion();
4404           Invalid = true;
4405         }
4406       }
4407     }
4408 
4409     // C++11 [class.union]p8 (DR1460):
4410     //   At most one variant member of a union may have a
4411     //   brace-or-equal-initializer.
4412     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4413         Owner->isRecord())
4414       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4415                                 cast<CXXRecordDecl>(Record));
4416   }
4417 
4418   if (!Record->isUnion() && !Owner->isRecord()) {
4419     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4420       << getLangOpts().CPlusPlus;
4421     Invalid = true;
4422   }
4423 
4424   // Mock up a declarator.
4425   Declarator Dc(DS, Declarator::MemberContext);
4426   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4427   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4428 
4429   // Create a declaration for this anonymous struct/union.
4430   NamedDecl *Anon = nullptr;
4431   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4432     Anon = FieldDecl::Create(Context, OwningClass,
4433                              DS.getLocStart(),
4434                              Record->getLocation(),
4435                              /*IdentifierInfo=*/nullptr,
4436                              Context.getTypeDeclType(Record),
4437                              TInfo,
4438                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4439                              /*InitStyle=*/ICIS_NoInit);
4440     Anon->setAccess(AS);
4441     if (getLangOpts().CPlusPlus)
4442       FieldCollector->Add(cast<FieldDecl>(Anon));
4443   } else {
4444     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4445     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4446     if (SCSpec == DeclSpec::SCS_mutable) {
4447       // mutable can only appear on non-static class members, so it's always
4448       // an error here
4449       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4450       Invalid = true;
4451       SC = SC_None;
4452     }
4453 
4454     Anon = VarDecl::Create(Context, Owner,
4455                            DS.getLocStart(),
4456                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4457                            Context.getTypeDeclType(Record),
4458                            TInfo, SC);
4459 
4460     // Default-initialize the implicit variable. This initialization will be
4461     // trivial in almost all cases, except if a union member has an in-class
4462     // initializer:
4463     //   union { int n = 0; };
4464     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4465   }
4466   Anon->setImplicit();
4467 
4468   // Mark this as an anonymous struct/union type.
4469   Record->setAnonymousStructOrUnion(true);
4470 
4471   // Add the anonymous struct/union object to the current
4472   // context. We'll be referencing this object when we refer to one of
4473   // its members.
4474   Owner->addDecl(Anon);
4475 
4476   // Inject the members of the anonymous struct/union into the owning
4477   // context and into the identifier resolver chain for name lookup
4478   // purposes.
4479   SmallVector<NamedDecl*, 2> Chain;
4480   Chain.push_back(Anon);
4481 
4482   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4483     Invalid = true;
4484 
4485   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4486     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4487       Decl *ManglingContextDecl;
4488       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4489               NewVD->getDeclContext(), ManglingContextDecl)) {
4490         Context.setManglingNumber(
4491             NewVD, MCtx->getManglingNumber(
4492                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4493         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4494       }
4495     }
4496   }
4497 
4498   if (Invalid)
4499     Anon->setInvalidDecl();
4500 
4501   return Anon;
4502 }
4503 
4504 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4505 /// Microsoft C anonymous structure.
4506 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4507 /// Example:
4508 ///
4509 /// struct A { int a; };
4510 /// struct B { struct A; int b; };
4511 ///
4512 /// void foo() {
4513 ///   B var;
4514 ///   var.a = 3;
4515 /// }
4516 ///
4517 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4518                                            RecordDecl *Record) {
4519   assert(Record && "expected a record!");
4520 
4521   // Mock up a declarator.
4522   Declarator Dc(DS, Declarator::TypeNameContext);
4523   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4524   assert(TInfo && "couldn't build declarator info for anonymous struct");
4525 
4526   auto *ParentDecl = cast<RecordDecl>(CurContext);
4527   QualType RecTy = Context.getTypeDeclType(Record);
4528 
4529   // Create a declaration for this anonymous struct.
4530   NamedDecl *Anon = FieldDecl::Create(Context,
4531                              ParentDecl,
4532                              DS.getLocStart(),
4533                              DS.getLocStart(),
4534                              /*IdentifierInfo=*/nullptr,
4535                              RecTy,
4536                              TInfo,
4537                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4538                              /*InitStyle=*/ICIS_NoInit);
4539   Anon->setImplicit();
4540 
4541   // Add the anonymous struct object to the current context.
4542   CurContext->addDecl(Anon);
4543 
4544   // Inject the members of the anonymous struct into the current
4545   // context and into the identifier resolver chain for name lookup
4546   // purposes.
4547   SmallVector<NamedDecl*, 2> Chain;
4548   Chain.push_back(Anon);
4549 
4550   RecordDecl *RecordDef = Record->getDefinition();
4551   if (RequireCompleteType(Anon->getLocation(), RecTy,
4552                           diag::err_field_incomplete) ||
4553       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4554                                           AS_none, Chain)) {
4555     Anon->setInvalidDecl();
4556     ParentDecl->setInvalidDecl();
4557   }
4558 
4559   return Anon;
4560 }
4561 
4562 /// GetNameForDeclarator - Determine the full declaration name for the
4563 /// given Declarator.
4564 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4565   return GetNameFromUnqualifiedId(D.getName());
4566 }
4567 
4568 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4569 DeclarationNameInfo
4570 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4571   DeclarationNameInfo NameInfo;
4572   NameInfo.setLoc(Name.StartLocation);
4573 
4574   switch (Name.getKind()) {
4575 
4576   case UnqualifiedId::IK_ImplicitSelfParam:
4577   case UnqualifiedId::IK_Identifier:
4578     NameInfo.setName(Name.Identifier);
4579     NameInfo.setLoc(Name.StartLocation);
4580     return NameInfo;
4581 
4582   case UnqualifiedId::IK_OperatorFunctionId:
4583     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4584                                            Name.OperatorFunctionId.Operator));
4585     NameInfo.setLoc(Name.StartLocation);
4586     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4587       = Name.OperatorFunctionId.SymbolLocations[0];
4588     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4589       = Name.EndLocation.getRawEncoding();
4590     return NameInfo;
4591 
4592   case UnqualifiedId::IK_LiteralOperatorId:
4593     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4594                                                            Name.Identifier));
4595     NameInfo.setLoc(Name.StartLocation);
4596     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4597     return NameInfo;
4598 
4599   case UnqualifiedId::IK_ConversionFunctionId: {
4600     TypeSourceInfo *TInfo;
4601     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4602     if (Ty.isNull())
4603       return DeclarationNameInfo();
4604     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4605                                                Context.getCanonicalType(Ty)));
4606     NameInfo.setLoc(Name.StartLocation);
4607     NameInfo.setNamedTypeInfo(TInfo);
4608     return NameInfo;
4609   }
4610 
4611   case UnqualifiedId::IK_ConstructorName: {
4612     TypeSourceInfo *TInfo;
4613     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4614     if (Ty.isNull())
4615       return DeclarationNameInfo();
4616     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4617                                               Context.getCanonicalType(Ty)));
4618     NameInfo.setLoc(Name.StartLocation);
4619     NameInfo.setNamedTypeInfo(TInfo);
4620     return NameInfo;
4621   }
4622 
4623   case UnqualifiedId::IK_ConstructorTemplateId: {
4624     // In well-formed code, we can only have a constructor
4625     // template-id that refers to the current context, so go there
4626     // to find the actual type being constructed.
4627     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4628     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4629       return DeclarationNameInfo();
4630 
4631     // Determine the type of the class being constructed.
4632     QualType CurClassType = Context.getTypeDeclType(CurClass);
4633 
4634     // FIXME: Check two things: that the template-id names the same type as
4635     // CurClassType, and that the template-id does not occur when the name
4636     // was qualified.
4637 
4638     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4639                                     Context.getCanonicalType(CurClassType)));
4640     NameInfo.setLoc(Name.StartLocation);
4641     // FIXME: should we retrieve TypeSourceInfo?
4642     NameInfo.setNamedTypeInfo(nullptr);
4643     return NameInfo;
4644   }
4645 
4646   case UnqualifiedId::IK_DestructorName: {
4647     TypeSourceInfo *TInfo;
4648     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4649     if (Ty.isNull())
4650       return DeclarationNameInfo();
4651     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4652                                               Context.getCanonicalType(Ty)));
4653     NameInfo.setLoc(Name.StartLocation);
4654     NameInfo.setNamedTypeInfo(TInfo);
4655     return NameInfo;
4656   }
4657 
4658   case UnqualifiedId::IK_TemplateId: {
4659     TemplateName TName = Name.TemplateId->Template.get();
4660     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4661     return Context.getNameForTemplate(TName, TNameLoc);
4662   }
4663 
4664   } // switch (Name.getKind())
4665 
4666   llvm_unreachable("Unknown name kind");
4667 }
4668 
4669 static QualType getCoreType(QualType Ty) {
4670   do {
4671     if (Ty->isPointerType() || Ty->isReferenceType())
4672       Ty = Ty->getPointeeType();
4673     else if (Ty->isArrayType())
4674       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4675     else
4676       return Ty.withoutLocalFastQualifiers();
4677   } while (true);
4678 }
4679 
4680 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4681 /// and Definition have "nearly" matching parameters. This heuristic is
4682 /// used to improve diagnostics in the case where an out-of-line function
4683 /// definition doesn't match any declaration within the class or namespace.
4684 /// Also sets Params to the list of indices to the parameters that differ
4685 /// between the declaration and the definition. If hasSimilarParameters
4686 /// returns true and Params is empty, then all of the parameters match.
4687 static bool hasSimilarParameters(ASTContext &Context,
4688                                      FunctionDecl *Declaration,
4689                                      FunctionDecl *Definition,
4690                                      SmallVectorImpl<unsigned> &Params) {
4691   Params.clear();
4692   if (Declaration->param_size() != Definition->param_size())
4693     return false;
4694   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4695     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4696     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4697 
4698     // The parameter types are identical
4699     if (Context.hasSameType(DefParamTy, DeclParamTy))
4700       continue;
4701 
4702     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4703     QualType DefParamBaseTy = getCoreType(DefParamTy);
4704     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4705     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4706 
4707     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4708         (DeclTyName && DeclTyName == DefTyName))
4709       Params.push_back(Idx);
4710     else  // The two parameters aren't even close
4711       return false;
4712   }
4713 
4714   return true;
4715 }
4716 
4717 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4718 /// declarator needs to be rebuilt in the current instantiation.
4719 /// Any bits of declarator which appear before the name are valid for
4720 /// consideration here.  That's specifically the type in the decl spec
4721 /// and the base type in any member-pointer chunks.
4722 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4723                                                     DeclarationName Name) {
4724   // The types we specifically need to rebuild are:
4725   //   - typenames, typeofs, and decltypes
4726   //   - types which will become injected class names
4727   // Of course, we also need to rebuild any type referencing such a
4728   // type.  It's safest to just say "dependent", but we call out a
4729   // few cases here.
4730 
4731   DeclSpec &DS = D.getMutableDeclSpec();
4732   switch (DS.getTypeSpecType()) {
4733   case DeclSpec::TST_typename:
4734   case DeclSpec::TST_typeofType:
4735   case DeclSpec::TST_underlyingType:
4736   case DeclSpec::TST_atomic: {
4737     // Grab the type from the parser.
4738     TypeSourceInfo *TSI = nullptr;
4739     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4740     if (T.isNull() || !T->isDependentType()) break;
4741 
4742     // Make sure there's a type source info.  This isn't really much
4743     // of a waste; most dependent types should have type source info
4744     // attached already.
4745     if (!TSI)
4746       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4747 
4748     // Rebuild the type in the current instantiation.
4749     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4750     if (!TSI) return true;
4751 
4752     // Store the new type back in the decl spec.
4753     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4754     DS.UpdateTypeRep(LocType);
4755     break;
4756   }
4757 
4758   case DeclSpec::TST_decltype:
4759   case DeclSpec::TST_typeofExpr: {
4760     Expr *E = DS.getRepAsExpr();
4761     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4762     if (Result.isInvalid()) return true;
4763     DS.UpdateExprRep(Result.get());
4764     break;
4765   }
4766 
4767   default:
4768     // Nothing to do for these decl specs.
4769     break;
4770   }
4771 
4772   // It doesn't matter what order we do this in.
4773   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4774     DeclaratorChunk &Chunk = D.getTypeObject(I);
4775 
4776     // The only type information in the declarator which can come
4777     // before the declaration name is the base type of a member
4778     // pointer.
4779     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4780       continue;
4781 
4782     // Rebuild the scope specifier in-place.
4783     CXXScopeSpec &SS = Chunk.Mem.Scope();
4784     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4785       return true;
4786   }
4787 
4788   return false;
4789 }
4790 
4791 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4792   D.setFunctionDefinitionKind(FDK_Declaration);
4793   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4794 
4795   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4796       Dcl && Dcl->getDeclContext()->isFileContext())
4797     Dcl->setTopLevelDeclInObjCContainer();
4798 
4799   return Dcl;
4800 }
4801 
4802 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4803 ///   If T is the name of a class, then each of the following shall have a
4804 ///   name different from T:
4805 ///     - every static data member of class T;
4806 ///     - every member function of class T
4807 ///     - every member of class T that is itself a type;
4808 /// \returns true if the declaration name violates these rules.
4809 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4810                                    DeclarationNameInfo NameInfo) {
4811   DeclarationName Name = NameInfo.getName();
4812 
4813   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4814   while (Record && Record->isAnonymousStructOrUnion())
4815     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4816   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4817     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4818     return true;
4819   }
4820 
4821   return false;
4822 }
4823 
4824 /// \brief Diagnose a declaration whose declarator-id has the given
4825 /// nested-name-specifier.
4826 ///
4827 /// \param SS The nested-name-specifier of the declarator-id.
4828 ///
4829 /// \param DC The declaration context to which the nested-name-specifier
4830 /// resolves.
4831 ///
4832 /// \param Name The name of the entity being declared.
4833 ///
4834 /// \param Loc The location of the name of the entity being declared.
4835 ///
4836 /// \returns true if we cannot safely recover from this error, false otherwise.
4837 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4838                                         DeclarationName Name,
4839                                         SourceLocation Loc) {
4840   DeclContext *Cur = CurContext;
4841   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4842     Cur = Cur->getParent();
4843 
4844   // If the user provided a superfluous scope specifier that refers back to the
4845   // class in which the entity is already declared, diagnose and ignore it.
4846   //
4847   // class X {
4848   //   void X::f();
4849   // };
4850   //
4851   // Note, it was once ill-formed to give redundant qualification in all
4852   // contexts, but that rule was removed by DR482.
4853   if (Cur->Equals(DC)) {
4854     if (Cur->isRecord()) {
4855       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4856                                       : diag::err_member_extra_qualification)
4857         << Name << FixItHint::CreateRemoval(SS.getRange());
4858       SS.clear();
4859     } else {
4860       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4861     }
4862     return false;
4863   }
4864 
4865   // Check whether the qualifying scope encloses the scope of the original
4866   // declaration.
4867   if (!Cur->Encloses(DC)) {
4868     if (Cur->isRecord())
4869       Diag(Loc, diag::err_member_qualification)
4870         << Name << SS.getRange();
4871     else if (isa<TranslationUnitDecl>(DC))
4872       Diag(Loc, diag::err_invalid_declarator_global_scope)
4873         << Name << SS.getRange();
4874     else if (isa<FunctionDecl>(Cur))
4875       Diag(Loc, diag::err_invalid_declarator_in_function)
4876         << Name << SS.getRange();
4877     else if (isa<BlockDecl>(Cur))
4878       Diag(Loc, diag::err_invalid_declarator_in_block)
4879         << Name << SS.getRange();
4880     else
4881       Diag(Loc, diag::err_invalid_declarator_scope)
4882       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4883 
4884     return true;
4885   }
4886 
4887   if (Cur->isRecord()) {
4888     // Cannot qualify members within a class.
4889     Diag(Loc, diag::err_member_qualification)
4890       << Name << SS.getRange();
4891     SS.clear();
4892 
4893     // C++ constructors and destructors with incorrect scopes can break
4894     // our AST invariants by having the wrong underlying types. If
4895     // that's the case, then drop this declaration entirely.
4896     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4897          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4898         !Context.hasSameType(Name.getCXXNameType(),
4899                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4900       return true;
4901 
4902     return false;
4903   }
4904 
4905   // C++11 [dcl.meaning]p1:
4906   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4907   //   not begin with a decltype-specifer"
4908   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4909   while (SpecLoc.getPrefix())
4910     SpecLoc = SpecLoc.getPrefix();
4911   if (dyn_cast_or_null<DecltypeType>(
4912         SpecLoc.getNestedNameSpecifier()->getAsType()))
4913     Diag(Loc, diag::err_decltype_in_declarator)
4914       << SpecLoc.getTypeLoc().getSourceRange();
4915 
4916   return false;
4917 }
4918 
4919 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4920                                   MultiTemplateParamsArg TemplateParamLists) {
4921   // TODO: consider using NameInfo for diagnostic.
4922   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4923   DeclarationName Name = NameInfo.getName();
4924 
4925   // All of these full declarators require an identifier.  If it doesn't have
4926   // one, the ParsedFreeStandingDeclSpec action should be used.
4927   if (!Name) {
4928     if (!D.isInvalidType())  // Reject this if we think it is valid.
4929       Diag(D.getDeclSpec().getLocStart(),
4930            diag::err_declarator_need_ident)
4931         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4932     return nullptr;
4933   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4934     return nullptr;
4935 
4936   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4937   // we find one that is.
4938   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4939          (S->getFlags() & Scope::TemplateParamScope) != 0)
4940     S = S->getParent();
4941 
4942   DeclContext *DC = CurContext;
4943   if (D.getCXXScopeSpec().isInvalid())
4944     D.setInvalidType();
4945   else if (D.getCXXScopeSpec().isSet()) {
4946     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4947                                         UPPC_DeclarationQualifier))
4948       return nullptr;
4949 
4950     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4951     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4952     if (!DC || isa<EnumDecl>(DC)) {
4953       // If we could not compute the declaration context, it's because the
4954       // declaration context is dependent but does not refer to a class,
4955       // class template, or class template partial specialization. Complain
4956       // and return early, to avoid the coming semantic disaster.
4957       Diag(D.getIdentifierLoc(),
4958            diag::err_template_qualified_declarator_no_match)
4959         << D.getCXXScopeSpec().getScopeRep()
4960         << D.getCXXScopeSpec().getRange();
4961       return nullptr;
4962     }
4963     bool IsDependentContext = DC->isDependentContext();
4964 
4965     if (!IsDependentContext &&
4966         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4967       return nullptr;
4968 
4969     // If a class is incomplete, do not parse entities inside it.
4970     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4971       Diag(D.getIdentifierLoc(),
4972            diag::err_member_def_undefined_record)
4973         << Name << DC << D.getCXXScopeSpec().getRange();
4974       return nullptr;
4975     }
4976     if (!D.getDeclSpec().isFriendSpecified()) {
4977       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4978                                       Name, D.getIdentifierLoc())) {
4979         if (DC->isRecord())
4980           return nullptr;
4981 
4982         D.setInvalidType();
4983       }
4984     }
4985 
4986     // Check whether we need to rebuild the type of the given
4987     // declaration in the current instantiation.
4988     if (EnteringContext && IsDependentContext &&
4989         TemplateParamLists.size() != 0) {
4990       ContextRAII SavedContext(*this, DC);
4991       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4992         D.setInvalidType();
4993     }
4994   }
4995 
4996   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4997   QualType R = TInfo->getType();
4998 
4999   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5000     // If this is a typedef, we'll end up spewing multiple diagnostics.
5001     // Just return early; it's safer. If this is a function, let the
5002     // "constructor cannot have a return type" diagnostic handle it.
5003     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5004       return nullptr;
5005 
5006   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5007                                       UPPC_DeclarationType))
5008     D.setInvalidType();
5009 
5010   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5011                         ForRedeclaration);
5012 
5013   // See if this is a redefinition of a variable in the same scope.
5014   if (!D.getCXXScopeSpec().isSet()) {
5015     bool IsLinkageLookup = false;
5016     bool CreateBuiltins = false;
5017 
5018     // If the declaration we're planning to build will be a function
5019     // or object with linkage, then look for another declaration with
5020     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5021     //
5022     // If the declaration we're planning to build will be declared with
5023     // external linkage in the translation unit, create any builtin with
5024     // the same name.
5025     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5026       /* Do nothing*/;
5027     else if (CurContext->isFunctionOrMethod() &&
5028              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5029               R->isFunctionType())) {
5030       IsLinkageLookup = true;
5031       CreateBuiltins =
5032           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5033     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5034                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5035       CreateBuiltins = true;
5036 
5037     if (IsLinkageLookup)
5038       Previous.clear(LookupRedeclarationWithLinkage);
5039 
5040     LookupName(Previous, S, CreateBuiltins);
5041   } else { // Something like "int foo::x;"
5042     LookupQualifiedName(Previous, DC);
5043 
5044     // C++ [dcl.meaning]p1:
5045     //   When the declarator-id is qualified, the declaration shall refer to a
5046     //  previously declared member of the class or namespace to which the
5047     //  qualifier refers (or, in the case of a namespace, of an element of the
5048     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5049     //  thereof; [...]
5050     //
5051     // Note that we already checked the context above, and that we do not have
5052     // enough information to make sure that Previous contains the declaration
5053     // we want to match. For example, given:
5054     //
5055     //   class X {
5056     //     void f();
5057     //     void f(float);
5058     //   };
5059     //
5060     //   void X::f(int) { } // ill-formed
5061     //
5062     // In this case, Previous will point to the overload set
5063     // containing the two f's declared in X, but neither of them
5064     // matches.
5065 
5066     // C++ [dcl.meaning]p1:
5067     //   [...] the member shall not merely have been introduced by a
5068     //   using-declaration in the scope of the class or namespace nominated by
5069     //   the nested-name-specifier of the declarator-id.
5070     RemoveUsingDecls(Previous);
5071   }
5072 
5073   if (Previous.isSingleResult() &&
5074       Previous.getFoundDecl()->isTemplateParameter()) {
5075     // Maybe we will complain about the shadowed template parameter.
5076     if (!D.isInvalidType())
5077       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5078                                       Previous.getFoundDecl());
5079 
5080     // Just pretend that we didn't see the previous declaration.
5081     Previous.clear();
5082   }
5083 
5084   // In C++, the previous declaration we find might be a tag type
5085   // (class or enum). In this case, the new declaration will hide the
5086   // tag type. Note that this does does not apply if we're declaring a
5087   // typedef (C++ [dcl.typedef]p4).
5088   if (Previous.isSingleTagDecl() &&
5089       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5090     Previous.clear();
5091 
5092   // Check that there are no default arguments other than in the parameters
5093   // of a function declaration (C++ only).
5094   if (getLangOpts().CPlusPlus)
5095     CheckExtraCXXDefaultArguments(D);
5096 
5097   if (D.getDeclSpec().isConceptSpecified()) {
5098     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5099     // applied only to the definition of a function template or variable
5100     // template, declared in namespace scope
5101     if (!TemplateParamLists.size()) {
5102       Diag(D.getDeclSpec().getConceptSpecLoc(),
5103            diag:: err_concept_wrong_decl_kind);
5104       return nullptr;
5105     }
5106 
5107     if (!DC->getRedeclContext()->isFileContext()) {
5108       Diag(D.getIdentifierLoc(),
5109            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5110       return nullptr;
5111     }
5112   }
5113 
5114   NamedDecl *New;
5115 
5116   bool AddToScope = true;
5117   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5118     if (TemplateParamLists.size()) {
5119       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5120       return nullptr;
5121     }
5122 
5123     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5124   } else if (R->isFunctionType()) {
5125     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5126                                   TemplateParamLists,
5127                                   AddToScope);
5128   } else {
5129     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5130                                   AddToScope);
5131   }
5132 
5133   if (!New)
5134     return nullptr;
5135 
5136   // If this has an identifier and is not a function template specialization,
5137   // add it to the scope stack.
5138   if (New->getDeclName() && AddToScope) {
5139     // Only make a locally-scoped extern declaration visible if it is the first
5140     // declaration of this entity. Qualified lookup for such an entity should
5141     // only find this declaration if there is no visible declaration of it.
5142     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5143     PushOnScopeChains(New, S, AddToContext);
5144     if (!AddToContext)
5145       CurContext->addHiddenDecl(New);
5146   }
5147 
5148   if (isInOpenMPDeclareTargetContext())
5149     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5150 
5151   return New;
5152 }
5153 
5154 /// Helper method to turn variable array types into constant array
5155 /// types in certain situations which would otherwise be errors (for
5156 /// GCC compatibility).
5157 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5158                                                     ASTContext &Context,
5159                                                     bool &SizeIsNegative,
5160                                                     llvm::APSInt &Oversized) {
5161   // This method tries to turn a variable array into a constant
5162   // array even when the size isn't an ICE.  This is necessary
5163   // for compatibility with code that depends on gcc's buggy
5164   // constant expression folding, like struct {char x[(int)(char*)2];}
5165   SizeIsNegative = false;
5166   Oversized = 0;
5167 
5168   if (T->isDependentType())
5169     return QualType();
5170 
5171   QualifierCollector Qs;
5172   const Type *Ty = Qs.strip(T);
5173 
5174   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5175     QualType Pointee = PTy->getPointeeType();
5176     QualType FixedType =
5177         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5178                                             Oversized);
5179     if (FixedType.isNull()) return FixedType;
5180     FixedType = Context.getPointerType(FixedType);
5181     return Qs.apply(Context, FixedType);
5182   }
5183   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5184     QualType Inner = PTy->getInnerType();
5185     QualType FixedType =
5186         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5187                                             Oversized);
5188     if (FixedType.isNull()) return FixedType;
5189     FixedType = Context.getParenType(FixedType);
5190     return Qs.apply(Context, FixedType);
5191   }
5192 
5193   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5194   if (!VLATy)
5195     return QualType();
5196   // FIXME: We should probably handle this case
5197   if (VLATy->getElementType()->isVariablyModifiedType())
5198     return QualType();
5199 
5200   llvm::APSInt Res;
5201   if (!VLATy->getSizeExpr() ||
5202       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5203     return QualType();
5204 
5205   // Check whether the array size is negative.
5206   if (Res.isSigned() && Res.isNegative()) {
5207     SizeIsNegative = true;
5208     return QualType();
5209   }
5210 
5211   // Check whether the array is too large to be addressed.
5212   unsigned ActiveSizeBits
5213     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5214                                               Res);
5215   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5216     Oversized = Res;
5217     return QualType();
5218   }
5219 
5220   return Context.getConstantArrayType(VLATy->getElementType(),
5221                                       Res, ArrayType::Normal, 0);
5222 }
5223 
5224 static void
5225 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5226   SrcTL = SrcTL.getUnqualifiedLoc();
5227   DstTL = DstTL.getUnqualifiedLoc();
5228   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5229     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5230     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5231                                       DstPTL.getPointeeLoc());
5232     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5233     return;
5234   }
5235   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5236     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5237     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5238                                       DstPTL.getInnerLoc());
5239     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5240     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5241     return;
5242   }
5243   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5244   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5245   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5246   TypeLoc DstElemTL = DstATL.getElementLoc();
5247   DstElemTL.initializeFullCopy(SrcElemTL);
5248   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5249   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5250   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5251 }
5252 
5253 /// Helper method to turn variable array types into constant array
5254 /// types in certain situations which would otherwise be errors (for
5255 /// GCC compatibility).
5256 static TypeSourceInfo*
5257 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5258                                               ASTContext &Context,
5259                                               bool &SizeIsNegative,
5260                                               llvm::APSInt &Oversized) {
5261   QualType FixedTy
5262     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5263                                           SizeIsNegative, Oversized);
5264   if (FixedTy.isNull())
5265     return nullptr;
5266   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5267   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5268                                     FixedTInfo->getTypeLoc());
5269   return FixedTInfo;
5270 }
5271 
5272 /// \brief Register the given locally-scoped extern "C" declaration so
5273 /// that it can be found later for redeclarations. We include any extern "C"
5274 /// declaration that is not visible in the translation unit here, not just
5275 /// function-scope declarations.
5276 void
5277 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5278   if (!getLangOpts().CPlusPlus &&
5279       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5280     // Don't need to track declarations in the TU in C.
5281     return;
5282 
5283   // Note that we have a locally-scoped external with this name.
5284   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5285 }
5286 
5287 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5288   // FIXME: We can have multiple results via __attribute__((overloadable)).
5289   auto Result = Context.getExternCContextDecl()->lookup(Name);
5290   return Result.empty() ? nullptr : *Result.begin();
5291 }
5292 
5293 /// \brief Diagnose function specifiers on a declaration of an identifier that
5294 /// does not identify a function.
5295 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5296   // FIXME: We should probably indicate the identifier in question to avoid
5297   // confusion for constructs like "virtual int a(), b;"
5298   if (DS.isVirtualSpecified())
5299     Diag(DS.getVirtualSpecLoc(),
5300          diag::err_virtual_non_function);
5301 
5302   if (DS.isExplicitSpecified())
5303     Diag(DS.getExplicitSpecLoc(),
5304          diag::err_explicit_non_function);
5305 
5306   if (DS.isNoreturnSpecified())
5307     Diag(DS.getNoreturnSpecLoc(),
5308          diag::err_noreturn_non_function);
5309 }
5310 
5311 NamedDecl*
5312 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5313                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5314   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5315   if (D.getCXXScopeSpec().isSet()) {
5316     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5317       << D.getCXXScopeSpec().getRange();
5318     D.setInvalidType();
5319     // Pretend we didn't see the scope specifier.
5320     DC = CurContext;
5321     Previous.clear();
5322   }
5323 
5324   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5325 
5326   if (D.getDeclSpec().isInlineSpecified())
5327     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5328         << getLangOpts().CPlusPlus1z;
5329   if (D.getDeclSpec().isConstexprSpecified())
5330     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5331       << 1;
5332   if (D.getDeclSpec().isConceptSpecified())
5333     Diag(D.getDeclSpec().getConceptSpecLoc(),
5334          diag::err_concept_wrong_decl_kind);
5335 
5336   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5337     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5338       << D.getName().getSourceRange();
5339     return nullptr;
5340   }
5341 
5342   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5343   if (!NewTD) return nullptr;
5344 
5345   // Handle attributes prior to checking for duplicates in MergeVarDecl
5346   ProcessDeclAttributes(S, NewTD, D);
5347 
5348   CheckTypedefForVariablyModifiedType(S, NewTD);
5349 
5350   bool Redeclaration = D.isRedeclaration();
5351   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5352   D.setRedeclaration(Redeclaration);
5353   return ND;
5354 }
5355 
5356 void
5357 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5358   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5359   // then it shall have block scope.
5360   // Note that variably modified types must be fixed before merging the decl so
5361   // that redeclarations will match.
5362   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5363   QualType T = TInfo->getType();
5364   if (T->isVariablyModifiedType()) {
5365     getCurFunction()->setHasBranchProtectedScope();
5366 
5367     if (S->getFnParent() == nullptr) {
5368       bool SizeIsNegative;
5369       llvm::APSInt Oversized;
5370       TypeSourceInfo *FixedTInfo =
5371         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5372                                                       SizeIsNegative,
5373                                                       Oversized);
5374       if (FixedTInfo) {
5375         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5376         NewTD->setTypeSourceInfo(FixedTInfo);
5377       } else {
5378         if (SizeIsNegative)
5379           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5380         else if (T->isVariableArrayType())
5381           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5382         else if (Oversized.getBoolValue())
5383           Diag(NewTD->getLocation(), diag::err_array_too_large)
5384             << Oversized.toString(10);
5385         else
5386           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5387         NewTD->setInvalidDecl();
5388       }
5389     }
5390   }
5391 }
5392 
5393 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5394 /// declares a typedef-name, either using the 'typedef' type specifier or via
5395 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5396 NamedDecl*
5397 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5398                            LookupResult &Previous, bool &Redeclaration) {
5399   // Merge the decl with the existing one if appropriate. If the decl is
5400   // in an outer scope, it isn't the same thing.
5401   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5402                        /*AllowInlineNamespace*/false);
5403   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5404   if (!Previous.empty()) {
5405     Redeclaration = true;
5406     MergeTypedefNameDecl(S, NewTD, Previous);
5407   }
5408 
5409   // If this is the C FILE type, notify the AST context.
5410   if (IdentifierInfo *II = NewTD->getIdentifier())
5411     if (!NewTD->isInvalidDecl() &&
5412         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5413       if (II->isStr("FILE"))
5414         Context.setFILEDecl(NewTD);
5415       else if (II->isStr("jmp_buf"))
5416         Context.setjmp_bufDecl(NewTD);
5417       else if (II->isStr("sigjmp_buf"))
5418         Context.setsigjmp_bufDecl(NewTD);
5419       else if (II->isStr("ucontext_t"))
5420         Context.setucontext_tDecl(NewTD);
5421     }
5422 
5423   return NewTD;
5424 }
5425 
5426 /// \brief Determines whether the given declaration is an out-of-scope
5427 /// previous declaration.
5428 ///
5429 /// This routine should be invoked when name lookup has found a
5430 /// previous declaration (PrevDecl) that is not in the scope where a
5431 /// new declaration by the same name is being introduced. If the new
5432 /// declaration occurs in a local scope, previous declarations with
5433 /// linkage may still be considered previous declarations (C99
5434 /// 6.2.2p4-5, C++ [basic.link]p6).
5435 ///
5436 /// \param PrevDecl the previous declaration found by name
5437 /// lookup
5438 ///
5439 /// \param DC the context in which the new declaration is being
5440 /// declared.
5441 ///
5442 /// \returns true if PrevDecl is an out-of-scope previous declaration
5443 /// for a new delcaration with the same name.
5444 static bool
5445 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5446                                 ASTContext &Context) {
5447   if (!PrevDecl)
5448     return false;
5449 
5450   if (!PrevDecl->hasLinkage())
5451     return false;
5452 
5453   if (Context.getLangOpts().CPlusPlus) {
5454     // C++ [basic.link]p6:
5455     //   If there is a visible declaration of an entity with linkage
5456     //   having the same name and type, ignoring entities declared
5457     //   outside the innermost enclosing namespace scope, the block
5458     //   scope declaration declares that same entity and receives the
5459     //   linkage of the previous declaration.
5460     DeclContext *OuterContext = DC->getRedeclContext();
5461     if (!OuterContext->isFunctionOrMethod())
5462       // This rule only applies to block-scope declarations.
5463       return false;
5464 
5465     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5466     if (PrevOuterContext->isRecord())
5467       // We found a member function: ignore it.
5468       return false;
5469 
5470     // Find the innermost enclosing namespace for the new and
5471     // previous declarations.
5472     OuterContext = OuterContext->getEnclosingNamespaceContext();
5473     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5474 
5475     // The previous declaration is in a different namespace, so it
5476     // isn't the same function.
5477     if (!OuterContext->Equals(PrevOuterContext))
5478       return false;
5479   }
5480 
5481   return true;
5482 }
5483 
5484 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5485   CXXScopeSpec &SS = D.getCXXScopeSpec();
5486   if (!SS.isSet()) return;
5487   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5488 }
5489 
5490 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5491   QualType type = decl->getType();
5492   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5493   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5494     // Various kinds of declaration aren't allowed to be __autoreleasing.
5495     unsigned kind = -1U;
5496     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5497       if (var->hasAttr<BlocksAttr>())
5498         kind = 0; // __block
5499       else if (!var->hasLocalStorage())
5500         kind = 1; // global
5501     } else if (isa<ObjCIvarDecl>(decl)) {
5502       kind = 3; // ivar
5503     } else if (isa<FieldDecl>(decl)) {
5504       kind = 2; // field
5505     }
5506 
5507     if (kind != -1U) {
5508       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5509         << kind;
5510     }
5511   } else if (lifetime == Qualifiers::OCL_None) {
5512     // Try to infer lifetime.
5513     if (!type->isObjCLifetimeType())
5514       return false;
5515 
5516     lifetime = type->getObjCARCImplicitLifetime();
5517     type = Context.getLifetimeQualifiedType(type, lifetime);
5518     decl->setType(type);
5519   }
5520 
5521   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5522     // Thread-local variables cannot have lifetime.
5523     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5524         var->getTLSKind()) {
5525       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5526         << var->getType();
5527       return true;
5528     }
5529   }
5530 
5531   return false;
5532 }
5533 
5534 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5535   // Ensure that an auto decl is deduced otherwise the checks below might cache
5536   // the wrong linkage.
5537   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5538 
5539   // 'weak' only applies to declarations with external linkage.
5540   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5541     if (!ND.isExternallyVisible()) {
5542       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5543       ND.dropAttr<WeakAttr>();
5544     }
5545   }
5546   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5547     if (ND.isExternallyVisible()) {
5548       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5549       ND.dropAttr<WeakRefAttr>();
5550       ND.dropAttr<AliasAttr>();
5551     }
5552   }
5553 
5554   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5555     if (VD->hasInit()) {
5556       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5557         assert(VD->isThisDeclarationADefinition() &&
5558                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5559         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5560         VD->dropAttr<AliasAttr>();
5561       }
5562     }
5563   }
5564 
5565   // 'selectany' only applies to externally visible variable declarations.
5566   // It does not apply to functions.
5567   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5568     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5569       S.Diag(Attr->getLocation(),
5570              diag::err_attribute_selectany_non_extern_data);
5571       ND.dropAttr<SelectAnyAttr>();
5572     }
5573   }
5574 
5575   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5576     // dll attributes require external linkage. Static locals may have external
5577     // linkage but still cannot be explicitly imported or exported.
5578     auto *VD = dyn_cast<VarDecl>(&ND);
5579     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5580       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5581         << &ND << Attr;
5582       ND.setInvalidDecl();
5583     }
5584   }
5585 
5586   // Virtual functions cannot be marked as 'notail'.
5587   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5588     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5589       if (MD->isVirtual()) {
5590         S.Diag(ND.getLocation(),
5591                diag::err_invalid_attribute_on_virtual_function)
5592             << Attr;
5593         ND.dropAttr<NotTailCalledAttr>();
5594       }
5595 }
5596 
5597 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5598                                            NamedDecl *NewDecl,
5599                                            bool IsSpecialization,
5600                                            bool IsDefinition) {
5601   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5602     OldDecl = OldTD->getTemplatedDecl();
5603     if (!IsSpecialization)
5604       IsDefinition = false;
5605   }
5606   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5607     NewDecl = NewTD->getTemplatedDecl();
5608 
5609   if (!OldDecl || !NewDecl)
5610     return;
5611 
5612   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5613   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5614   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5615   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5616 
5617   // dllimport and dllexport are inheritable attributes so we have to exclude
5618   // inherited attribute instances.
5619   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5620                     (NewExportAttr && !NewExportAttr->isInherited());
5621 
5622   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5623   // the only exception being explicit specializations.
5624   // Implicitly generated declarations are also excluded for now because there
5625   // is no other way to switch these to use dllimport or dllexport.
5626   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5627 
5628   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5629     // Allow with a warning for free functions and global variables.
5630     bool JustWarn = false;
5631     if (!OldDecl->isCXXClassMember()) {
5632       auto *VD = dyn_cast<VarDecl>(OldDecl);
5633       if (VD && !VD->getDescribedVarTemplate())
5634         JustWarn = true;
5635       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5636       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5637         JustWarn = true;
5638     }
5639 
5640     // We cannot change a declaration that's been used because IR has already
5641     // been emitted. Dllimported functions will still work though (modulo
5642     // address equality) as they can use the thunk.
5643     if (OldDecl->isUsed())
5644       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5645         JustWarn = false;
5646 
5647     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5648                                : diag::err_attribute_dll_redeclaration;
5649     S.Diag(NewDecl->getLocation(), DiagID)
5650         << NewDecl
5651         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5652     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5653     if (!JustWarn) {
5654       NewDecl->setInvalidDecl();
5655       return;
5656     }
5657   }
5658 
5659   // A redeclaration is not allowed to drop a dllimport attribute, the only
5660   // exceptions being inline function definitions, local extern declarations,
5661   // qualified friend declarations or special MSVC extension: in the last case,
5662   // the declaration is treated as if it were marked dllexport.
5663   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5664   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5665   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5666     // Ignore static data because out-of-line definitions are diagnosed
5667     // separately.
5668     IsStaticDataMember = VD->isStaticDataMember();
5669     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5670                    VarDecl::DeclarationOnly;
5671   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5672     IsInline = FD->isInlined();
5673     IsQualifiedFriend = FD->getQualifier() &&
5674                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5675   }
5676 
5677   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5678       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5679     if (IsMicrosoft && IsDefinition) {
5680       S.Diag(NewDecl->getLocation(),
5681              diag::warn_redeclaration_without_import_attribute)
5682           << NewDecl;
5683       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5684       NewDecl->dropAttr<DLLImportAttr>();
5685       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5686           NewImportAttr->getRange(), S.Context,
5687           NewImportAttr->getSpellingListIndex()));
5688     } else {
5689       S.Diag(NewDecl->getLocation(),
5690              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5691           << NewDecl << OldImportAttr;
5692       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5693       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5694       OldDecl->dropAttr<DLLImportAttr>();
5695       NewDecl->dropAttr<DLLImportAttr>();
5696     }
5697   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5698     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5699     OldDecl->dropAttr<DLLImportAttr>();
5700     NewDecl->dropAttr<DLLImportAttr>();
5701     S.Diag(NewDecl->getLocation(),
5702            diag::warn_dllimport_dropped_from_inline_function)
5703         << NewDecl << OldImportAttr;
5704   }
5705 }
5706 
5707 /// Given that we are within the definition of the given function,
5708 /// will that definition behave like C99's 'inline', where the
5709 /// definition is discarded except for optimization purposes?
5710 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5711   // Try to avoid calling GetGVALinkageForFunction.
5712 
5713   // All cases of this require the 'inline' keyword.
5714   if (!FD->isInlined()) return false;
5715 
5716   // This is only possible in C++ with the gnu_inline attribute.
5717   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5718     return false;
5719 
5720   // Okay, go ahead and call the relatively-more-expensive function.
5721 
5722 #ifndef NDEBUG
5723   // AST quite reasonably asserts that it's working on a function
5724   // definition.  We don't really have a way to tell it that we're
5725   // currently defining the function, so just lie to it in +Asserts
5726   // builds.  This is an awful hack.
5727   FD->setLazyBody(1);
5728 #endif
5729 
5730   bool isC99Inline =
5731       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5732 
5733 #ifndef NDEBUG
5734   FD->setLazyBody(0);
5735 #endif
5736 
5737   return isC99Inline;
5738 }
5739 
5740 /// Determine whether a variable is extern "C" prior to attaching
5741 /// an initializer. We can't just call isExternC() here, because that
5742 /// will also compute and cache whether the declaration is externally
5743 /// visible, which might change when we attach the initializer.
5744 ///
5745 /// This can only be used if the declaration is known to not be a
5746 /// redeclaration of an internal linkage declaration.
5747 ///
5748 /// For instance:
5749 ///
5750 ///   auto x = []{};
5751 ///
5752 /// Attaching the initializer here makes this declaration not externally
5753 /// visible, because its type has internal linkage.
5754 ///
5755 /// FIXME: This is a hack.
5756 template<typename T>
5757 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5758   if (S.getLangOpts().CPlusPlus) {
5759     // In C++, the overloadable attribute negates the effects of extern "C".
5760     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5761       return false;
5762 
5763     // So do CUDA's host/device attributes.
5764     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5765                                  D->template hasAttr<CUDAHostAttr>()))
5766       return false;
5767   }
5768   return D->isExternC();
5769 }
5770 
5771 static bool shouldConsiderLinkage(const VarDecl *VD) {
5772   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5773   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5774     return VD->hasExternalStorage();
5775   if (DC->isFileContext())
5776     return true;
5777   if (DC->isRecord())
5778     return false;
5779   llvm_unreachable("Unexpected context");
5780 }
5781 
5782 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5783   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5784   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5785       isa<OMPDeclareReductionDecl>(DC))
5786     return true;
5787   if (DC->isRecord())
5788     return false;
5789   llvm_unreachable("Unexpected context");
5790 }
5791 
5792 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5793                           AttributeList::Kind Kind) {
5794   for (const AttributeList *L = AttrList; L; L = L->getNext())
5795     if (L->getKind() == Kind)
5796       return true;
5797   return false;
5798 }
5799 
5800 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5801                           AttributeList::Kind Kind) {
5802   // Check decl attributes on the DeclSpec.
5803   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5804     return true;
5805 
5806   // Walk the declarator structure, checking decl attributes that were in a type
5807   // position to the decl itself.
5808   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5809     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5810       return true;
5811   }
5812 
5813   // Finally, check attributes on the decl itself.
5814   return hasParsedAttr(S, PD.getAttributes(), Kind);
5815 }
5816 
5817 /// Adjust the \c DeclContext for a function or variable that might be a
5818 /// function-local external declaration.
5819 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5820   if (!DC->isFunctionOrMethod())
5821     return false;
5822 
5823   // If this is a local extern function or variable declared within a function
5824   // template, don't add it into the enclosing namespace scope until it is
5825   // instantiated; it might have a dependent type right now.
5826   if (DC->isDependentContext())
5827     return true;
5828 
5829   // C++11 [basic.link]p7:
5830   //   When a block scope declaration of an entity with linkage is not found to
5831   //   refer to some other declaration, then that entity is a member of the
5832   //   innermost enclosing namespace.
5833   //
5834   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5835   // semantically-enclosing namespace, not a lexically-enclosing one.
5836   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5837     DC = DC->getParent();
5838   return true;
5839 }
5840 
5841 /// \brief Returns true if given declaration has external C language linkage.
5842 static bool isDeclExternC(const Decl *D) {
5843   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5844     return FD->isExternC();
5845   if (const auto *VD = dyn_cast<VarDecl>(D))
5846     return VD->isExternC();
5847 
5848   llvm_unreachable("Unknown type of decl!");
5849 }
5850 
5851 NamedDecl *
5852 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5853                               TypeSourceInfo *TInfo, LookupResult &Previous,
5854                               MultiTemplateParamsArg TemplateParamLists,
5855                               bool &AddToScope) {
5856   QualType R = TInfo->getType();
5857   DeclarationName Name = GetNameForDeclarator(D).getName();
5858 
5859   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5860   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5861   // argument.
5862   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5863     Diag(D.getIdentifierLoc(),
5864          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5865         << R;
5866     D.setInvalidType();
5867     return nullptr;
5868   }
5869 
5870   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5871   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5872 
5873   // dllimport globals without explicit storage class are treated as extern. We
5874   // have to change the storage class this early to get the right DeclContext.
5875   if (SC == SC_None && !DC->isRecord() &&
5876       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5877       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5878     SC = SC_Extern;
5879 
5880   DeclContext *OriginalDC = DC;
5881   bool IsLocalExternDecl = SC == SC_Extern &&
5882                            adjustContextForLocalExternDecl(DC);
5883 
5884   if (getLangOpts().OpenCL) {
5885     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5886     QualType NR = R;
5887     while (NR->isPointerType()) {
5888       if (NR->isFunctionPointerType()) {
5889         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5890         D.setInvalidType();
5891         break;
5892       }
5893       NR = NR->getPointeeType();
5894     }
5895 
5896     if (!getOpenCLOptions().cl_khr_fp16) {
5897       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5898       // half array type (unless the cl_khr_fp16 extension is enabled).
5899       if (Context.getBaseElementType(R)->isHalfType()) {
5900         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5901         D.setInvalidType();
5902       }
5903     }
5904   }
5905 
5906   if (SCSpec == DeclSpec::SCS_mutable) {
5907     // mutable can only appear on non-static class members, so it's always
5908     // an error here
5909     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5910     D.setInvalidType();
5911     SC = SC_None;
5912   }
5913 
5914   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5915       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5916                               D.getDeclSpec().getStorageClassSpecLoc())) {
5917     // In C++11, the 'register' storage class specifier is deprecated.
5918     // Suppress the warning in system macros, it's used in macros in some
5919     // popular C system headers, such as in glibc's htonl() macro.
5920     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5921          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5922                                    : diag::warn_deprecated_register)
5923       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5924   }
5925 
5926   IdentifierInfo *II = Name.getAsIdentifierInfo();
5927   if (!II) {
5928     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5929       << Name;
5930     return nullptr;
5931   }
5932 
5933   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5934 
5935   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5936     // C99 6.9p2: The storage-class specifiers auto and register shall not
5937     // appear in the declaration specifiers in an external declaration.
5938     // Global Register+Asm is a GNU extension we support.
5939     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5940       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5941       D.setInvalidType();
5942     }
5943   }
5944 
5945   if (getLangOpts().OpenCL) {
5946     // OpenCL v1.2 s6.9.b p4:
5947     // The sampler type cannot be used with the __local and __global address
5948     // space qualifiers.
5949     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5950       R.getAddressSpace() == LangAS::opencl_global)) {
5951       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5952     }
5953 
5954     // OpenCL 1.2 spec, p6.9 r:
5955     // The event type cannot be used to declare a program scope variable.
5956     // The event type cannot be used with the __local, __constant and __global
5957     // address space qualifiers.
5958     if (R->isEventT()) {
5959       if (S->getParent() == nullptr) {
5960         Diag(D.getLocStart(), diag::err_event_t_global_var);
5961         D.setInvalidType();
5962       }
5963 
5964       if (R.getAddressSpace()) {
5965         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5966         D.setInvalidType();
5967       }
5968     }
5969   }
5970 
5971   bool IsExplicitSpecialization = false;
5972   bool IsVariableTemplateSpecialization = false;
5973   bool IsPartialSpecialization = false;
5974   bool IsVariableTemplate = false;
5975   VarDecl *NewVD = nullptr;
5976   VarTemplateDecl *NewTemplate = nullptr;
5977   TemplateParameterList *TemplateParams = nullptr;
5978   if (!getLangOpts().CPlusPlus) {
5979     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5980                             D.getIdentifierLoc(), II,
5981                             R, TInfo, SC);
5982 
5983     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5984       ParsingInitForAutoVars.insert(NewVD);
5985 
5986     if (D.isInvalidType())
5987       NewVD->setInvalidDecl();
5988   } else {
5989     bool Invalid = false;
5990 
5991     if (DC->isRecord() && !CurContext->isRecord()) {
5992       // This is an out-of-line definition of a static data member.
5993       switch (SC) {
5994       case SC_None:
5995         break;
5996       case SC_Static:
5997         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5998              diag::err_static_out_of_line)
5999           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6000         break;
6001       case SC_Auto:
6002       case SC_Register:
6003       case SC_Extern:
6004         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6005         // to names of variables declared in a block or to function parameters.
6006         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6007         // of class members
6008 
6009         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6010              diag::err_storage_class_for_static_member)
6011           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6012         break;
6013       case SC_PrivateExtern:
6014         llvm_unreachable("C storage class in c++!");
6015       }
6016     }
6017 
6018     if (SC == SC_Static && CurContext->isRecord()) {
6019       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6020         if (RD->isLocalClass())
6021           Diag(D.getIdentifierLoc(),
6022                diag::err_static_data_member_not_allowed_in_local_class)
6023             << Name << RD->getDeclName();
6024 
6025         // C++98 [class.union]p1: If a union contains a static data member,
6026         // the program is ill-formed. C++11 drops this restriction.
6027         if (RD->isUnion())
6028           Diag(D.getIdentifierLoc(),
6029                getLangOpts().CPlusPlus11
6030                  ? diag::warn_cxx98_compat_static_data_member_in_union
6031                  : diag::ext_static_data_member_in_union) << Name;
6032         // We conservatively disallow static data members in anonymous structs.
6033         else if (!RD->getDeclName())
6034           Diag(D.getIdentifierLoc(),
6035                diag::err_static_data_member_not_allowed_in_anon_struct)
6036             << Name << RD->isUnion();
6037       }
6038     }
6039 
6040     // Match up the template parameter lists with the scope specifier, then
6041     // determine whether we have a template or a template specialization.
6042     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6043         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6044         D.getCXXScopeSpec(),
6045         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6046             ? D.getName().TemplateId
6047             : nullptr,
6048         TemplateParamLists,
6049         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6050 
6051     if (TemplateParams) {
6052       if (!TemplateParams->size() &&
6053           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6054         // There is an extraneous 'template<>' for this variable. Complain
6055         // about it, but allow the declaration of the variable.
6056         Diag(TemplateParams->getTemplateLoc(),
6057              diag::err_template_variable_noparams)
6058           << II
6059           << SourceRange(TemplateParams->getTemplateLoc(),
6060                          TemplateParams->getRAngleLoc());
6061         TemplateParams = nullptr;
6062       } else {
6063         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6064           // This is an explicit specialization or a partial specialization.
6065           // FIXME: Check that we can declare a specialization here.
6066           IsVariableTemplateSpecialization = true;
6067           IsPartialSpecialization = TemplateParams->size() > 0;
6068         } else { // if (TemplateParams->size() > 0)
6069           // This is a template declaration.
6070           IsVariableTemplate = true;
6071 
6072           // Check that we can declare a template here.
6073           if (CheckTemplateDeclScope(S, TemplateParams))
6074             return nullptr;
6075 
6076           // Only C++1y supports variable templates (N3651).
6077           Diag(D.getIdentifierLoc(),
6078                getLangOpts().CPlusPlus14
6079                    ? diag::warn_cxx11_compat_variable_template
6080                    : diag::ext_variable_template);
6081         }
6082       }
6083     } else {
6084       assert(
6085           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6086           "should have a 'template<>' for this decl");
6087     }
6088 
6089     if (IsVariableTemplateSpecialization) {
6090       SourceLocation TemplateKWLoc =
6091           TemplateParamLists.size() > 0
6092               ? TemplateParamLists[0]->getTemplateLoc()
6093               : SourceLocation();
6094       DeclResult Res = ActOnVarTemplateSpecialization(
6095           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6096           IsPartialSpecialization);
6097       if (Res.isInvalid())
6098         return nullptr;
6099       NewVD = cast<VarDecl>(Res.get());
6100       AddToScope = false;
6101     } else
6102       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6103                               D.getIdentifierLoc(), II, R, TInfo, SC);
6104 
6105     // If this is supposed to be a variable template, create it as such.
6106     if (IsVariableTemplate) {
6107       NewTemplate =
6108           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6109                                   TemplateParams, NewVD);
6110       NewVD->setDescribedVarTemplate(NewTemplate);
6111     }
6112 
6113     // If this decl has an auto type in need of deduction, make a note of the
6114     // Decl so we can diagnose uses of it in its own initializer.
6115     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6116       ParsingInitForAutoVars.insert(NewVD);
6117 
6118     if (D.isInvalidType() || Invalid) {
6119       NewVD->setInvalidDecl();
6120       if (NewTemplate)
6121         NewTemplate->setInvalidDecl();
6122     }
6123 
6124     SetNestedNameSpecifier(NewVD, D);
6125 
6126     // If we have any template parameter lists that don't directly belong to
6127     // the variable (matching the scope specifier), store them.
6128     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6129     if (TemplateParamLists.size() > VDTemplateParamLists)
6130       NewVD->setTemplateParameterListsInfo(
6131           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6132 
6133     if (D.getDeclSpec().isConstexprSpecified()) {
6134       NewVD->setConstexpr(true);
6135       // C++1z [dcl.spec.constexpr]p1:
6136       //   A static data member declared with the constexpr specifier is
6137       //   implicitly an inline variable.
6138       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6139         NewVD->setImplicitlyInline();
6140     }
6141 
6142     if (D.getDeclSpec().isConceptSpecified()) {
6143       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6144         VTD->setConcept();
6145 
6146       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6147       // be declared with the thread_local, inline, friend, or constexpr
6148       // specifiers, [...]
6149       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6150         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6151              diag::err_concept_decl_invalid_specifiers)
6152             << 0 << 0;
6153         NewVD->setInvalidDecl(true);
6154       }
6155 
6156       if (D.getDeclSpec().isConstexprSpecified()) {
6157         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6158              diag::err_concept_decl_invalid_specifiers)
6159             << 0 << 3;
6160         NewVD->setInvalidDecl(true);
6161       }
6162 
6163       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6164       // applied only to the definition of a function template or variable
6165       // template, declared in namespace scope.
6166       if (IsVariableTemplateSpecialization) {
6167         Diag(D.getDeclSpec().getConceptSpecLoc(),
6168              diag::err_concept_specified_specialization)
6169             << (IsPartialSpecialization ? 2 : 1);
6170       }
6171 
6172       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6173       // following restrictions:
6174       // - The declared type shall have the type bool.
6175       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6176           !NewVD->isInvalidDecl()) {
6177         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6178         NewVD->setInvalidDecl(true);
6179       }
6180     }
6181   }
6182 
6183   if (D.getDeclSpec().isInlineSpecified()) {
6184     if (CurContext->isFunctionOrMethod()) {
6185       // 'inline' is not allowed on block scope variable declaration.
6186       Diag(D.getDeclSpec().getInlineSpecLoc(),
6187            diag::err_inline_declaration_block_scope) << Name
6188         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6189     } else {
6190       Diag(D.getDeclSpec().getInlineSpecLoc(),
6191            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6192                                      : diag::ext_inline_variable);
6193       NewVD->setInlineSpecified();
6194     }
6195   }
6196 
6197   // Set the lexical context. If the declarator has a C++ scope specifier, the
6198   // lexical context will be different from the semantic context.
6199   NewVD->setLexicalDeclContext(CurContext);
6200   if (NewTemplate)
6201     NewTemplate->setLexicalDeclContext(CurContext);
6202 
6203   if (IsLocalExternDecl)
6204     NewVD->setLocalExternDecl();
6205 
6206   bool EmitTLSUnsupportedError = false;
6207   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6208     // C++11 [dcl.stc]p4:
6209     //   When thread_local is applied to a variable of block scope the
6210     //   storage-class-specifier static is implied if it does not appear
6211     //   explicitly.
6212     // Core issue: 'static' is not implied if the variable is declared
6213     //   'extern'.
6214     if (NewVD->hasLocalStorage() &&
6215         (SCSpec != DeclSpec::SCS_unspecified ||
6216          TSCS != DeclSpec::TSCS_thread_local ||
6217          !DC->isFunctionOrMethod()))
6218       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6219            diag::err_thread_non_global)
6220         << DeclSpec::getSpecifierName(TSCS);
6221     else if (!Context.getTargetInfo().isTLSSupported()) {
6222       if (getLangOpts().CUDA) {
6223         // Postpone error emission until we've collected attributes required to
6224         // figure out whether it's a host or device variable and whether the
6225         // error should be ignored.
6226         EmitTLSUnsupportedError = true;
6227         // We still need to mark the variable as TLS so it shows up in AST with
6228         // proper storage class for other tools to use even if we're not going
6229         // to emit any code for it.
6230         NewVD->setTSCSpec(TSCS);
6231       } else
6232         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6233              diag::err_thread_unsupported);
6234     } else
6235       NewVD->setTSCSpec(TSCS);
6236   }
6237 
6238   // C99 6.7.4p3
6239   //   An inline definition of a function with external linkage shall
6240   //   not contain a definition of a modifiable object with static or
6241   //   thread storage duration...
6242   // We only apply this when the function is required to be defined
6243   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6244   // that a local variable with thread storage duration still has to
6245   // be marked 'static'.  Also note that it's possible to get these
6246   // semantics in C++ using __attribute__((gnu_inline)).
6247   if (SC == SC_Static && S->getFnParent() != nullptr &&
6248       !NewVD->getType().isConstQualified()) {
6249     FunctionDecl *CurFD = getCurFunctionDecl();
6250     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6251       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6252            diag::warn_static_local_in_extern_inline);
6253       MaybeSuggestAddingStaticToDecl(CurFD);
6254     }
6255   }
6256 
6257   if (D.getDeclSpec().isModulePrivateSpecified()) {
6258     if (IsVariableTemplateSpecialization)
6259       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6260           << (IsPartialSpecialization ? 1 : 0)
6261           << FixItHint::CreateRemoval(
6262                  D.getDeclSpec().getModulePrivateSpecLoc());
6263     else if (IsExplicitSpecialization)
6264       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6265         << 2
6266         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6267     else if (NewVD->hasLocalStorage())
6268       Diag(NewVD->getLocation(), diag::err_module_private_local)
6269         << 0 << NewVD->getDeclName()
6270         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6271         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6272     else {
6273       NewVD->setModulePrivate();
6274       if (NewTemplate)
6275         NewTemplate->setModulePrivate();
6276     }
6277   }
6278 
6279   // Handle attributes prior to checking for duplicates in MergeVarDecl
6280   ProcessDeclAttributes(S, NewVD, D);
6281 
6282   if (getLangOpts().CUDA) {
6283     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6284       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6285            diag::err_thread_unsupported);
6286     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6287     // storage [duration]."
6288     if (SC == SC_None && S->getFnParent() != nullptr &&
6289         (NewVD->hasAttr<CUDASharedAttr>() ||
6290          NewVD->hasAttr<CUDAConstantAttr>())) {
6291       NewVD->setStorageClass(SC_Static);
6292     }
6293   }
6294 
6295   // Ensure that dllimport globals without explicit storage class are treated as
6296   // extern. The storage class is set above using parsed attributes. Now we can
6297   // check the VarDecl itself.
6298   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6299          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6300          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6301 
6302   // In auto-retain/release, infer strong retension for variables of
6303   // retainable type.
6304   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6305     NewVD->setInvalidDecl();
6306 
6307   // Handle GNU asm-label extension (encoded as an attribute).
6308   if (Expr *E = (Expr*)D.getAsmLabel()) {
6309     // The parser guarantees this is a string.
6310     StringLiteral *SE = cast<StringLiteral>(E);
6311     StringRef Label = SE->getString();
6312     if (S->getFnParent() != nullptr) {
6313       switch (SC) {
6314       case SC_None:
6315       case SC_Auto:
6316         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6317         break;
6318       case SC_Register:
6319         // Local Named register
6320         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6321             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6322           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6323         break;
6324       case SC_Static:
6325       case SC_Extern:
6326       case SC_PrivateExtern:
6327         break;
6328       }
6329     } else if (SC == SC_Register) {
6330       // Global Named register
6331       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6332         const auto &TI = Context.getTargetInfo();
6333         bool HasSizeMismatch;
6334 
6335         if (!TI.isValidGCCRegisterName(Label))
6336           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6337         else if (!TI.validateGlobalRegisterVariable(Label,
6338                                                     Context.getTypeSize(R),
6339                                                     HasSizeMismatch))
6340           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6341         else if (HasSizeMismatch)
6342           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6343       }
6344 
6345       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6346         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6347         NewVD->setInvalidDecl(true);
6348       }
6349     }
6350 
6351     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6352                                                 Context, Label, 0));
6353   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6354     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6355       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6356     if (I != ExtnameUndeclaredIdentifiers.end()) {
6357       if (isDeclExternC(NewVD)) {
6358         NewVD->addAttr(I->second);
6359         ExtnameUndeclaredIdentifiers.erase(I);
6360       } else
6361         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6362             << /*Variable*/1 << NewVD;
6363     }
6364   }
6365 
6366   // Diagnose shadowed variables before filtering for scope.
6367   if (D.getCXXScopeSpec().isEmpty())
6368     CheckShadow(S, NewVD, Previous);
6369 
6370   // Don't consider existing declarations that are in a different
6371   // scope and are out-of-semantic-context declarations (if the new
6372   // declaration has linkage).
6373   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6374                        D.getCXXScopeSpec().isNotEmpty() ||
6375                        IsExplicitSpecialization ||
6376                        IsVariableTemplateSpecialization);
6377 
6378   // Check whether the previous declaration is in the same block scope. This
6379   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6380   if (getLangOpts().CPlusPlus &&
6381       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6382     NewVD->setPreviousDeclInSameBlockScope(
6383         Previous.isSingleResult() && !Previous.isShadowed() &&
6384         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6385 
6386   if (!getLangOpts().CPlusPlus) {
6387     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6388   } else {
6389     // If this is an explicit specialization of a static data member, check it.
6390     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6391         CheckMemberSpecialization(NewVD, Previous))
6392       NewVD->setInvalidDecl();
6393 
6394     // Merge the decl with the existing one if appropriate.
6395     if (!Previous.empty()) {
6396       if (Previous.isSingleResult() &&
6397           isa<FieldDecl>(Previous.getFoundDecl()) &&
6398           D.getCXXScopeSpec().isSet()) {
6399         // The user tried to define a non-static data member
6400         // out-of-line (C++ [dcl.meaning]p1).
6401         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6402           << D.getCXXScopeSpec().getRange();
6403         Previous.clear();
6404         NewVD->setInvalidDecl();
6405       }
6406     } else if (D.getCXXScopeSpec().isSet()) {
6407       // No previous declaration in the qualifying scope.
6408       Diag(D.getIdentifierLoc(), diag::err_no_member)
6409         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6410         << D.getCXXScopeSpec().getRange();
6411       NewVD->setInvalidDecl();
6412     }
6413 
6414     if (!IsVariableTemplateSpecialization)
6415       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6416 
6417     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6418     // an explicit specialization (14.8.3) or a partial specialization of a
6419     // concept definition.
6420     if (IsVariableTemplateSpecialization &&
6421         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6422         Previous.isSingleResult()) {
6423       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6424       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6425         if (VarTmpl->isConcept()) {
6426           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6427               << 1                            /*variable*/
6428               << (IsPartialSpecialization ? 2 /*partially specialized*/
6429                                           : 1 /*explicitly specialized*/);
6430           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6431           NewVD->setInvalidDecl();
6432         }
6433       }
6434     }
6435 
6436     if (NewTemplate) {
6437       VarTemplateDecl *PrevVarTemplate =
6438           NewVD->getPreviousDecl()
6439               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6440               : nullptr;
6441 
6442       // Check the template parameter list of this declaration, possibly
6443       // merging in the template parameter list from the previous variable
6444       // template declaration.
6445       if (CheckTemplateParameterList(
6446               TemplateParams,
6447               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6448                               : nullptr,
6449               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6450                DC->isDependentContext())
6451                   ? TPC_ClassTemplateMember
6452                   : TPC_VarTemplate))
6453         NewVD->setInvalidDecl();
6454 
6455       // If we are providing an explicit specialization of a static variable
6456       // template, make a note of that.
6457       if (PrevVarTemplate &&
6458           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6459         PrevVarTemplate->setMemberSpecialization();
6460     }
6461   }
6462 
6463   ProcessPragmaWeak(S, NewVD);
6464 
6465   // If this is the first declaration of an extern C variable, update
6466   // the map of such variables.
6467   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6468       isIncompleteDeclExternC(*this, NewVD))
6469     RegisterLocallyScopedExternCDecl(NewVD, S);
6470 
6471   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6472     Decl *ManglingContextDecl;
6473     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6474             NewVD->getDeclContext(), ManglingContextDecl)) {
6475       Context.setManglingNumber(
6476           NewVD, MCtx->getManglingNumber(
6477                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6478       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6479     }
6480   }
6481 
6482   // Special handling of variable named 'main'.
6483   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6484       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6485       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6486 
6487     // C++ [basic.start.main]p3
6488     // A program that declares a variable main at global scope is ill-formed.
6489     if (getLangOpts().CPlusPlus)
6490       Diag(D.getLocStart(), diag::err_main_global_variable);
6491 
6492     // In C, and external-linkage variable named main results in undefined
6493     // behavior.
6494     else if (NewVD->hasExternalFormalLinkage())
6495       Diag(D.getLocStart(), diag::warn_main_redefined);
6496   }
6497 
6498   if (D.isRedeclaration() && !Previous.empty()) {
6499     checkDLLAttributeRedeclaration(
6500         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6501         IsExplicitSpecialization, D.isFunctionDefinition());
6502   }
6503 
6504   if (NewTemplate) {
6505     if (NewVD->isInvalidDecl())
6506       NewTemplate->setInvalidDecl();
6507     ActOnDocumentableDecl(NewTemplate);
6508     return NewTemplate;
6509   }
6510 
6511   return NewVD;
6512 }
6513 
6514 /// Enum describing the %select options in diag::warn_decl_shadow.
6515 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6516 
6517 /// Determine what kind of declaration we're shadowing.
6518 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6519                                                 const DeclContext *OldDC) {
6520   if (isa<RecordDecl>(OldDC))
6521     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6522   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6523 }
6524 
6525 /// \brief Diagnose variable or built-in function shadowing.  Implements
6526 /// -Wshadow.
6527 ///
6528 /// This method is called whenever a VarDecl is added to a "useful"
6529 /// scope.
6530 ///
6531 /// \param S the scope in which the shadowing name is being declared
6532 /// \param R the lookup of the name
6533 ///
6534 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6535   // Return if warning is ignored.
6536   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6537     return;
6538 
6539   // Don't diagnose declarations at file scope.
6540   if (D->hasGlobalStorage())
6541     return;
6542 
6543   DeclContext *NewDC = D->getDeclContext();
6544 
6545   // Only diagnose if we're shadowing an unambiguous field or variable.
6546   if (R.getResultKind() != LookupResult::Found)
6547     return;
6548 
6549   NamedDecl* ShadowedDecl = R.getFoundDecl();
6550   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6551     return;
6552 
6553   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6554     // Fields are not shadowed by variables in C++ static methods.
6555     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6556       if (MD->isStatic())
6557         return;
6558 
6559     // Fields shadowed by constructor parameters are a special case. Usually
6560     // the constructor initializes the field with the parameter.
6561     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6562       // Remember that this was shadowed so we can either warn about its
6563       // modification or its existence depending on warning settings.
6564       D = D->getCanonicalDecl();
6565       ShadowingDecls.insert({D, FD});
6566       return;
6567     }
6568   }
6569 
6570   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6571     if (shadowedVar->isExternC()) {
6572       // For shadowing external vars, make sure that we point to the global
6573       // declaration, not a locally scoped extern declaration.
6574       for (auto I : shadowedVar->redecls())
6575         if (I->isFileVarDecl()) {
6576           ShadowedDecl = I;
6577           break;
6578         }
6579     }
6580 
6581   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6582 
6583   // Only warn about certain kinds of shadowing for class members.
6584   if (NewDC && NewDC->isRecord()) {
6585     // In particular, don't warn about shadowing non-class members.
6586     if (!OldDC->isRecord())
6587       return;
6588 
6589     // TODO: should we warn about static data members shadowing
6590     // static data members from base classes?
6591 
6592     // TODO: don't diagnose for inaccessible shadowed members.
6593     // This is hard to do perfectly because we might friend the
6594     // shadowing context, but that's just a false negative.
6595   }
6596 
6597 
6598   DeclarationName Name = R.getLookupName();
6599 
6600   // Emit warning and note.
6601   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6602     return;
6603   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6604   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6605   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6606 }
6607 
6608 /// \brief Check -Wshadow without the advantage of a previous lookup.
6609 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6610   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6611     return;
6612 
6613   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6614                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6615   LookupName(R, S);
6616   CheckShadow(S, D, R);
6617 }
6618 
6619 /// Check if 'E', which is an expression that is about to be modified, refers
6620 /// to a constructor parameter that shadows a field.
6621 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6622   // Quickly ignore expressions that can't be shadowing ctor parameters.
6623   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6624     return;
6625   E = E->IgnoreParenImpCasts();
6626   auto *DRE = dyn_cast<DeclRefExpr>(E);
6627   if (!DRE)
6628     return;
6629   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6630   auto I = ShadowingDecls.find(D);
6631   if (I == ShadowingDecls.end())
6632     return;
6633   const NamedDecl *ShadowedDecl = I->second;
6634   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6635   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6636   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6637   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6638 
6639   // Avoid issuing multiple warnings about the same decl.
6640   ShadowingDecls.erase(I);
6641 }
6642 
6643 /// Check for conflict between this global or extern "C" declaration and
6644 /// previous global or extern "C" declarations. This is only used in C++.
6645 template<typename T>
6646 static bool checkGlobalOrExternCConflict(
6647     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6648   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6649   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6650 
6651   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6652     // The common case: this global doesn't conflict with any extern "C"
6653     // declaration.
6654     return false;
6655   }
6656 
6657   if (Prev) {
6658     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6659       // Both the old and new declarations have C language linkage. This is a
6660       // redeclaration.
6661       Previous.clear();
6662       Previous.addDecl(Prev);
6663       return true;
6664     }
6665 
6666     // This is a global, non-extern "C" declaration, and there is a previous
6667     // non-global extern "C" declaration. Diagnose if this is a variable
6668     // declaration.
6669     if (!isa<VarDecl>(ND))
6670       return false;
6671   } else {
6672     // The declaration is extern "C". Check for any declaration in the
6673     // translation unit which might conflict.
6674     if (IsGlobal) {
6675       // We have already performed the lookup into the translation unit.
6676       IsGlobal = false;
6677       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6678            I != E; ++I) {
6679         if (isa<VarDecl>(*I)) {
6680           Prev = *I;
6681           break;
6682         }
6683       }
6684     } else {
6685       DeclContext::lookup_result R =
6686           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6687       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6688            I != E; ++I) {
6689         if (isa<VarDecl>(*I)) {
6690           Prev = *I;
6691           break;
6692         }
6693         // FIXME: If we have any other entity with this name in global scope,
6694         // the declaration is ill-formed, but that is a defect: it breaks the
6695         // 'stat' hack, for instance. Only variables can have mangled name
6696         // clashes with extern "C" declarations, so only they deserve a
6697         // diagnostic.
6698       }
6699     }
6700 
6701     if (!Prev)
6702       return false;
6703   }
6704 
6705   // Use the first declaration's location to ensure we point at something which
6706   // is lexically inside an extern "C" linkage-spec.
6707   assert(Prev && "should have found a previous declaration to diagnose");
6708   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6709     Prev = FD->getFirstDecl();
6710   else
6711     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6712 
6713   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6714     << IsGlobal << ND;
6715   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6716     << IsGlobal;
6717   return false;
6718 }
6719 
6720 /// Apply special rules for handling extern "C" declarations. Returns \c true
6721 /// if we have found that this is a redeclaration of some prior entity.
6722 ///
6723 /// Per C++ [dcl.link]p6:
6724 ///   Two declarations [for a function or variable] with C language linkage
6725 ///   with the same name that appear in different scopes refer to the same
6726 ///   [entity]. An entity with C language linkage shall not be declared with
6727 ///   the same name as an entity in global scope.
6728 template<typename T>
6729 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6730                                                   LookupResult &Previous) {
6731   if (!S.getLangOpts().CPlusPlus) {
6732     // In C, when declaring a global variable, look for a corresponding 'extern'
6733     // variable declared in function scope. We don't need this in C++, because
6734     // we find local extern decls in the surrounding file-scope DeclContext.
6735     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6736       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6737         Previous.clear();
6738         Previous.addDecl(Prev);
6739         return true;
6740       }
6741     }
6742     return false;
6743   }
6744 
6745   // A declaration in the translation unit can conflict with an extern "C"
6746   // declaration.
6747   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6748     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6749 
6750   // An extern "C" declaration can conflict with a declaration in the
6751   // translation unit or can be a redeclaration of an extern "C" declaration
6752   // in another scope.
6753   if (isIncompleteDeclExternC(S,ND))
6754     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6755 
6756   // Neither global nor extern "C": nothing to do.
6757   return false;
6758 }
6759 
6760 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6761   // If the decl is already known invalid, don't check it.
6762   if (NewVD->isInvalidDecl())
6763     return;
6764 
6765   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6766   QualType T = TInfo->getType();
6767 
6768   // Defer checking an 'auto' type until its initializer is attached.
6769   if (T->isUndeducedType())
6770     return;
6771 
6772   if (NewVD->hasAttrs())
6773     CheckAlignasUnderalignment(NewVD);
6774 
6775   if (T->isObjCObjectType()) {
6776     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6777       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6778     T = Context.getObjCObjectPointerType(T);
6779     NewVD->setType(T);
6780   }
6781 
6782   // Emit an error if an address space was applied to decl with local storage.
6783   // This includes arrays of objects with address space qualifiers, but not
6784   // automatic variables that point to other address spaces.
6785   // ISO/IEC TR 18037 S5.1.2
6786   if (!getLangOpts().OpenCL
6787       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6788     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6789     NewVD->setInvalidDecl();
6790     return;
6791   }
6792 
6793   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6794   // scope.
6795   if (getLangOpts().OpenCLVersion == 120 &&
6796       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6797       NewVD->isStaticLocal()) {
6798     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6799     NewVD->setInvalidDecl();
6800     return;
6801   }
6802 
6803   if (getLangOpts().OpenCL) {
6804     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6805     if (NewVD->hasAttr<BlocksAttr>()) {
6806       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6807       return;
6808     }
6809 
6810     if (T->isBlockPointerType()) {
6811       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6812       // can't use 'extern' storage class.
6813       if (!T.isConstQualified()) {
6814         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6815             << 0 /*const*/;
6816         NewVD->setInvalidDecl();
6817         return;
6818       }
6819       if (NewVD->hasExternalStorage()) {
6820         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6821         NewVD->setInvalidDecl();
6822         return;
6823       }
6824       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6825       // TODO: this check is not enough as it doesn't diagnose the typedef
6826       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6827       const FunctionProtoType *FTy =
6828           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6829       if (FTy && FTy->isVariadic()) {
6830         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6831             << T << NewVD->getSourceRange();
6832         NewVD->setInvalidDecl();
6833         return;
6834       }
6835     }
6836     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6837     // __constant address space.
6838     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6839     // variables inside a function can also be declared in the global
6840     // address space.
6841     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6842         NewVD->hasExternalStorage()) {
6843       if (!T->isSamplerT() &&
6844           !(T.getAddressSpace() == LangAS::opencl_constant ||
6845             (T.getAddressSpace() == LangAS::opencl_global &&
6846              getLangOpts().OpenCLVersion == 200))) {
6847         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6848         if (getLangOpts().OpenCLVersion == 200)
6849           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6850               << Scope << "global or constant";
6851         else
6852           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6853               << Scope << "constant";
6854         NewVD->setInvalidDecl();
6855         return;
6856       }
6857     } else {
6858       if (T.getAddressSpace() == LangAS::opencl_global) {
6859         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6860             << 1 /*is any function*/ << "global";
6861         NewVD->setInvalidDecl();
6862         return;
6863       }
6864       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6865       // in functions.
6866       if (T.getAddressSpace() == LangAS::opencl_constant ||
6867           T.getAddressSpace() == LangAS::opencl_local) {
6868         FunctionDecl *FD = getCurFunctionDecl();
6869         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6870           if (T.getAddressSpace() == LangAS::opencl_constant)
6871             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6872                 << 0 /*non-kernel only*/ << "constant";
6873           else
6874             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6875                 << 0 /*non-kernel only*/ << "local";
6876           NewVD->setInvalidDecl();
6877           return;
6878         }
6879       }
6880     }
6881   }
6882 
6883   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6884       && !NewVD->hasAttr<BlocksAttr>()) {
6885     if (getLangOpts().getGC() != LangOptions::NonGC)
6886       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6887     else {
6888       assert(!getLangOpts().ObjCAutoRefCount);
6889       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6890     }
6891   }
6892 
6893   bool isVM = T->isVariablyModifiedType();
6894   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6895       NewVD->hasAttr<BlocksAttr>())
6896     getCurFunction()->setHasBranchProtectedScope();
6897 
6898   if ((isVM && NewVD->hasLinkage()) ||
6899       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6900     bool SizeIsNegative;
6901     llvm::APSInt Oversized;
6902     TypeSourceInfo *FixedTInfo =
6903       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6904                                                     SizeIsNegative, Oversized);
6905     if (!FixedTInfo && T->isVariableArrayType()) {
6906       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6907       // FIXME: This won't give the correct result for
6908       // int a[10][n];
6909       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6910 
6911       if (NewVD->isFileVarDecl())
6912         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6913         << SizeRange;
6914       else if (NewVD->isStaticLocal())
6915         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6916         << SizeRange;
6917       else
6918         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6919         << SizeRange;
6920       NewVD->setInvalidDecl();
6921       return;
6922     }
6923 
6924     if (!FixedTInfo) {
6925       if (NewVD->isFileVarDecl())
6926         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6927       else
6928         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6929       NewVD->setInvalidDecl();
6930       return;
6931     }
6932 
6933     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6934     NewVD->setType(FixedTInfo->getType());
6935     NewVD->setTypeSourceInfo(FixedTInfo);
6936   }
6937 
6938   if (T->isVoidType()) {
6939     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6940     //                    of objects and functions.
6941     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6942       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6943         << T;
6944       NewVD->setInvalidDecl();
6945       return;
6946     }
6947   }
6948 
6949   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6950     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6951     NewVD->setInvalidDecl();
6952     return;
6953   }
6954 
6955   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6956     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6957     NewVD->setInvalidDecl();
6958     return;
6959   }
6960 
6961   if (NewVD->isConstexpr() && !T->isDependentType() &&
6962       RequireLiteralType(NewVD->getLocation(), T,
6963                          diag::err_constexpr_var_non_literal)) {
6964     NewVD->setInvalidDecl();
6965     return;
6966   }
6967 }
6968 
6969 /// \brief Perform semantic checking on a newly-created variable
6970 /// declaration.
6971 ///
6972 /// This routine performs all of the type-checking required for a
6973 /// variable declaration once it has been built. It is used both to
6974 /// check variables after they have been parsed and their declarators
6975 /// have been translated into a declaration, and to check variables
6976 /// that have been instantiated from a template.
6977 ///
6978 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6979 ///
6980 /// Returns true if the variable declaration is a redeclaration.
6981 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6982   CheckVariableDeclarationType(NewVD);
6983 
6984   // If the decl is already known invalid, don't check it.
6985   if (NewVD->isInvalidDecl())
6986     return false;
6987 
6988   // If we did not find anything by this name, look for a non-visible
6989   // extern "C" declaration with the same name.
6990   if (Previous.empty() &&
6991       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6992     Previous.setShadowed();
6993 
6994   if (!Previous.empty()) {
6995     MergeVarDecl(NewVD, Previous);
6996     return true;
6997   }
6998   return false;
6999 }
7000 
7001 namespace {
7002 struct FindOverriddenMethod {
7003   Sema *S;
7004   CXXMethodDecl *Method;
7005 
7006   /// Member lookup function that determines whether a given C++
7007   /// method overrides a method in a base class, to be used with
7008   /// CXXRecordDecl::lookupInBases().
7009   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7010     RecordDecl *BaseRecord =
7011         Specifier->getType()->getAs<RecordType>()->getDecl();
7012 
7013     DeclarationName Name = Method->getDeclName();
7014 
7015     // FIXME: Do we care about other names here too?
7016     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7017       // We really want to find the base class destructor here.
7018       QualType T = S->Context.getTypeDeclType(BaseRecord);
7019       CanQualType CT = S->Context.getCanonicalType(T);
7020 
7021       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7022     }
7023 
7024     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7025          Path.Decls = Path.Decls.slice(1)) {
7026       NamedDecl *D = Path.Decls.front();
7027       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7028         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7029           return true;
7030       }
7031     }
7032 
7033     return false;
7034   }
7035 };
7036 
7037 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7038 } // end anonymous namespace
7039 
7040 /// \brief Report an error regarding overriding, along with any relevant
7041 /// overriden methods.
7042 ///
7043 /// \param DiagID the primary error to report.
7044 /// \param MD the overriding method.
7045 /// \param OEK which overrides to include as notes.
7046 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7047                             OverrideErrorKind OEK = OEK_All) {
7048   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7049   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7050                                       E = MD->end_overridden_methods();
7051        I != E; ++I) {
7052     // This check (& the OEK parameter) could be replaced by a predicate, but
7053     // without lambdas that would be overkill. This is still nicer than writing
7054     // out the diag loop 3 times.
7055     if ((OEK == OEK_All) ||
7056         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7057         (OEK == OEK_Deleted && (*I)->isDeleted()))
7058       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7059   }
7060 }
7061 
7062 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7063 /// and if so, check that it's a valid override and remember it.
7064 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7065   // Look for methods in base classes that this method might override.
7066   CXXBasePaths Paths;
7067   FindOverriddenMethod FOM;
7068   FOM.Method = MD;
7069   FOM.S = this;
7070   bool hasDeletedOverridenMethods = false;
7071   bool hasNonDeletedOverridenMethods = false;
7072   bool AddedAny = false;
7073   if (DC->lookupInBases(FOM, Paths)) {
7074     for (auto *I : Paths.found_decls()) {
7075       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7076         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7077         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7078             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7079             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7080             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7081           hasDeletedOverridenMethods |= OldMD->isDeleted();
7082           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7083           AddedAny = true;
7084         }
7085       }
7086     }
7087   }
7088 
7089   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7090     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7091   }
7092   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7093     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7094   }
7095 
7096   return AddedAny;
7097 }
7098 
7099 namespace {
7100   // Struct for holding all of the extra arguments needed by
7101   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7102   struct ActOnFDArgs {
7103     Scope *S;
7104     Declarator &D;
7105     MultiTemplateParamsArg TemplateParamLists;
7106     bool AddToScope;
7107   };
7108 } // end anonymous namespace
7109 
7110 namespace {
7111 
7112 // Callback to only accept typo corrections that have a non-zero edit distance.
7113 // Also only accept corrections that have the same parent decl.
7114 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7115  public:
7116   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7117                             CXXRecordDecl *Parent)
7118       : Context(Context), OriginalFD(TypoFD),
7119         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7120 
7121   bool ValidateCandidate(const TypoCorrection &candidate) override {
7122     if (candidate.getEditDistance() == 0)
7123       return false;
7124 
7125     SmallVector<unsigned, 1> MismatchedParams;
7126     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7127                                           CDeclEnd = candidate.end();
7128          CDecl != CDeclEnd; ++CDecl) {
7129       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7130 
7131       if (FD && !FD->hasBody() &&
7132           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7133         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7134           CXXRecordDecl *Parent = MD->getParent();
7135           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7136             return true;
7137         } else if (!ExpectedParent) {
7138           return true;
7139         }
7140       }
7141     }
7142 
7143     return false;
7144   }
7145 
7146  private:
7147   ASTContext &Context;
7148   FunctionDecl *OriginalFD;
7149   CXXRecordDecl *ExpectedParent;
7150 };
7151 
7152 } // end anonymous namespace
7153 
7154 /// \brief Generate diagnostics for an invalid function redeclaration.
7155 ///
7156 /// This routine handles generating the diagnostic messages for an invalid
7157 /// function redeclaration, including finding possible similar declarations
7158 /// or performing typo correction if there are no previous declarations with
7159 /// the same name.
7160 ///
7161 /// Returns a NamedDecl iff typo correction was performed and substituting in
7162 /// the new declaration name does not cause new errors.
7163 static NamedDecl *DiagnoseInvalidRedeclaration(
7164     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7165     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7166   DeclarationName Name = NewFD->getDeclName();
7167   DeclContext *NewDC = NewFD->getDeclContext();
7168   SmallVector<unsigned, 1> MismatchedParams;
7169   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7170   TypoCorrection Correction;
7171   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7172   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7173                                    : diag::err_member_decl_does_not_match;
7174   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7175                     IsLocalFriend ? Sema::LookupLocalFriendName
7176                                   : Sema::LookupOrdinaryName,
7177                     Sema::ForRedeclaration);
7178 
7179   NewFD->setInvalidDecl();
7180   if (IsLocalFriend)
7181     SemaRef.LookupName(Prev, S);
7182   else
7183     SemaRef.LookupQualifiedName(Prev, NewDC);
7184   assert(!Prev.isAmbiguous() &&
7185          "Cannot have an ambiguity in previous-declaration lookup");
7186   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7187   if (!Prev.empty()) {
7188     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7189          Func != FuncEnd; ++Func) {
7190       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7191       if (FD &&
7192           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7193         // Add 1 to the index so that 0 can mean the mismatch didn't
7194         // involve a parameter
7195         unsigned ParamNum =
7196             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7197         NearMatches.push_back(std::make_pair(FD, ParamNum));
7198       }
7199     }
7200   // If the qualified name lookup yielded nothing, try typo correction
7201   } else if ((Correction = SemaRef.CorrectTypo(
7202                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7203                   &ExtraArgs.D.getCXXScopeSpec(),
7204                   llvm::make_unique<DifferentNameValidatorCCC>(
7205                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7206                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7207     // Set up everything for the call to ActOnFunctionDeclarator
7208     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7209                               ExtraArgs.D.getIdentifierLoc());
7210     Previous.clear();
7211     Previous.setLookupName(Correction.getCorrection());
7212     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7213                                     CDeclEnd = Correction.end();
7214          CDecl != CDeclEnd; ++CDecl) {
7215       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7216       if (FD && !FD->hasBody() &&
7217           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7218         Previous.addDecl(FD);
7219       }
7220     }
7221     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7222 
7223     NamedDecl *Result;
7224     // Retry building the function declaration with the new previous
7225     // declarations, and with errors suppressed.
7226     {
7227       // Trap errors.
7228       Sema::SFINAETrap Trap(SemaRef);
7229 
7230       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7231       // pieces need to verify the typo-corrected C++ declaration and hopefully
7232       // eliminate the need for the parameter pack ExtraArgs.
7233       Result = SemaRef.ActOnFunctionDeclarator(
7234           ExtraArgs.S, ExtraArgs.D,
7235           Correction.getCorrectionDecl()->getDeclContext(),
7236           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7237           ExtraArgs.AddToScope);
7238 
7239       if (Trap.hasErrorOccurred())
7240         Result = nullptr;
7241     }
7242 
7243     if (Result) {
7244       // Determine which correction we picked.
7245       Decl *Canonical = Result->getCanonicalDecl();
7246       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7247            I != E; ++I)
7248         if ((*I)->getCanonicalDecl() == Canonical)
7249           Correction.setCorrectionDecl(*I);
7250 
7251       SemaRef.diagnoseTypo(
7252           Correction,
7253           SemaRef.PDiag(IsLocalFriend
7254                           ? diag::err_no_matching_local_friend_suggest
7255                           : diag::err_member_decl_does_not_match_suggest)
7256             << Name << NewDC << IsDefinition);
7257       return Result;
7258     }
7259 
7260     // Pretend the typo correction never occurred
7261     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7262                               ExtraArgs.D.getIdentifierLoc());
7263     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7264     Previous.clear();
7265     Previous.setLookupName(Name);
7266   }
7267 
7268   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7269       << Name << NewDC << IsDefinition << NewFD->getLocation();
7270 
7271   bool NewFDisConst = false;
7272   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7273     NewFDisConst = NewMD->isConst();
7274 
7275   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7276        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7277        NearMatch != NearMatchEnd; ++NearMatch) {
7278     FunctionDecl *FD = NearMatch->first;
7279     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7280     bool FDisConst = MD && MD->isConst();
7281     bool IsMember = MD || !IsLocalFriend;
7282 
7283     // FIXME: These notes are poorly worded for the local friend case.
7284     if (unsigned Idx = NearMatch->second) {
7285       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7286       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7287       if (Loc.isInvalid()) Loc = FD->getLocation();
7288       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7289                                  : diag::note_local_decl_close_param_match)
7290         << Idx << FDParam->getType()
7291         << NewFD->getParamDecl(Idx - 1)->getType();
7292     } else if (FDisConst != NewFDisConst) {
7293       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7294           << NewFDisConst << FD->getSourceRange().getEnd();
7295     } else
7296       SemaRef.Diag(FD->getLocation(),
7297                    IsMember ? diag::note_member_def_close_match
7298                             : diag::note_local_decl_close_match);
7299   }
7300   return nullptr;
7301 }
7302 
7303 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7304   switch (D.getDeclSpec().getStorageClassSpec()) {
7305   default: llvm_unreachable("Unknown storage class!");
7306   case DeclSpec::SCS_auto:
7307   case DeclSpec::SCS_register:
7308   case DeclSpec::SCS_mutable:
7309     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7310                  diag::err_typecheck_sclass_func);
7311     D.setInvalidType();
7312     break;
7313   case DeclSpec::SCS_unspecified: break;
7314   case DeclSpec::SCS_extern:
7315     if (D.getDeclSpec().isExternInLinkageSpec())
7316       return SC_None;
7317     return SC_Extern;
7318   case DeclSpec::SCS_static: {
7319     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7320       // C99 6.7.1p5:
7321       //   The declaration of an identifier for a function that has
7322       //   block scope shall have no explicit storage-class specifier
7323       //   other than extern
7324       // See also (C++ [dcl.stc]p4).
7325       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7326                    diag::err_static_block_func);
7327       break;
7328     } else
7329       return SC_Static;
7330   }
7331   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7332   }
7333 
7334   // No explicit storage class has already been returned
7335   return SC_None;
7336 }
7337 
7338 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7339                                            DeclContext *DC, QualType &R,
7340                                            TypeSourceInfo *TInfo,
7341                                            StorageClass SC,
7342                                            bool &IsVirtualOkay) {
7343   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7344   DeclarationName Name = NameInfo.getName();
7345 
7346   FunctionDecl *NewFD = nullptr;
7347   bool isInline = D.getDeclSpec().isInlineSpecified();
7348 
7349   if (!SemaRef.getLangOpts().CPlusPlus) {
7350     // Determine whether the function was written with a
7351     // prototype. This true when:
7352     //   - there is a prototype in the declarator, or
7353     //   - the type R of the function is some kind of typedef or other reference
7354     //     to a type name (which eventually refers to a function type).
7355     bool HasPrototype =
7356       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7357       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7358 
7359     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7360                                  D.getLocStart(), NameInfo, R,
7361                                  TInfo, SC, isInline,
7362                                  HasPrototype, false);
7363     if (D.isInvalidType())
7364       NewFD->setInvalidDecl();
7365 
7366     return NewFD;
7367   }
7368 
7369   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7370   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7371 
7372   // Check that the return type is not an abstract class type.
7373   // For record types, this is done by the AbstractClassUsageDiagnoser once
7374   // the class has been completely parsed.
7375   if (!DC->isRecord() &&
7376       SemaRef.RequireNonAbstractType(
7377           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7378           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7379     D.setInvalidType();
7380 
7381   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7382     // This is a C++ constructor declaration.
7383     assert(DC->isRecord() &&
7384            "Constructors can only be declared in a member context");
7385 
7386     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7387     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7388                                       D.getLocStart(), NameInfo,
7389                                       R, TInfo, isExplicit, isInline,
7390                                       /*isImplicitlyDeclared=*/false,
7391                                       isConstexpr);
7392 
7393   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7394     // This is a C++ destructor declaration.
7395     if (DC->isRecord()) {
7396       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7397       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7398       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7399                                         SemaRef.Context, Record,
7400                                         D.getLocStart(),
7401                                         NameInfo, R, TInfo, isInline,
7402                                         /*isImplicitlyDeclared=*/false);
7403 
7404       // If the class is complete, then we now create the implicit exception
7405       // specification. If the class is incomplete or dependent, we can't do
7406       // it yet.
7407       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7408           Record->getDefinition() && !Record->isBeingDefined() &&
7409           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7410         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7411       }
7412 
7413       IsVirtualOkay = true;
7414       return NewDD;
7415 
7416     } else {
7417       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7418       D.setInvalidType();
7419 
7420       // Create a FunctionDecl to satisfy the function definition parsing
7421       // code path.
7422       return FunctionDecl::Create(SemaRef.Context, DC,
7423                                   D.getLocStart(),
7424                                   D.getIdentifierLoc(), Name, R, TInfo,
7425                                   SC, isInline,
7426                                   /*hasPrototype=*/true, isConstexpr);
7427     }
7428 
7429   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7430     if (!DC->isRecord()) {
7431       SemaRef.Diag(D.getIdentifierLoc(),
7432            diag::err_conv_function_not_member);
7433       return nullptr;
7434     }
7435 
7436     SemaRef.CheckConversionDeclarator(D, R, SC);
7437     IsVirtualOkay = true;
7438     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7439                                      D.getLocStart(), NameInfo,
7440                                      R, TInfo, isInline, isExplicit,
7441                                      isConstexpr, SourceLocation());
7442 
7443   } else if (DC->isRecord()) {
7444     // If the name of the function is the same as the name of the record,
7445     // then this must be an invalid constructor that has a return type.
7446     // (The parser checks for a return type and makes the declarator a
7447     // constructor if it has no return type).
7448     if (Name.getAsIdentifierInfo() &&
7449         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7450       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7451         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7452         << SourceRange(D.getIdentifierLoc());
7453       return nullptr;
7454     }
7455 
7456     // This is a C++ method declaration.
7457     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7458                                                cast<CXXRecordDecl>(DC),
7459                                                D.getLocStart(), NameInfo, R,
7460                                                TInfo, SC, isInline,
7461                                                isConstexpr, SourceLocation());
7462     IsVirtualOkay = !Ret->isStatic();
7463     return Ret;
7464   } else {
7465     bool isFriend =
7466         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7467     if (!isFriend && SemaRef.CurContext->isRecord())
7468       return nullptr;
7469 
7470     // Determine whether the function was written with a
7471     // prototype. This true when:
7472     //   - we're in C++ (where every function has a prototype),
7473     return FunctionDecl::Create(SemaRef.Context, DC,
7474                                 D.getLocStart(),
7475                                 NameInfo, R, TInfo, SC, isInline,
7476                                 true/*HasPrototype*/, isConstexpr);
7477   }
7478 }
7479 
7480 enum OpenCLParamType {
7481   ValidKernelParam,
7482   PtrPtrKernelParam,
7483   PtrKernelParam,
7484   PrivatePtrKernelParam,
7485   InvalidKernelParam,
7486   RecordKernelParam
7487 };
7488 
7489 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7490   if (PT->isPointerType()) {
7491     QualType PointeeType = PT->getPointeeType();
7492     if (PointeeType->isPointerType())
7493       return PtrPtrKernelParam;
7494     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7495                                               : PtrKernelParam;
7496   }
7497 
7498   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7499   // be used as builtin types.
7500 
7501   if (PT->isImageType())
7502     return PtrKernelParam;
7503 
7504   if (PT->isBooleanType())
7505     return InvalidKernelParam;
7506 
7507   if (PT->isEventT())
7508     return InvalidKernelParam;
7509 
7510   if (PT->isHalfType())
7511     return InvalidKernelParam;
7512 
7513   if (PT->isRecordType())
7514     return RecordKernelParam;
7515 
7516   return ValidKernelParam;
7517 }
7518 
7519 static void checkIsValidOpenCLKernelParameter(
7520   Sema &S,
7521   Declarator &D,
7522   ParmVarDecl *Param,
7523   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7524   QualType PT = Param->getType();
7525 
7526   // Cache the valid types we encounter to avoid rechecking structs that are
7527   // used again
7528   if (ValidTypes.count(PT.getTypePtr()))
7529     return;
7530 
7531   switch (getOpenCLKernelParameterType(PT)) {
7532   case PtrPtrKernelParam:
7533     // OpenCL v1.2 s6.9.a:
7534     // A kernel function argument cannot be declared as a
7535     // pointer to a pointer type.
7536     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7537     D.setInvalidType();
7538     return;
7539 
7540   case PrivatePtrKernelParam:
7541     // OpenCL v1.2 s6.9.a:
7542     // A kernel function argument cannot be declared as a
7543     // pointer to the private address space.
7544     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7545     D.setInvalidType();
7546     return;
7547 
7548     // OpenCL v1.2 s6.9.k:
7549     // Arguments to kernel functions in a program cannot be declared with the
7550     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7551     // uintptr_t or a struct and/or union that contain fields declared to be
7552     // one of these built-in scalar types.
7553 
7554   case InvalidKernelParam:
7555     // OpenCL v1.2 s6.8 n:
7556     // A kernel function argument cannot be declared
7557     // of event_t type.
7558     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7559     D.setInvalidType();
7560     return;
7561 
7562   case PtrKernelParam:
7563   case ValidKernelParam:
7564     ValidTypes.insert(PT.getTypePtr());
7565     return;
7566 
7567   case RecordKernelParam:
7568     break;
7569   }
7570 
7571   // Track nested structs we will inspect
7572   SmallVector<const Decl *, 4> VisitStack;
7573 
7574   // Track where we are in the nested structs. Items will migrate from
7575   // VisitStack to HistoryStack as we do the DFS for bad field.
7576   SmallVector<const FieldDecl *, 4> HistoryStack;
7577   HistoryStack.push_back(nullptr);
7578 
7579   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7580   VisitStack.push_back(PD);
7581 
7582   assert(VisitStack.back() && "First decl null?");
7583 
7584   do {
7585     const Decl *Next = VisitStack.pop_back_val();
7586     if (!Next) {
7587       assert(!HistoryStack.empty());
7588       // Found a marker, we have gone up a level
7589       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7590         ValidTypes.insert(Hist->getType().getTypePtr());
7591 
7592       continue;
7593     }
7594 
7595     // Adds everything except the original parameter declaration (which is not a
7596     // field itself) to the history stack.
7597     const RecordDecl *RD;
7598     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7599       HistoryStack.push_back(Field);
7600       RD = Field->getType()->castAs<RecordType>()->getDecl();
7601     } else {
7602       RD = cast<RecordDecl>(Next);
7603     }
7604 
7605     // Add a null marker so we know when we've gone back up a level
7606     VisitStack.push_back(nullptr);
7607 
7608     for (const auto *FD : RD->fields()) {
7609       QualType QT = FD->getType();
7610 
7611       if (ValidTypes.count(QT.getTypePtr()))
7612         continue;
7613 
7614       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7615       if (ParamType == ValidKernelParam)
7616         continue;
7617 
7618       if (ParamType == RecordKernelParam) {
7619         VisitStack.push_back(FD);
7620         continue;
7621       }
7622 
7623       // OpenCL v1.2 s6.9.p:
7624       // Arguments to kernel functions that are declared to be a struct or union
7625       // do not allow OpenCL objects to be passed as elements of the struct or
7626       // union.
7627       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7628           ParamType == PrivatePtrKernelParam) {
7629         S.Diag(Param->getLocation(),
7630                diag::err_record_with_pointers_kernel_param)
7631           << PT->isUnionType()
7632           << PT;
7633       } else {
7634         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7635       }
7636 
7637       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7638         << PD->getDeclName();
7639 
7640       // We have an error, now let's go back up through history and show where
7641       // the offending field came from
7642       for (ArrayRef<const FieldDecl *>::const_iterator
7643                I = HistoryStack.begin() + 1,
7644                E = HistoryStack.end();
7645            I != E; ++I) {
7646         const FieldDecl *OuterField = *I;
7647         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7648           << OuterField->getType();
7649       }
7650 
7651       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7652         << QT->isPointerType()
7653         << QT;
7654       D.setInvalidType();
7655       return;
7656     }
7657   } while (!VisitStack.empty());
7658 }
7659 
7660 NamedDecl*
7661 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7662                               TypeSourceInfo *TInfo, LookupResult &Previous,
7663                               MultiTemplateParamsArg TemplateParamLists,
7664                               bool &AddToScope) {
7665   QualType R = TInfo->getType();
7666 
7667   assert(R.getTypePtr()->isFunctionType());
7668 
7669   // TODO: consider using NameInfo for diagnostic.
7670   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7671   DeclarationName Name = NameInfo.getName();
7672   StorageClass SC = getFunctionStorageClass(*this, D);
7673 
7674   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7675     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7676          diag::err_invalid_thread)
7677       << DeclSpec::getSpecifierName(TSCS);
7678 
7679   if (D.isFirstDeclarationOfMember())
7680     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7681                            D.getIdentifierLoc());
7682 
7683   bool isFriend = false;
7684   FunctionTemplateDecl *FunctionTemplate = nullptr;
7685   bool isExplicitSpecialization = false;
7686   bool isFunctionTemplateSpecialization = false;
7687 
7688   bool isDependentClassScopeExplicitSpecialization = false;
7689   bool HasExplicitTemplateArgs = false;
7690   TemplateArgumentListInfo TemplateArgs;
7691 
7692   bool isVirtualOkay = false;
7693 
7694   DeclContext *OriginalDC = DC;
7695   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7696 
7697   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7698                                               isVirtualOkay);
7699   if (!NewFD) return nullptr;
7700 
7701   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7702     NewFD->setTopLevelDeclInObjCContainer();
7703 
7704   // Set the lexical context. If this is a function-scope declaration, or has a
7705   // C++ scope specifier, or is the object of a friend declaration, the lexical
7706   // context will be different from the semantic context.
7707   NewFD->setLexicalDeclContext(CurContext);
7708 
7709   if (IsLocalExternDecl)
7710     NewFD->setLocalExternDecl();
7711 
7712   if (getLangOpts().CPlusPlus) {
7713     bool isInline = D.getDeclSpec().isInlineSpecified();
7714     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7715     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7716     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7717     bool isConcept = D.getDeclSpec().isConceptSpecified();
7718     isFriend = D.getDeclSpec().isFriendSpecified();
7719     if (isFriend && !isInline && D.isFunctionDefinition()) {
7720       // C++ [class.friend]p5
7721       //   A function can be defined in a friend declaration of a
7722       //   class . . . . Such a function is implicitly inline.
7723       NewFD->setImplicitlyInline();
7724     }
7725 
7726     // If this is a method defined in an __interface, and is not a constructor
7727     // or an overloaded operator, then set the pure flag (isVirtual will already
7728     // return true).
7729     if (const CXXRecordDecl *Parent =
7730           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7731       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7732         NewFD->setPure(true);
7733 
7734       // C++ [class.union]p2
7735       //   A union can have member functions, but not virtual functions.
7736       if (isVirtual && Parent->isUnion())
7737         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7738     }
7739 
7740     SetNestedNameSpecifier(NewFD, D);
7741     isExplicitSpecialization = false;
7742     isFunctionTemplateSpecialization = false;
7743     if (D.isInvalidType())
7744       NewFD->setInvalidDecl();
7745 
7746     // Match up the template parameter lists with the scope specifier, then
7747     // determine whether we have a template or a template specialization.
7748     bool Invalid = false;
7749     if (TemplateParameterList *TemplateParams =
7750             MatchTemplateParametersToScopeSpecifier(
7751                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7752                 D.getCXXScopeSpec(),
7753                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7754                     ? D.getName().TemplateId
7755                     : nullptr,
7756                 TemplateParamLists, isFriend, isExplicitSpecialization,
7757                 Invalid)) {
7758       if (TemplateParams->size() > 0) {
7759         // This is a function template
7760 
7761         // Check that we can declare a template here.
7762         if (CheckTemplateDeclScope(S, TemplateParams))
7763           NewFD->setInvalidDecl();
7764 
7765         // A destructor cannot be a template.
7766         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7767           Diag(NewFD->getLocation(), diag::err_destructor_template);
7768           NewFD->setInvalidDecl();
7769         }
7770 
7771         // If we're adding a template to a dependent context, we may need to
7772         // rebuilding some of the types used within the template parameter list,
7773         // now that we know what the current instantiation is.
7774         if (DC->isDependentContext()) {
7775           ContextRAII SavedContext(*this, DC);
7776           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7777             Invalid = true;
7778         }
7779 
7780         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7781                                                         NewFD->getLocation(),
7782                                                         Name, TemplateParams,
7783                                                         NewFD);
7784         FunctionTemplate->setLexicalDeclContext(CurContext);
7785         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7786 
7787         // For source fidelity, store the other template param lists.
7788         if (TemplateParamLists.size() > 1) {
7789           NewFD->setTemplateParameterListsInfo(Context,
7790                                                TemplateParamLists.drop_back(1));
7791         }
7792       } else {
7793         // This is a function template specialization.
7794         isFunctionTemplateSpecialization = true;
7795         // For source fidelity, store all the template param lists.
7796         if (TemplateParamLists.size() > 0)
7797           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7798 
7799         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7800         if (isFriend) {
7801           // We want to remove the "template<>", found here.
7802           SourceRange RemoveRange = TemplateParams->getSourceRange();
7803 
7804           // If we remove the template<> and the name is not a
7805           // template-id, we're actually silently creating a problem:
7806           // the friend declaration will refer to an untemplated decl,
7807           // and clearly the user wants a template specialization.  So
7808           // we need to insert '<>' after the name.
7809           SourceLocation InsertLoc;
7810           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7811             InsertLoc = D.getName().getSourceRange().getEnd();
7812             InsertLoc = getLocForEndOfToken(InsertLoc);
7813           }
7814 
7815           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7816             << Name << RemoveRange
7817             << FixItHint::CreateRemoval(RemoveRange)
7818             << FixItHint::CreateInsertion(InsertLoc, "<>");
7819         }
7820       }
7821     }
7822     else {
7823       // All template param lists were matched against the scope specifier:
7824       // this is NOT (an explicit specialization of) a template.
7825       if (TemplateParamLists.size() > 0)
7826         // For source fidelity, store all the template param lists.
7827         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7828     }
7829 
7830     if (Invalid) {
7831       NewFD->setInvalidDecl();
7832       if (FunctionTemplate)
7833         FunctionTemplate->setInvalidDecl();
7834     }
7835 
7836     // C++ [dcl.fct.spec]p5:
7837     //   The virtual specifier shall only be used in declarations of
7838     //   nonstatic class member functions that appear within a
7839     //   member-specification of a class declaration; see 10.3.
7840     //
7841     if (isVirtual && !NewFD->isInvalidDecl()) {
7842       if (!isVirtualOkay) {
7843         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7844              diag::err_virtual_non_function);
7845       } else if (!CurContext->isRecord()) {
7846         // 'virtual' was specified outside of the class.
7847         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7848              diag::err_virtual_out_of_class)
7849           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7850       } else if (NewFD->getDescribedFunctionTemplate()) {
7851         // C++ [temp.mem]p3:
7852         //  A member function template shall not be virtual.
7853         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7854              diag::err_virtual_member_function_template)
7855           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7856       } else {
7857         // Okay: Add virtual to the method.
7858         NewFD->setVirtualAsWritten(true);
7859       }
7860 
7861       if (getLangOpts().CPlusPlus14 &&
7862           NewFD->getReturnType()->isUndeducedType())
7863         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7864     }
7865 
7866     if (getLangOpts().CPlusPlus14 &&
7867         (NewFD->isDependentContext() ||
7868          (isFriend && CurContext->isDependentContext())) &&
7869         NewFD->getReturnType()->isUndeducedType()) {
7870       // If the function template is referenced directly (for instance, as a
7871       // member of the current instantiation), pretend it has a dependent type.
7872       // This is not really justified by the standard, but is the only sane
7873       // thing to do.
7874       // FIXME: For a friend function, we have not marked the function as being
7875       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7876       const FunctionProtoType *FPT =
7877           NewFD->getType()->castAs<FunctionProtoType>();
7878       QualType Result =
7879           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7880       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7881                                              FPT->getExtProtoInfo()));
7882     }
7883 
7884     // C++ [dcl.fct.spec]p3:
7885     //  The inline specifier shall not appear on a block scope function
7886     //  declaration.
7887     if (isInline && !NewFD->isInvalidDecl()) {
7888       if (CurContext->isFunctionOrMethod()) {
7889         // 'inline' is not allowed on block scope function declaration.
7890         Diag(D.getDeclSpec().getInlineSpecLoc(),
7891              diag::err_inline_declaration_block_scope) << Name
7892           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7893       }
7894     }
7895 
7896     // C++ [dcl.fct.spec]p6:
7897     //  The explicit specifier shall be used only in the declaration of a
7898     //  constructor or conversion function within its class definition;
7899     //  see 12.3.1 and 12.3.2.
7900     if (isExplicit && !NewFD->isInvalidDecl()) {
7901       if (!CurContext->isRecord()) {
7902         // 'explicit' was specified outside of the class.
7903         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7904              diag::err_explicit_out_of_class)
7905           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7906       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7907                  !isa<CXXConversionDecl>(NewFD)) {
7908         // 'explicit' was specified on a function that wasn't a constructor
7909         // or conversion function.
7910         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7911              diag::err_explicit_non_ctor_or_conv_function)
7912           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7913       }
7914     }
7915 
7916     if (isConstexpr) {
7917       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7918       // are implicitly inline.
7919       NewFD->setImplicitlyInline();
7920 
7921       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7922       // be either constructors or to return a literal type. Therefore,
7923       // destructors cannot be declared constexpr.
7924       if (isa<CXXDestructorDecl>(NewFD))
7925         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7926     }
7927 
7928     if (isConcept) {
7929       // This is a function concept.
7930       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7931         FTD->setConcept();
7932 
7933       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7934       // applied only to the definition of a function template [...]
7935       if (!D.isFunctionDefinition()) {
7936         Diag(D.getDeclSpec().getConceptSpecLoc(),
7937              diag::err_function_concept_not_defined);
7938         NewFD->setInvalidDecl();
7939       }
7940 
7941       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7942       // have no exception-specification and is treated as if it were specified
7943       // with noexcept(true) (15.4). [...]
7944       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7945         if (FPT->hasExceptionSpec()) {
7946           SourceRange Range;
7947           if (D.isFunctionDeclarator())
7948             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7949           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7950               << FixItHint::CreateRemoval(Range);
7951           NewFD->setInvalidDecl();
7952         } else {
7953           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7954         }
7955 
7956         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7957         // following restrictions:
7958         // - The declared return type shall have the type bool.
7959         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7960           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7961           NewFD->setInvalidDecl();
7962         }
7963 
7964         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7965         // following restrictions:
7966         // - The declaration's parameter list shall be equivalent to an empty
7967         //   parameter list.
7968         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7969           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7970       }
7971 
7972       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7973       // implicity defined to be a constexpr declaration (implicitly inline)
7974       NewFD->setImplicitlyInline();
7975 
7976       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7977       // be declared with the thread_local, inline, friend, or constexpr
7978       // specifiers, [...]
7979       if (isInline) {
7980         Diag(D.getDeclSpec().getInlineSpecLoc(),
7981              diag::err_concept_decl_invalid_specifiers)
7982             << 1 << 1;
7983         NewFD->setInvalidDecl(true);
7984       }
7985 
7986       if (isFriend) {
7987         Diag(D.getDeclSpec().getFriendSpecLoc(),
7988              diag::err_concept_decl_invalid_specifiers)
7989             << 1 << 2;
7990         NewFD->setInvalidDecl(true);
7991       }
7992 
7993       if (isConstexpr) {
7994         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7995              diag::err_concept_decl_invalid_specifiers)
7996             << 1 << 3;
7997         NewFD->setInvalidDecl(true);
7998       }
7999 
8000       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8001       // applied only to the definition of a function template or variable
8002       // template, declared in namespace scope.
8003       if (isFunctionTemplateSpecialization) {
8004         Diag(D.getDeclSpec().getConceptSpecLoc(),
8005              diag::err_concept_specified_specialization) << 1;
8006         NewFD->setInvalidDecl(true);
8007         return NewFD;
8008       }
8009     }
8010 
8011     // If __module_private__ was specified, mark the function accordingly.
8012     if (D.getDeclSpec().isModulePrivateSpecified()) {
8013       if (isFunctionTemplateSpecialization) {
8014         SourceLocation ModulePrivateLoc
8015           = D.getDeclSpec().getModulePrivateSpecLoc();
8016         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8017           << 0
8018           << FixItHint::CreateRemoval(ModulePrivateLoc);
8019       } else {
8020         NewFD->setModulePrivate();
8021         if (FunctionTemplate)
8022           FunctionTemplate->setModulePrivate();
8023       }
8024     }
8025 
8026     if (isFriend) {
8027       if (FunctionTemplate) {
8028         FunctionTemplate->setObjectOfFriendDecl();
8029         FunctionTemplate->setAccess(AS_public);
8030       }
8031       NewFD->setObjectOfFriendDecl();
8032       NewFD->setAccess(AS_public);
8033     }
8034 
8035     // If a function is defined as defaulted or deleted, mark it as such now.
8036     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8037     // definition kind to FDK_Definition.
8038     switch (D.getFunctionDefinitionKind()) {
8039       case FDK_Declaration:
8040       case FDK_Definition:
8041         break;
8042 
8043       case FDK_Defaulted:
8044         NewFD->setDefaulted();
8045         break;
8046 
8047       case FDK_Deleted:
8048         NewFD->setDeletedAsWritten();
8049         break;
8050     }
8051 
8052     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8053         D.isFunctionDefinition()) {
8054       // C++ [class.mfct]p2:
8055       //   A member function may be defined (8.4) in its class definition, in
8056       //   which case it is an inline member function (7.1.2)
8057       NewFD->setImplicitlyInline();
8058     }
8059 
8060     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8061         !CurContext->isRecord()) {
8062       // C++ [class.static]p1:
8063       //   A data or function member of a class may be declared static
8064       //   in a class definition, in which case it is a static member of
8065       //   the class.
8066 
8067       // Complain about the 'static' specifier if it's on an out-of-line
8068       // member function definition.
8069       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8070            diag::err_static_out_of_line)
8071         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8072     }
8073 
8074     // C++11 [except.spec]p15:
8075     //   A deallocation function with no exception-specification is treated
8076     //   as if it were specified with noexcept(true).
8077     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8078     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8079          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8080         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8081       NewFD->setType(Context.getFunctionType(
8082           FPT->getReturnType(), FPT->getParamTypes(),
8083           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8084   }
8085 
8086   // Filter out previous declarations that don't match the scope.
8087   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8088                        D.getCXXScopeSpec().isNotEmpty() ||
8089                        isExplicitSpecialization ||
8090                        isFunctionTemplateSpecialization);
8091 
8092   // Handle GNU asm-label extension (encoded as an attribute).
8093   if (Expr *E = (Expr*) D.getAsmLabel()) {
8094     // The parser guarantees this is a string.
8095     StringLiteral *SE = cast<StringLiteral>(E);
8096     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8097                                                 SE->getString(), 0));
8098   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8099     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8100       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8101     if (I != ExtnameUndeclaredIdentifiers.end()) {
8102       if (isDeclExternC(NewFD)) {
8103         NewFD->addAttr(I->second);
8104         ExtnameUndeclaredIdentifiers.erase(I);
8105       } else
8106         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8107             << /*Variable*/0 << NewFD;
8108     }
8109   }
8110 
8111   // Copy the parameter declarations from the declarator D to the function
8112   // declaration NewFD, if they are available.  First scavenge them into Params.
8113   SmallVector<ParmVarDecl*, 16> Params;
8114   if (D.isFunctionDeclarator()) {
8115     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8116 
8117     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8118     // function that takes no arguments, not a function that takes a
8119     // single void argument.
8120     // We let through "const void" here because Sema::GetTypeForDeclarator
8121     // already checks for that case.
8122     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8123       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8124         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8125         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8126         Param->setDeclContext(NewFD);
8127         Params.push_back(Param);
8128 
8129         if (Param->isInvalidDecl())
8130           NewFD->setInvalidDecl();
8131       }
8132     }
8133   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8134     // When we're declaring a function with a typedef, typeof, etc as in the
8135     // following example, we'll need to synthesize (unnamed)
8136     // parameters for use in the declaration.
8137     //
8138     // @code
8139     // typedef void fn(int);
8140     // fn f;
8141     // @endcode
8142 
8143     // Synthesize a parameter for each argument type.
8144     for (const auto &AI : FT->param_types()) {
8145       ParmVarDecl *Param =
8146           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8147       Param->setScopeInfo(0, Params.size());
8148       Params.push_back(Param);
8149     }
8150   } else {
8151     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8152            "Should not need args for typedef of non-prototype fn");
8153   }
8154 
8155   // Finally, we know we have the right number of parameters, install them.
8156   NewFD->setParams(Params);
8157 
8158   // Find all anonymous symbols defined during the declaration of this function
8159   // and add to NewFD. This lets us track decls such 'enum Y' in:
8160   //
8161   //   void f(enum Y {AA} x) {}
8162   //
8163   // which would otherwise incorrectly end up in the translation unit scope.
8164   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8165   DeclsInPrototypeScope.clear();
8166 
8167   if (D.getDeclSpec().isNoreturnSpecified())
8168     NewFD->addAttr(
8169         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8170                                        Context, 0));
8171 
8172   // Functions returning a variably modified type violate C99 6.7.5.2p2
8173   // because all functions have linkage.
8174   if (!NewFD->isInvalidDecl() &&
8175       NewFD->getReturnType()->isVariablyModifiedType()) {
8176     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8177     NewFD->setInvalidDecl();
8178   }
8179 
8180   // Apply an implicit SectionAttr if #pragma code_seg is active.
8181   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8182       !NewFD->hasAttr<SectionAttr>()) {
8183     NewFD->addAttr(
8184         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8185                                     CodeSegStack.CurrentValue->getString(),
8186                                     CodeSegStack.CurrentPragmaLocation));
8187     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8188                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8189                          ASTContext::PSF_Read,
8190                      NewFD))
8191       NewFD->dropAttr<SectionAttr>();
8192   }
8193 
8194   // Handle attributes.
8195   ProcessDeclAttributes(S, NewFD, D);
8196 
8197   if (getLangOpts().CUDA)
8198     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8199 
8200   if (getLangOpts().OpenCL) {
8201     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8202     // type declaration will generate a compilation error.
8203     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8204     if (AddressSpace == LangAS::opencl_local ||
8205         AddressSpace == LangAS::opencl_global ||
8206         AddressSpace == LangAS::opencl_constant) {
8207       Diag(NewFD->getLocation(),
8208            diag::err_opencl_return_value_with_address_space);
8209       NewFD->setInvalidDecl();
8210     }
8211   }
8212 
8213   if (!getLangOpts().CPlusPlus) {
8214     // Perform semantic checking on the function declaration.
8215     bool isExplicitSpecialization=false;
8216     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8217       CheckMain(NewFD, D.getDeclSpec());
8218 
8219     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8220       CheckMSVCRTEntryPoint(NewFD);
8221 
8222     if (!NewFD->isInvalidDecl())
8223       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8224                                                   isExplicitSpecialization));
8225     else if (!Previous.empty())
8226       // Recover gracefully from an invalid redeclaration.
8227       D.setRedeclaration(true);
8228     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8229             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8230            "previous declaration set still overloaded");
8231 
8232     // Diagnose no-prototype function declarations with calling conventions that
8233     // don't support variadic calls. Only do this in C and do it after merging
8234     // possibly prototyped redeclarations.
8235     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8236     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8237       CallingConv CC = FT->getExtInfo().getCC();
8238       if (!supportsVariadicCall(CC)) {
8239         // Windows system headers sometimes accidentally use stdcall without
8240         // (void) parameters, so we relax this to a warning.
8241         int DiagID =
8242             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8243         Diag(NewFD->getLocation(), DiagID)
8244             << FunctionType::getNameForCallConv(CC);
8245       }
8246     }
8247   } else {
8248     // C++11 [replacement.functions]p3:
8249     //  The program's definitions shall not be specified as inline.
8250     //
8251     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8252     //
8253     // Suppress the diagnostic if the function is __attribute__((used)), since
8254     // that forces an external definition to be emitted.
8255     if (D.getDeclSpec().isInlineSpecified() &&
8256         NewFD->isReplaceableGlobalAllocationFunction() &&
8257         !NewFD->hasAttr<UsedAttr>())
8258       Diag(D.getDeclSpec().getInlineSpecLoc(),
8259            diag::ext_operator_new_delete_declared_inline)
8260         << NewFD->getDeclName();
8261 
8262     // If the declarator is a template-id, translate the parser's template
8263     // argument list into our AST format.
8264     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8265       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8266       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8267       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8268       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8269                                          TemplateId->NumArgs);
8270       translateTemplateArguments(TemplateArgsPtr,
8271                                  TemplateArgs);
8272 
8273       HasExplicitTemplateArgs = true;
8274 
8275       if (NewFD->isInvalidDecl()) {
8276         HasExplicitTemplateArgs = false;
8277       } else if (FunctionTemplate) {
8278         // Function template with explicit template arguments.
8279         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8280           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8281 
8282         HasExplicitTemplateArgs = false;
8283       } else {
8284         assert((isFunctionTemplateSpecialization ||
8285                 D.getDeclSpec().isFriendSpecified()) &&
8286                "should have a 'template<>' for this decl");
8287         // "friend void foo<>(int);" is an implicit specialization decl.
8288         isFunctionTemplateSpecialization = true;
8289       }
8290     } else if (isFriend && isFunctionTemplateSpecialization) {
8291       // This combination is only possible in a recovery case;  the user
8292       // wrote something like:
8293       //   template <> friend void foo(int);
8294       // which we're recovering from as if the user had written:
8295       //   friend void foo<>(int);
8296       // Go ahead and fake up a template id.
8297       HasExplicitTemplateArgs = true;
8298       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8299       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8300     }
8301 
8302     // If it's a friend (and only if it's a friend), it's possible
8303     // that either the specialized function type or the specialized
8304     // template is dependent, and therefore matching will fail.  In
8305     // this case, don't check the specialization yet.
8306     bool InstantiationDependent = false;
8307     if (isFunctionTemplateSpecialization && isFriend &&
8308         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8309          TemplateSpecializationType::anyDependentTemplateArguments(
8310             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8311             InstantiationDependent))) {
8312       assert(HasExplicitTemplateArgs &&
8313              "friend function specialization without template args");
8314       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8315                                                        Previous))
8316         NewFD->setInvalidDecl();
8317     } else if (isFunctionTemplateSpecialization) {
8318       if (CurContext->isDependentContext() && CurContext->isRecord()
8319           && !isFriend) {
8320         isDependentClassScopeExplicitSpecialization = true;
8321         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8322           diag::ext_function_specialization_in_class :
8323           diag::err_function_specialization_in_class)
8324           << NewFD->getDeclName();
8325       } else if (CheckFunctionTemplateSpecialization(NewFD,
8326                                   (HasExplicitTemplateArgs ? &TemplateArgs
8327                                                            : nullptr),
8328                                                      Previous))
8329         NewFD->setInvalidDecl();
8330 
8331       // C++ [dcl.stc]p1:
8332       //   A storage-class-specifier shall not be specified in an explicit
8333       //   specialization (14.7.3)
8334       FunctionTemplateSpecializationInfo *Info =
8335           NewFD->getTemplateSpecializationInfo();
8336       if (Info && SC != SC_None) {
8337         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8338           Diag(NewFD->getLocation(),
8339                diag::err_explicit_specialization_inconsistent_storage_class)
8340             << SC
8341             << FixItHint::CreateRemoval(
8342                                       D.getDeclSpec().getStorageClassSpecLoc());
8343 
8344         else
8345           Diag(NewFD->getLocation(),
8346                diag::ext_explicit_specialization_storage_class)
8347             << FixItHint::CreateRemoval(
8348                                       D.getDeclSpec().getStorageClassSpecLoc());
8349       }
8350     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8351       if (CheckMemberSpecialization(NewFD, Previous))
8352           NewFD->setInvalidDecl();
8353     }
8354 
8355     // Perform semantic checking on the function declaration.
8356     if (!isDependentClassScopeExplicitSpecialization) {
8357       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8358         CheckMain(NewFD, D.getDeclSpec());
8359 
8360       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8361         CheckMSVCRTEntryPoint(NewFD);
8362 
8363       if (!NewFD->isInvalidDecl())
8364         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8365                                                     isExplicitSpecialization));
8366       else if (!Previous.empty())
8367         // Recover gracefully from an invalid redeclaration.
8368         D.setRedeclaration(true);
8369     }
8370 
8371     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8372             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8373            "previous declaration set still overloaded");
8374 
8375     NamedDecl *PrincipalDecl = (FunctionTemplate
8376                                 ? cast<NamedDecl>(FunctionTemplate)
8377                                 : NewFD);
8378 
8379     if (isFriend && D.isRedeclaration()) {
8380       AccessSpecifier Access = AS_public;
8381       if (!NewFD->isInvalidDecl())
8382         Access = NewFD->getPreviousDecl()->getAccess();
8383 
8384       NewFD->setAccess(Access);
8385       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8386     }
8387 
8388     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8389         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8390       PrincipalDecl->setNonMemberOperator();
8391 
8392     // If we have a function template, check the template parameter
8393     // list. This will check and merge default template arguments.
8394     if (FunctionTemplate) {
8395       FunctionTemplateDecl *PrevTemplate =
8396                                      FunctionTemplate->getPreviousDecl();
8397       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8398                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8399                                     : nullptr,
8400                             D.getDeclSpec().isFriendSpecified()
8401                               ? (D.isFunctionDefinition()
8402                                    ? TPC_FriendFunctionTemplateDefinition
8403                                    : TPC_FriendFunctionTemplate)
8404                               : (D.getCXXScopeSpec().isSet() &&
8405                                  DC && DC->isRecord() &&
8406                                  DC->isDependentContext())
8407                                   ? TPC_ClassTemplateMember
8408                                   : TPC_FunctionTemplate);
8409     }
8410 
8411     if (NewFD->isInvalidDecl()) {
8412       // Ignore all the rest of this.
8413     } else if (!D.isRedeclaration()) {
8414       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8415                                        AddToScope };
8416       // Fake up an access specifier if it's supposed to be a class member.
8417       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8418         NewFD->setAccess(AS_public);
8419 
8420       // Qualified decls generally require a previous declaration.
8421       if (D.getCXXScopeSpec().isSet()) {
8422         // ...with the major exception of templated-scope or
8423         // dependent-scope friend declarations.
8424 
8425         // TODO: we currently also suppress this check in dependent
8426         // contexts because (1) the parameter depth will be off when
8427         // matching friend templates and (2) we might actually be
8428         // selecting a friend based on a dependent factor.  But there
8429         // are situations where these conditions don't apply and we
8430         // can actually do this check immediately.
8431         if (isFriend &&
8432             (TemplateParamLists.size() ||
8433              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8434              CurContext->isDependentContext())) {
8435           // ignore these
8436         } else {
8437           // The user tried to provide an out-of-line definition for a
8438           // function that is a member of a class or namespace, but there
8439           // was no such member function declared (C++ [class.mfct]p2,
8440           // C++ [namespace.memdef]p2). For example:
8441           //
8442           // class X {
8443           //   void f() const;
8444           // };
8445           //
8446           // void X::f() { } // ill-formed
8447           //
8448           // Complain about this problem, and attempt to suggest close
8449           // matches (e.g., those that differ only in cv-qualifiers and
8450           // whether the parameter types are references).
8451 
8452           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8453                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8454             AddToScope = ExtraArgs.AddToScope;
8455             return Result;
8456           }
8457         }
8458 
8459         // Unqualified local friend declarations are required to resolve
8460         // to something.
8461       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8462         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8463                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8464           AddToScope = ExtraArgs.AddToScope;
8465           return Result;
8466         }
8467       }
8468     } else if (!D.isFunctionDefinition() &&
8469                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8470                !isFriend && !isFunctionTemplateSpecialization &&
8471                !isExplicitSpecialization) {
8472       // An out-of-line member function declaration must also be a
8473       // definition (C++ [class.mfct]p2).
8474       // Note that this is not the case for explicit specializations of
8475       // function templates or member functions of class templates, per
8476       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8477       // extension for compatibility with old SWIG code which likes to
8478       // generate them.
8479       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8480         << D.getCXXScopeSpec().getRange();
8481     }
8482   }
8483 
8484   ProcessPragmaWeak(S, NewFD);
8485   checkAttributesAfterMerging(*this, *NewFD);
8486 
8487   AddKnownFunctionAttributes(NewFD);
8488 
8489   if (NewFD->hasAttr<OverloadableAttr>() &&
8490       !NewFD->getType()->getAs<FunctionProtoType>()) {
8491     Diag(NewFD->getLocation(),
8492          diag::err_attribute_overloadable_no_prototype)
8493       << NewFD;
8494 
8495     // Turn this into a variadic function with no parameters.
8496     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8497     FunctionProtoType::ExtProtoInfo EPI(
8498         Context.getDefaultCallingConvention(true, false));
8499     EPI.Variadic = true;
8500     EPI.ExtInfo = FT->getExtInfo();
8501 
8502     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8503     NewFD->setType(R);
8504   }
8505 
8506   // If there's a #pragma GCC visibility in scope, and this isn't a class
8507   // member, set the visibility of this function.
8508   if (!DC->isRecord() && NewFD->isExternallyVisible())
8509     AddPushedVisibilityAttribute(NewFD);
8510 
8511   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8512   // marking the function.
8513   AddCFAuditedAttribute(NewFD);
8514 
8515   // If this is a function definition, check if we have to apply optnone due to
8516   // a pragma.
8517   if(D.isFunctionDefinition())
8518     AddRangeBasedOptnone(NewFD);
8519 
8520   // If this is the first declaration of an extern C variable, update
8521   // the map of such variables.
8522   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8523       isIncompleteDeclExternC(*this, NewFD))
8524     RegisterLocallyScopedExternCDecl(NewFD, S);
8525 
8526   // Set this FunctionDecl's range up to the right paren.
8527   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8528 
8529   if (D.isRedeclaration() && !Previous.empty()) {
8530     checkDLLAttributeRedeclaration(
8531         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8532         isExplicitSpecialization || isFunctionTemplateSpecialization,
8533         D.isFunctionDefinition());
8534   }
8535 
8536   if (getLangOpts().CUDA) {
8537     IdentifierInfo *II = NewFD->getIdentifier();
8538     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8539         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8540       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8541         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8542 
8543       Context.setcudaConfigureCallDecl(NewFD);
8544     }
8545 
8546     // Variadic functions, other than a *declaration* of printf, are not allowed
8547     // in device-side CUDA code, unless someone passed
8548     // -fcuda-allow-variadic-functions.
8549     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8550         (NewFD->hasAttr<CUDADeviceAttr>() ||
8551          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8552         !(II && II->isStr("printf") && NewFD->isExternC() &&
8553           !D.isFunctionDefinition())) {
8554       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8555     }
8556   }
8557 
8558   if (getLangOpts().CPlusPlus) {
8559     if (FunctionTemplate) {
8560       if (NewFD->isInvalidDecl())
8561         FunctionTemplate->setInvalidDecl();
8562       return FunctionTemplate;
8563     }
8564   }
8565 
8566   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8567     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8568     if ((getLangOpts().OpenCLVersion >= 120)
8569         && (SC == SC_Static)) {
8570       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8571       D.setInvalidType();
8572     }
8573 
8574     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8575     if (!NewFD->getReturnType()->isVoidType()) {
8576       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8577       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8578           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8579                                 : FixItHint());
8580       D.setInvalidType();
8581     }
8582 
8583     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8584     for (auto Param : NewFD->parameters())
8585       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8586   }
8587   for (const ParmVarDecl *Param : NewFD->parameters()) {
8588     QualType PT = Param->getType();
8589 
8590     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8591     // types.
8592     if (getLangOpts().OpenCLVersion >= 200) {
8593       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8594         QualType ElemTy = PipeTy->getElementType();
8595           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8596             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8597             D.setInvalidType();
8598           }
8599       }
8600     }
8601   }
8602 
8603   MarkUnusedFileScopedDecl(NewFD);
8604 
8605   // Here we have an function template explicit specialization at class scope.
8606   // The actually specialization will be postponed to template instatiation
8607   // time via the ClassScopeFunctionSpecializationDecl node.
8608   if (isDependentClassScopeExplicitSpecialization) {
8609     ClassScopeFunctionSpecializationDecl *NewSpec =
8610                          ClassScopeFunctionSpecializationDecl::Create(
8611                                 Context, CurContext, SourceLocation(),
8612                                 cast<CXXMethodDecl>(NewFD),
8613                                 HasExplicitTemplateArgs, TemplateArgs);
8614     CurContext->addDecl(NewSpec);
8615     AddToScope = false;
8616   }
8617 
8618   return NewFD;
8619 }
8620 
8621 /// \brief Perform semantic checking of a new function declaration.
8622 ///
8623 /// Performs semantic analysis of the new function declaration
8624 /// NewFD. This routine performs all semantic checking that does not
8625 /// require the actual declarator involved in the declaration, and is
8626 /// used both for the declaration of functions as they are parsed
8627 /// (called via ActOnDeclarator) and for the declaration of functions
8628 /// that have been instantiated via C++ template instantiation (called
8629 /// via InstantiateDecl).
8630 ///
8631 /// \param IsExplicitSpecialization whether this new function declaration is
8632 /// an explicit specialization of the previous declaration.
8633 ///
8634 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8635 ///
8636 /// \returns true if the function declaration is a redeclaration.
8637 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8638                                     LookupResult &Previous,
8639                                     bool IsExplicitSpecialization) {
8640   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8641          "Variably modified return types are not handled here");
8642 
8643   // Determine whether the type of this function should be merged with
8644   // a previous visible declaration. This never happens for functions in C++,
8645   // and always happens in C if the previous declaration was visible.
8646   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8647                                !Previous.isShadowed();
8648 
8649   bool Redeclaration = false;
8650   NamedDecl *OldDecl = nullptr;
8651 
8652   // Merge or overload the declaration with an existing declaration of
8653   // the same name, if appropriate.
8654   if (!Previous.empty()) {
8655     // Determine whether NewFD is an overload of PrevDecl or
8656     // a declaration that requires merging. If it's an overload,
8657     // there's no more work to do here; we'll just add the new
8658     // function to the scope.
8659     if (!AllowOverloadingOfFunction(Previous, Context)) {
8660       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8661       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8662         Redeclaration = true;
8663         OldDecl = Candidate;
8664       }
8665     } else {
8666       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8667                             /*NewIsUsingDecl*/ false)) {
8668       case Ovl_Match:
8669         Redeclaration = true;
8670         break;
8671 
8672       case Ovl_NonFunction:
8673         Redeclaration = true;
8674         break;
8675 
8676       case Ovl_Overload:
8677         Redeclaration = false;
8678         break;
8679       }
8680 
8681       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8682         // If a function name is overloadable in C, then every function
8683         // with that name must be marked "overloadable".
8684         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8685           << Redeclaration << NewFD;
8686         NamedDecl *OverloadedDecl = nullptr;
8687         if (Redeclaration)
8688           OverloadedDecl = OldDecl;
8689         else if (!Previous.empty())
8690           OverloadedDecl = Previous.getRepresentativeDecl();
8691         if (OverloadedDecl)
8692           Diag(OverloadedDecl->getLocation(),
8693                diag::note_attribute_overloadable_prev_overload);
8694         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8695       }
8696     }
8697   }
8698 
8699   // Check for a previous extern "C" declaration with this name.
8700   if (!Redeclaration &&
8701       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8702     if (!Previous.empty()) {
8703       // This is an extern "C" declaration with the same name as a previous
8704       // declaration, and thus redeclares that entity...
8705       Redeclaration = true;
8706       OldDecl = Previous.getFoundDecl();
8707       MergeTypeWithPrevious = false;
8708 
8709       // ... except in the presence of __attribute__((overloadable)).
8710       if (OldDecl->hasAttr<OverloadableAttr>()) {
8711         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8712           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8713             << Redeclaration << NewFD;
8714           Diag(Previous.getFoundDecl()->getLocation(),
8715                diag::note_attribute_overloadable_prev_overload);
8716           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8717         }
8718         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8719           Redeclaration = false;
8720           OldDecl = nullptr;
8721         }
8722       }
8723     }
8724   }
8725 
8726   // C++11 [dcl.constexpr]p8:
8727   //   A constexpr specifier for a non-static member function that is not
8728   //   a constructor declares that member function to be const.
8729   //
8730   // This needs to be delayed until we know whether this is an out-of-line
8731   // definition of a static member function.
8732   //
8733   // This rule is not present in C++1y, so we produce a backwards
8734   // compatibility warning whenever it happens in C++11.
8735   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8736   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8737       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8738       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8739     CXXMethodDecl *OldMD = nullptr;
8740     if (OldDecl)
8741       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8742     if (!OldMD || !OldMD->isStatic()) {
8743       const FunctionProtoType *FPT =
8744         MD->getType()->castAs<FunctionProtoType>();
8745       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8746       EPI.TypeQuals |= Qualifiers::Const;
8747       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8748                                           FPT->getParamTypes(), EPI));
8749 
8750       // Warn that we did this, if we're not performing template instantiation.
8751       // In that case, we'll have warned already when the template was defined.
8752       if (ActiveTemplateInstantiations.empty()) {
8753         SourceLocation AddConstLoc;
8754         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8755                 .IgnoreParens().getAs<FunctionTypeLoc>())
8756           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8757 
8758         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8759           << FixItHint::CreateInsertion(AddConstLoc, " const");
8760       }
8761     }
8762   }
8763 
8764   if (Redeclaration) {
8765     // NewFD and OldDecl represent declarations that need to be
8766     // merged.
8767     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8768       NewFD->setInvalidDecl();
8769       return Redeclaration;
8770     }
8771 
8772     Previous.clear();
8773     Previous.addDecl(OldDecl);
8774 
8775     if (FunctionTemplateDecl *OldTemplateDecl
8776                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8777       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8778       FunctionTemplateDecl *NewTemplateDecl
8779         = NewFD->getDescribedFunctionTemplate();
8780       assert(NewTemplateDecl && "Template/non-template mismatch");
8781       if (CXXMethodDecl *Method
8782             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8783         Method->setAccess(OldTemplateDecl->getAccess());
8784         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8785       }
8786 
8787       // If this is an explicit specialization of a member that is a function
8788       // template, mark it as a member specialization.
8789       if (IsExplicitSpecialization &&
8790           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8791         NewTemplateDecl->setMemberSpecialization();
8792         assert(OldTemplateDecl->isMemberSpecialization());
8793         // Explicit specializations of a member template do not inherit deleted
8794         // status from the parent member template that they are specializing.
8795         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8796           FunctionDecl *const OldTemplatedDecl =
8797               OldTemplateDecl->getTemplatedDecl();
8798           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8799           OldTemplatedDecl->setDeletedAsWritten(false);
8800         }
8801       }
8802 
8803     } else {
8804       // This needs to happen first so that 'inline' propagates.
8805       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8806 
8807       if (isa<CXXMethodDecl>(NewFD))
8808         NewFD->setAccess(OldDecl->getAccess());
8809     }
8810   }
8811 
8812   // Semantic checking for this function declaration (in isolation).
8813 
8814   if (getLangOpts().CPlusPlus) {
8815     // C++-specific checks.
8816     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8817       CheckConstructor(Constructor);
8818     } else if (CXXDestructorDecl *Destructor =
8819                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8820       CXXRecordDecl *Record = Destructor->getParent();
8821       QualType ClassType = Context.getTypeDeclType(Record);
8822 
8823       // FIXME: Shouldn't we be able to perform this check even when the class
8824       // type is dependent? Both gcc and edg can handle that.
8825       if (!ClassType->isDependentType()) {
8826         DeclarationName Name
8827           = Context.DeclarationNames.getCXXDestructorName(
8828                                         Context.getCanonicalType(ClassType));
8829         if (NewFD->getDeclName() != Name) {
8830           Diag(NewFD->getLocation(), diag::err_destructor_name);
8831           NewFD->setInvalidDecl();
8832           return Redeclaration;
8833         }
8834       }
8835     } else if (CXXConversionDecl *Conversion
8836                = dyn_cast<CXXConversionDecl>(NewFD)) {
8837       ActOnConversionDeclarator(Conversion);
8838     }
8839 
8840     // Find any virtual functions that this function overrides.
8841     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8842       if (!Method->isFunctionTemplateSpecialization() &&
8843           !Method->getDescribedFunctionTemplate() &&
8844           Method->isCanonicalDecl()) {
8845         if (AddOverriddenMethods(Method->getParent(), Method)) {
8846           // If the function was marked as "static", we have a problem.
8847           if (NewFD->getStorageClass() == SC_Static) {
8848             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8849           }
8850         }
8851       }
8852 
8853       if (Method->isStatic())
8854         checkThisInStaticMemberFunctionType(Method);
8855     }
8856 
8857     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8858     if (NewFD->isOverloadedOperator() &&
8859         CheckOverloadedOperatorDeclaration(NewFD)) {
8860       NewFD->setInvalidDecl();
8861       return Redeclaration;
8862     }
8863 
8864     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8865     if (NewFD->getLiteralIdentifier() &&
8866         CheckLiteralOperatorDeclaration(NewFD)) {
8867       NewFD->setInvalidDecl();
8868       return Redeclaration;
8869     }
8870 
8871     // In C++, check default arguments now that we have merged decls. Unless
8872     // the lexical context is the class, because in this case this is done
8873     // during delayed parsing anyway.
8874     if (!CurContext->isRecord())
8875       CheckCXXDefaultArguments(NewFD);
8876 
8877     // If this function declares a builtin function, check the type of this
8878     // declaration against the expected type for the builtin.
8879     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8880       ASTContext::GetBuiltinTypeError Error;
8881       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8882       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8883       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8884         // The type of this function differs from the type of the builtin,
8885         // so forget about the builtin entirely.
8886         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8887       }
8888     }
8889 
8890     // If this function is declared as being extern "C", then check to see if
8891     // the function returns a UDT (class, struct, or union type) that is not C
8892     // compatible, and if it does, warn the user.
8893     // But, issue any diagnostic on the first declaration only.
8894     if (Previous.empty() && NewFD->isExternC()) {
8895       QualType R = NewFD->getReturnType();
8896       if (R->isIncompleteType() && !R->isVoidType())
8897         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8898             << NewFD << R;
8899       else if (!R.isPODType(Context) && !R->isVoidType() &&
8900                !R->isObjCObjectPointerType())
8901         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8902     }
8903   }
8904   return Redeclaration;
8905 }
8906 
8907 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8908   // C++11 [basic.start.main]p3:
8909   //   A program that [...] declares main to be inline, static or
8910   //   constexpr is ill-formed.
8911   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8912   //   appear in a declaration of main.
8913   // static main is not an error under C99, but we should warn about it.
8914   // We accept _Noreturn main as an extension.
8915   if (FD->getStorageClass() == SC_Static)
8916     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8917          ? diag::err_static_main : diag::warn_static_main)
8918       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8919   if (FD->isInlineSpecified())
8920     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8921       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8922   if (DS.isNoreturnSpecified()) {
8923     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8924     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8925     Diag(NoreturnLoc, diag::ext_noreturn_main);
8926     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8927       << FixItHint::CreateRemoval(NoreturnRange);
8928   }
8929   if (FD->isConstexpr()) {
8930     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8931       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8932     FD->setConstexpr(false);
8933   }
8934 
8935   if (getLangOpts().OpenCL) {
8936     Diag(FD->getLocation(), diag::err_opencl_no_main)
8937         << FD->hasAttr<OpenCLKernelAttr>();
8938     FD->setInvalidDecl();
8939     return;
8940   }
8941 
8942   QualType T = FD->getType();
8943   assert(T->isFunctionType() && "function decl is not of function type");
8944   const FunctionType* FT = T->castAs<FunctionType>();
8945 
8946   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8947     // In C with GNU extensions we allow main() to have non-integer return
8948     // type, but we should warn about the extension, and we disable the
8949     // implicit-return-zero rule.
8950 
8951     // GCC in C mode accepts qualified 'int'.
8952     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8953       FD->setHasImplicitReturnZero(true);
8954     else {
8955       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8956       SourceRange RTRange = FD->getReturnTypeSourceRange();
8957       if (RTRange.isValid())
8958         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8959             << FixItHint::CreateReplacement(RTRange, "int");
8960     }
8961   } else {
8962     // In C and C++, main magically returns 0 if you fall off the end;
8963     // set the flag which tells us that.
8964     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8965 
8966     // All the standards say that main() should return 'int'.
8967     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8968       FD->setHasImplicitReturnZero(true);
8969     else {
8970       // Otherwise, this is just a flat-out error.
8971       SourceRange RTRange = FD->getReturnTypeSourceRange();
8972       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8973           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8974                                 : FixItHint());
8975       FD->setInvalidDecl(true);
8976     }
8977   }
8978 
8979   // Treat protoless main() as nullary.
8980   if (isa<FunctionNoProtoType>(FT)) return;
8981 
8982   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8983   unsigned nparams = FTP->getNumParams();
8984   assert(FD->getNumParams() == nparams);
8985 
8986   bool HasExtraParameters = (nparams > 3);
8987 
8988   if (FTP->isVariadic()) {
8989     Diag(FD->getLocation(), diag::ext_variadic_main);
8990     // FIXME: if we had information about the location of the ellipsis, we
8991     // could add a FixIt hint to remove it as a parameter.
8992   }
8993 
8994   // Darwin passes an undocumented fourth argument of type char**.  If
8995   // other platforms start sprouting these, the logic below will start
8996   // getting shifty.
8997   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8998     HasExtraParameters = false;
8999 
9000   if (HasExtraParameters) {
9001     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9002     FD->setInvalidDecl(true);
9003     nparams = 3;
9004   }
9005 
9006   // FIXME: a lot of the following diagnostics would be improved
9007   // if we had some location information about types.
9008 
9009   QualType CharPP =
9010     Context.getPointerType(Context.getPointerType(Context.CharTy));
9011   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9012 
9013   for (unsigned i = 0; i < nparams; ++i) {
9014     QualType AT = FTP->getParamType(i);
9015 
9016     bool mismatch = true;
9017 
9018     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9019       mismatch = false;
9020     else if (Expected[i] == CharPP) {
9021       // As an extension, the following forms are okay:
9022       //   char const **
9023       //   char const * const *
9024       //   char * const *
9025 
9026       QualifierCollector qs;
9027       const PointerType* PT;
9028       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9029           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9030           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9031                               Context.CharTy)) {
9032         qs.removeConst();
9033         mismatch = !qs.empty();
9034       }
9035     }
9036 
9037     if (mismatch) {
9038       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9039       // TODO: suggest replacing given type with expected type
9040       FD->setInvalidDecl(true);
9041     }
9042   }
9043 
9044   if (nparams == 1 && !FD->isInvalidDecl()) {
9045     Diag(FD->getLocation(), diag::warn_main_one_arg);
9046   }
9047 
9048   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9049     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9050     FD->setInvalidDecl();
9051   }
9052 }
9053 
9054 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9055   QualType T = FD->getType();
9056   assert(T->isFunctionType() && "function decl is not of function type");
9057   const FunctionType *FT = T->castAs<FunctionType>();
9058 
9059   // Set an implicit return of 'zero' if the function can return some integral,
9060   // enumeration, pointer or nullptr type.
9061   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9062       FT->getReturnType()->isAnyPointerType() ||
9063       FT->getReturnType()->isNullPtrType())
9064     // DllMain is exempt because a return value of zero means it failed.
9065     if (FD->getName() != "DllMain")
9066       FD->setHasImplicitReturnZero(true);
9067 
9068   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9069     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9070     FD->setInvalidDecl();
9071   }
9072 }
9073 
9074 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9075   // FIXME: Need strict checking.  In C89, we need to check for
9076   // any assignment, increment, decrement, function-calls, or
9077   // commas outside of a sizeof.  In C99, it's the same list,
9078   // except that the aforementioned are allowed in unevaluated
9079   // expressions.  Everything else falls under the
9080   // "may accept other forms of constant expressions" exception.
9081   // (We never end up here for C++, so the constant expression
9082   // rules there don't matter.)
9083   const Expr *Culprit;
9084   if (Init->isConstantInitializer(Context, false, &Culprit))
9085     return false;
9086   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9087     << Culprit->getSourceRange();
9088   return true;
9089 }
9090 
9091 namespace {
9092   // Visits an initialization expression to see if OrigDecl is evaluated in
9093   // its own initialization and throws a warning if it does.
9094   class SelfReferenceChecker
9095       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9096     Sema &S;
9097     Decl *OrigDecl;
9098     bool isRecordType;
9099     bool isPODType;
9100     bool isReferenceType;
9101 
9102     bool isInitList;
9103     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9104 
9105   public:
9106     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9107 
9108     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9109                                                     S(S), OrigDecl(OrigDecl) {
9110       isPODType = false;
9111       isRecordType = false;
9112       isReferenceType = false;
9113       isInitList = false;
9114       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9115         isPODType = VD->getType().isPODType(S.Context);
9116         isRecordType = VD->getType()->isRecordType();
9117         isReferenceType = VD->getType()->isReferenceType();
9118       }
9119     }
9120 
9121     // For most expressions, just call the visitor.  For initializer lists,
9122     // track the index of the field being initialized since fields are
9123     // initialized in order allowing use of previously initialized fields.
9124     void CheckExpr(Expr *E) {
9125       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9126       if (!InitList) {
9127         Visit(E);
9128         return;
9129       }
9130 
9131       // Track and increment the index here.
9132       isInitList = true;
9133       InitFieldIndex.push_back(0);
9134       for (auto Child : InitList->children()) {
9135         CheckExpr(cast<Expr>(Child));
9136         ++InitFieldIndex.back();
9137       }
9138       InitFieldIndex.pop_back();
9139     }
9140 
9141     // Returns true if MemberExpr is checked and no futher checking is needed.
9142     // Returns false if additional checking is required.
9143     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9144       llvm::SmallVector<FieldDecl*, 4> Fields;
9145       Expr *Base = E;
9146       bool ReferenceField = false;
9147 
9148       // Get the field memebers used.
9149       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9150         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9151         if (!FD)
9152           return false;
9153         Fields.push_back(FD);
9154         if (FD->getType()->isReferenceType())
9155           ReferenceField = true;
9156         Base = ME->getBase()->IgnoreParenImpCasts();
9157       }
9158 
9159       // Keep checking only if the base Decl is the same.
9160       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9161       if (!DRE || DRE->getDecl() != OrigDecl)
9162         return false;
9163 
9164       // A reference field can be bound to an unininitialized field.
9165       if (CheckReference && !ReferenceField)
9166         return true;
9167 
9168       // Convert FieldDecls to their index number.
9169       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9170       for (const FieldDecl *I : llvm::reverse(Fields))
9171         UsedFieldIndex.push_back(I->getFieldIndex());
9172 
9173       // See if a warning is needed by checking the first difference in index
9174       // numbers.  If field being used has index less than the field being
9175       // initialized, then the use is safe.
9176       for (auto UsedIter = UsedFieldIndex.begin(),
9177                 UsedEnd = UsedFieldIndex.end(),
9178                 OrigIter = InitFieldIndex.begin(),
9179                 OrigEnd = InitFieldIndex.end();
9180            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9181         if (*UsedIter < *OrigIter)
9182           return true;
9183         if (*UsedIter > *OrigIter)
9184           break;
9185       }
9186 
9187       // TODO: Add a different warning which will print the field names.
9188       HandleDeclRefExpr(DRE);
9189       return true;
9190     }
9191 
9192     // For most expressions, the cast is directly above the DeclRefExpr.
9193     // For conditional operators, the cast can be outside the conditional
9194     // operator if both expressions are DeclRefExpr's.
9195     void HandleValue(Expr *E) {
9196       E = E->IgnoreParens();
9197       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9198         HandleDeclRefExpr(DRE);
9199         return;
9200       }
9201 
9202       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9203         Visit(CO->getCond());
9204         HandleValue(CO->getTrueExpr());
9205         HandleValue(CO->getFalseExpr());
9206         return;
9207       }
9208 
9209       if (BinaryConditionalOperator *BCO =
9210               dyn_cast<BinaryConditionalOperator>(E)) {
9211         Visit(BCO->getCond());
9212         HandleValue(BCO->getFalseExpr());
9213         return;
9214       }
9215 
9216       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9217         HandleValue(OVE->getSourceExpr());
9218         return;
9219       }
9220 
9221       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9222         if (BO->getOpcode() == BO_Comma) {
9223           Visit(BO->getLHS());
9224           HandleValue(BO->getRHS());
9225           return;
9226         }
9227       }
9228 
9229       if (isa<MemberExpr>(E)) {
9230         if (isInitList) {
9231           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9232                                       false /*CheckReference*/))
9233             return;
9234         }
9235 
9236         Expr *Base = E->IgnoreParenImpCasts();
9237         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9238           // Check for static member variables and don't warn on them.
9239           if (!isa<FieldDecl>(ME->getMemberDecl()))
9240             return;
9241           Base = ME->getBase()->IgnoreParenImpCasts();
9242         }
9243         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9244           HandleDeclRefExpr(DRE);
9245         return;
9246       }
9247 
9248       Visit(E);
9249     }
9250 
9251     // Reference types not handled in HandleValue are handled here since all
9252     // uses of references are bad, not just r-value uses.
9253     void VisitDeclRefExpr(DeclRefExpr *E) {
9254       if (isReferenceType)
9255         HandleDeclRefExpr(E);
9256     }
9257 
9258     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9259       if (E->getCastKind() == CK_LValueToRValue) {
9260         HandleValue(E->getSubExpr());
9261         return;
9262       }
9263 
9264       Inherited::VisitImplicitCastExpr(E);
9265     }
9266 
9267     void VisitMemberExpr(MemberExpr *E) {
9268       if (isInitList) {
9269         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9270           return;
9271       }
9272 
9273       // Don't warn on arrays since they can be treated as pointers.
9274       if (E->getType()->canDecayToPointerType()) return;
9275 
9276       // Warn when a non-static method call is followed by non-static member
9277       // field accesses, which is followed by a DeclRefExpr.
9278       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9279       bool Warn = (MD && !MD->isStatic());
9280       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9281       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9282         if (!isa<FieldDecl>(ME->getMemberDecl()))
9283           Warn = false;
9284         Base = ME->getBase()->IgnoreParenImpCasts();
9285       }
9286 
9287       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9288         if (Warn)
9289           HandleDeclRefExpr(DRE);
9290         return;
9291       }
9292 
9293       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9294       // Visit that expression.
9295       Visit(Base);
9296     }
9297 
9298     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9299       Expr *Callee = E->getCallee();
9300 
9301       if (isa<UnresolvedLookupExpr>(Callee))
9302         return Inherited::VisitCXXOperatorCallExpr(E);
9303 
9304       Visit(Callee);
9305       for (auto Arg: E->arguments())
9306         HandleValue(Arg->IgnoreParenImpCasts());
9307     }
9308 
9309     void VisitUnaryOperator(UnaryOperator *E) {
9310       // For POD record types, addresses of its own members are well-defined.
9311       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9312           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9313         if (!isPODType)
9314           HandleValue(E->getSubExpr());
9315         return;
9316       }
9317 
9318       if (E->isIncrementDecrementOp()) {
9319         HandleValue(E->getSubExpr());
9320         return;
9321       }
9322 
9323       Inherited::VisitUnaryOperator(E);
9324     }
9325 
9326     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9327 
9328     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9329       if (E->getConstructor()->isCopyConstructor()) {
9330         Expr *ArgExpr = E->getArg(0);
9331         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9332           if (ILE->getNumInits() == 1)
9333             ArgExpr = ILE->getInit(0);
9334         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9335           if (ICE->getCastKind() == CK_NoOp)
9336             ArgExpr = ICE->getSubExpr();
9337         HandleValue(ArgExpr);
9338         return;
9339       }
9340       Inherited::VisitCXXConstructExpr(E);
9341     }
9342 
9343     void VisitCallExpr(CallExpr *E) {
9344       // Treat std::move as a use.
9345       if (E->getNumArgs() == 1) {
9346         if (FunctionDecl *FD = E->getDirectCallee()) {
9347           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9348               FD->getIdentifier()->isStr("move")) {
9349             HandleValue(E->getArg(0));
9350             return;
9351           }
9352         }
9353       }
9354 
9355       Inherited::VisitCallExpr(E);
9356     }
9357 
9358     void VisitBinaryOperator(BinaryOperator *E) {
9359       if (E->isCompoundAssignmentOp()) {
9360         HandleValue(E->getLHS());
9361         Visit(E->getRHS());
9362         return;
9363       }
9364 
9365       Inherited::VisitBinaryOperator(E);
9366     }
9367 
9368     // A custom visitor for BinaryConditionalOperator is needed because the
9369     // regular visitor would check the condition and true expression separately
9370     // but both point to the same place giving duplicate diagnostics.
9371     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9372       Visit(E->getCond());
9373       Visit(E->getFalseExpr());
9374     }
9375 
9376     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9377       Decl* ReferenceDecl = DRE->getDecl();
9378       if (OrigDecl != ReferenceDecl) return;
9379       unsigned diag;
9380       if (isReferenceType) {
9381         diag = diag::warn_uninit_self_reference_in_reference_init;
9382       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9383         diag = diag::warn_static_self_reference_in_init;
9384       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9385                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9386                  DRE->getDecl()->getType()->isRecordType()) {
9387         diag = diag::warn_uninit_self_reference_in_init;
9388       } else {
9389         // Local variables will be handled by the CFG analysis.
9390         return;
9391       }
9392 
9393       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9394                             S.PDiag(diag)
9395                               << DRE->getNameInfo().getName()
9396                               << OrigDecl->getLocation()
9397                               << DRE->getSourceRange());
9398     }
9399   };
9400 
9401   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9402   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9403                                  bool DirectInit) {
9404     // Parameters arguments are occassionially constructed with itself,
9405     // for instance, in recursive functions.  Skip them.
9406     if (isa<ParmVarDecl>(OrigDecl))
9407       return;
9408 
9409     E = E->IgnoreParens();
9410 
9411     // Skip checking T a = a where T is not a record or reference type.
9412     // Doing so is a way to silence uninitialized warnings.
9413     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9414       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9415         if (ICE->getCastKind() == CK_LValueToRValue)
9416           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9417             if (DRE->getDecl() == OrigDecl)
9418               return;
9419 
9420     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9421   }
9422 } // end anonymous namespace
9423 
9424 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9425                                             DeclarationName Name, QualType Type,
9426                                             TypeSourceInfo *TSI,
9427                                             SourceRange Range, bool DirectInit,
9428                                             Expr *Init) {
9429   bool IsInitCapture = !VDecl;
9430   assert((!VDecl || !VDecl->isInitCapture()) &&
9431          "init captures are expected to be deduced prior to initialization");
9432 
9433   ArrayRef<Expr *> DeduceInits = Init;
9434   if (DirectInit) {
9435     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9436       DeduceInits = PL->exprs();
9437     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9438       DeduceInits = IL->inits();
9439   }
9440 
9441   // Deduction only works if we have exactly one source expression.
9442   if (DeduceInits.empty()) {
9443     // It isn't possible to write this directly, but it is possible to
9444     // end up in this situation with "auto x(some_pack...);"
9445     Diag(Init->getLocStart(), IsInitCapture
9446                                   ? diag::err_init_capture_no_expression
9447                                   : diag::err_auto_var_init_no_expression)
9448         << Name << Type << Range;
9449     return QualType();
9450   }
9451 
9452   if (DeduceInits.size() > 1) {
9453     Diag(DeduceInits[1]->getLocStart(),
9454          IsInitCapture ? diag::err_init_capture_multiple_expressions
9455                        : diag::err_auto_var_init_multiple_expressions)
9456         << Name << Type << Range;
9457     return QualType();
9458   }
9459 
9460   Expr *DeduceInit = DeduceInits[0];
9461   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9462     Diag(Init->getLocStart(), IsInitCapture
9463                                   ? diag::err_init_capture_paren_braces
9464                                   : diag::err_auto_var_init_paren_braces)
9465         << isa<InitListExpr>(Init) << Name << Type << Range;
9466     return QualType();
9467   }
9468 
9469   // Expressions default to 'id' when we're in a debugger.
9470   bool DefaultedAnyToId = false;
9471   if (getLangOpts().DebuggerCastResultToId &&
9472       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9473     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9474     if (Result.isInvalid()) {
9475       return QualType();
9476     }
9477     Init = Result.get();
9478     DefaultedAnyToId = true;
9479   }
9480 
9481   QualType DeducedType;
9482   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9483     if (!IsInitCapture)
9484       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9485     else if (isa<InitListExpr>(Init))
9486       Diag(Range.getBegin(),
9487            diag::err_init_capture_deduction_failure_from_init_list)
9488           << Name
9489           << (DeduceInit->getType().isNull() ? TSI->getType()
9490                                              : DeduceInit->getType())
9491           << DeduceInit->getSourceRange();
9492     else
9493       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9494           << Name << TSI->getType()
9495           << (DeduceInit->getType().isNull() ? TSI->getType()
9496                                              : DeduceInit->getType())
9497           << DeduceInit->getSourceRange();
9498   }
9499 
9500   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9501   // 'id' instead of a specific object type prevents most of our usual
9502   // checks.
9503   // We only want to warn outside of template instantiations, though:
9504   // inside a template, the 'id' could have come from a parameter.
9505   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9506       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9507     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9508     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9509   }
9510 
9511   return DeducedType;
9512 }
9513 
9514 /// AddInitializerToDecl - Adds the initializer Init to the
9515 /// declaration dcl. If DirectInit is true, this is C++ direct
9516 /// initialization rather than copy initialization.
9517 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9518                                 bool DirectInit, bool TypeMayContainAuto) {
9519   // If there is no declaration, there was an error parsing it.  Just ignore
9520   // the initializer.
9521   if (!RealDecl || RealDecl->isInvalidDecl()) {
9522     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9523     return;
9524   }
9525 
9526   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9527     // Pure-specifiers are handled in ActOnPureSpecifier.
9528     Diag(Method->getLocation(), diag::err_member_function_initialization)
9529       << Method->getDeclName() << Init->getSourceRange();
9530     Method->setInvalidDecl();
9531     return;
9532   }
9533 
9534   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9535   if (!VDecl) {
9536     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9537     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9538     RealDecl->setInvalidDecl();
9539     return;
9540   }
9541 
9542   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9543   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9544     // Attempt typo correction early so that the type of the init expression can
9545     // be deduced based on the chosen correction if the original init contains a
9546     // TypoExpr.
9547     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9548     if (!Res.isUsable()) {
9549       RealDecl->setInvalidDecl();
9550       return;
9551     }
9552     Init = Res.get();
9553 
9554     QualType DeducedType = deduceVarTypeFromInitializer(
9555         VDecl, VDecl->getDeclName(), VDecl->getType(),
9556         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9557     if (DeducedType.isNull()) {
9558       RealDecl->setInvalidDecl();
9559       return;
9560     }
9561 
9562     VDecl->setType(DeducedType);
9563     assert(VDecl->isLinkageValid());
9564 
9565     // In ARC, infer lifetime.
9566     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9567       VDecl->setInvalidDecl();
9568 
9569     // If this is a redeclaration, check that the type we just deduced matches
9570     // the previously declared type.
9571     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9572       // We never need to merge the type, because we cannot form an incomplete
9573       // array of auto, nor deduce such a type.
9574       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9575     }
9576 
9577     // Check the deduced type is valid for a variable declaration.
9578     CheckVariableDeclarationType(VDecl);
9579     if (VDecl->isInvalidDecl())
9580       return;
9581   }
9582 
9583   // dllimport cannot be used on variable definitions.
9584   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9585     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9586     VDecl->setInvalidDecl();
9587     return;
9588   }
9589 
9590   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9591     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9592     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9593     VDecl->setInvalidDecl();
9594     return;
9595   }
9596 
9597   if (!VDecl->getType()->isDependentType()) {
9598     // A definition must end up with a complete type, which means it must be
9599     // complete with the restriction that an array type might be completed by
9600     // the initializer; note that later code assumes this restriction.
9601     QualType BaseDeclType = VDecl->getType();
9602     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9603       BaseDeclType = Array->getElementType();
9604     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9605                             diag::err_typecheck_decl_incomplete_type)) {
9606       RealDecl->setInvalidDecl();
9607       return;
9608     }
9609 
9610     // The variable can not have an abstract class type.
9611     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9612                                diag::err_abstract_type_in_decl,
9613                                AbstractVariableType))
9614       VDecl->setInvalidDecl();
9615   }
9616 
9617   VarDecl *Def;
9618   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9619     NamedDecl *Hidden = nullptr;
9620     if (!hasVisibleDefinition(Def, &Hidden) &&
9621         (VDecl->getFormalLinkage() == InternalLinkage ||
9622          VDecl->getDescribedVarTemplate() ||
9623          VDecl->getNumTemplateParameterLists() ||
9624          VDecl->getDeclContext()->isDependentContext())) {
9625       // The previous definition is hidden, and multiple definitions are
9626       // permitted (in separate TUs). Form another definition of it.
9627     } else {
9628       Diag(VDecl->getLocation(), diag::err_redefinition)
9629         << VDecl->getDeclName();
9630       Diag(Def->getLocation(), diag::note_previous_definition);
9631       VDecl->setInvalidDecl();
9632       return;
9633     }
9634   }
9635 
9636   if (getLangOpts().CPlusPlus) {
9637     // C++ [class.static.data]p4
9638     //   If a static data member is of const integral or const
9639     //   enumeration type, its declaration in the class definition can
9640     //   specify a constant-initializer which shall be an integral
9641     //   constant expression (5.19). In that case, the member can appear
9642     //   in integral constant expressions. The member shall still be
9643     //   defined in a namespace scope if it is used in the program and the
9644     //   namespace scope definition shall not contain an initializer.
9645     //
9646     // We already performed a redefinition check above, but for static
9647     // data members we also need to check whether there was an in-class
9648     // declaration with an initializer.
9649     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9650       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9651           << VDecl->getDeclName();
9652       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9653            diag::note_previous_initializer)
9654           << 0;
9655       return;
9656     }
9657 
9658     if (VDecl->hasLocalStorage())
9659       getCurFunction()->setHasBranchProtectedScope();
9660 
9661     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9662       VDecl->setInvalidDecl();
9663       return;
9664     }
9665   }
9666 
9667   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9668   // a kernel function cannot be initialized."
9669   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9670     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9671     VDecl->setInvalidDecl();
9672     return;
9673   }
9674 
9675   // Get the decls type and save a reference for later, since
9676   // CheckInitializerTypes may change it.
9677   QualType DclT = VDecl->getType(), SavT = DclT;
9678 
9679   // Expressions default to 'id' when we're in a debugger
9680   // and we are assigning it to a variable of Objective-C pointer type.
9681   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9682       Init->getType() == Context.UnknownAnyTy) {
9683     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9684     if (Result.isInvalid()) {
9685       VDecl->setInvalidDecl();
9686       return;
9687     }
9688     Init = Result.get();
9689   }
9690 
9691   // Perform the initialization.
9692   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9693   if (!VDecl->isInvalidDecl()) {
9694     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9695     InitializationKind Kind =
9696         DirectInit
9697             ? CXXDirectInit
9698                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9699                                                      Init->getLocStart(),
9700                                                      Init->getLocEnd())
9701                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9702             : InitializationKind::CreateCopy(VDecl->getLocation(),
9703                                              Init->getLocStart());
9704 
9705     MultiExprArg Args = Init;
9706     if (CXXDirectInit)
9707       Args = MultiExprArg(CXXDirectInit->getExprs(),
9708                           CXXDirectInit->getNumExprs());
9709 
9710     // Try to correct any TypoExprs in the initialization arguments.
9711     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9712       ExprResult Res = CorrectDelayedTyposInExpr(
9713           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9714             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9715             return Init.Failed() ? ExprError() : E;
9716           });
9717       if (Res.isInvalid()) {
9718         VDecl->setInvalidDecl();
9719       } else if (Res.get() != Args[Idx]) {
9720         Args[Idx] = Res.get();
9721       }
9722     }
9723     if (VDecl->isInvalidDecl())
9724       return;
9725 
9726     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9727                                    /*TopLevelOfInitList=*/false,
9728                                    /*TreatUnavailableAsInvalid=*/false);
9729     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9730     if (Result.isInvalid()) {
9731       VDecl->setInvalidDecl();
9732       return;
9733     }
9734 
9735     Init = Result.getAs<Expr>();
9736   }
9737 
9738   // Check for self-references within variable initializers.
9739   // Variables declared within a function/method body (except for references)
9740   // are handled by a dataflow analysis.
9741   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9742       VDecl->getType()->isReferenceType()) {
9743     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9744   }
9745 
9746   // If the type changed, it means we had an incomplete type that was
9747   // completed by the initializer. For example:
9748   //   int ary[] = { 1, 3, 5 };
9749   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9750   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9751     VDecl->setType(DclT);
9752 
9753   if (!VDecl->isInvalidDecl()) {
9754     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9755 
9756     if (VDecl->hasAttr<BlocksAttr>())
9757       checkRetainCycles(VDecl, Init);
9758 
9759     // It is safe to assign a weak reference into a strong variable.
9760     // Although this code can still have problems:
9761     //   id x = self.weakProp;
9762     //   id y = self.weakProp;
9763     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9764     // paths through the function. This should be revisited if
9765     // -Wrepeated-use-of-weak is made flow-sensitive.
9766     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9767         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9768                          Init->getLocStart()))
9769       getCurFunction()->markSafeWeakUse(Init);
9770   }
9771 
9772   // The initialization is usually a full-expression.
9773   //
9774   // FIXME: If this is a braced initialization of an aggregate, it is not
9775   // an expression, and each individual field initializer is a separate
9776   // full-expression. For instance, in:
9777   //
9778   //   struct Temp { ~Temp(); };
9779   //   struct S { S(Temp); };
9780   //   struct T { S a, b; } t = { Temp(), Temp() }
9781   //
9782   // we should destroy the first Temp before constructing the second.
9783   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9784                                           false,
9785                                           VDecl->isConstexpr());
9786   if (Result.isInvalid()) {
9787     VDecl->setInvalidDecl();
9788     return;
9789   }
9790   Init = Result.get();
9791 
9792   // Attach the initializer to the decl.
9793   VDecl->setInit(Init);
9794 
9795   if (VDecl->isLocalVarDecl()) {
9796     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9797     // static storage duration shall be constant expressions or string literals.
9798     // C++ does not have this restriction.
9799     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9800       const Expr *Culprit;
9801       if (VDecl->getStorageClass() == SC_Static)
9802         CheckForConstantInitializer(Init, DclT);
9803       // C89 is stricter than C99 for non-static aggregate types.
9804       // C89 6.5.7p3: All the expressions [...] in an initializer list
9805       // for an object that has aggregate or union type shall be
9806       // constant expressions.
9807       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9808                isa<InitListExpr>(Init) &&
9809                !Init->isConstantInitializer(Context, false, &Culprit))
9810         Diag(Culprit->getExprLoc(),
9811              diag::ext_aggregate_init_not_constant)
9812           << Culprit->getSourceRange();
9813     }
9814   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
9815              VDecl->getLexicalDeclContext()->isRecord()) {
9816     // This is an in-class initialization for a static data member, e.g.,
9817     //
9818     // struct S {
9819     //   static const int value = 17;
9820     // };
9821 
9822     // C++ [class.mem]p4:
9823     //   A member-declarator can contain a constant-initializer only
9824     //   if it declares a static member (9.4) of const integral or
9825     //   const enumeration type, see 9.4.2.
9826     //
9827     // C++11 [class.static.data]p3:
9828     //   If a non-volatile non-inline const static data member is of integral
9829     //   or enumeration type, its declaration in the class definition can
9830     //   specify a brace-or-equal-initializer in which every initalizer-clause
9831     //   that is an assignment-expression is a constant expression. A static
9832     //   data member of literal type can be declared in the class definition
9833     //   with the constexpr specifier; if so, its declaration shall specify a
9834     //   brace-or-equal-initializer in which every initializer-clause that is
9835     //   an assignment-expression is a constant expression.
9836 
9837     // Do nothing on dependent types.
9838     if (DclT->isDependentType()) {
9839 
9840     // Allow any 'static constexpr' members, whether or not they are of literal
9841     // type. We separately check that every constexpr variable is of literal
9842     // type.
9843     } else if (VDecl->isConstexpr()) {
9844 
9845     // Require constness.
9846     } else if (!DclT.isConstQualified()) {
9847       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9848         << Init->getSourceRange();
9849       VDecl->setInvalidDecl();
9850 
9851     // We allow integer constant expressions in all cases.
9852     } else if (DclT->isIntegralOrEnumerationType()) {
9853       // Check whether the expression is a constant expression.
9854       SourceLocation Loc;
9855       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9856         // In C++11, a non-constexpr const static data member with an
9857         // in-class initializer cannot be volatile.
9858         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9859       else if (Init->isValueDependent())
9860         ; // Nothing to check.
9861       else if (Init->isIntegerConstantExpr(Context, &Loc))
9862         ; // Ok, it's an ICE!
9863       else if (Init->isEvaluatable(Context)) {
9864         // If we can constant fold the initializer through heroics, accept it,
9865         // but report this as a use of an extension for -pedantic.
9866         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9867           << Init->getSourceRange();
9868       } else {
9869         // Otherwise, this is some crazy unknown case.  Report the issue at the
9870         // location provided by the isIntegerConstantExpr failed check.
9871         Diag(Loc, diag::err_in_class_initializer_non_constant)
9872           << Init->getSourceRange();
9873         VDecl->setInvalidDecl();
9874       }
9875 
9876     // We allow foldable floating-point constants as an extension.
9877     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9878       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9879       // it anyway and provide a fixit to add the 'constexpr'.
9880       if (getLangOpts().CPlusPlus11) {
9881         Diag(VDecl->getLocation(),
9882              diag::ext_in_class_initializer_float_type_cxx11)
9883             << DclT << Init->getSourceRange();
9884         Diag(VDecl->getLocStart(),
9885              diag::note_in_class_initializer_float_type_cxx11)
9886             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9887       } else {
9888         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9889           << DclT << Init->getSourceRange();
9890 
9891         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9892           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9893             << Init->getSourceRange();
9894           VDecl->setInvalidDecl();
9895         }
9896       }
9897 
9898     // Suggest adding 'constexpr' in C++11 for literal types.
9899     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9900       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9901         << DclT << Init->getSourceRange()
9902         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9903       VDecl->setConstexpr(true);
9904 
9905     } else {
9906       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9907         << DclT << Init->getSourceRange();
9908       VDecl->setInvalidDecl();
9909     }
9910   } else if (VDecl->isFileVarDecl()) {
9911     if (VDecl->getStorageClass() == SC_Extern &&
9912         (!getLangOpts().CPlusPlus ||
9913          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9914            VDecl->isExternC())) &&
9915         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9916       Diag(VDecl->getLocation(), diag::warn_extern_init);
9917 
9918     // C99 6.7.8p4. All file scoped initializers need to be constant.
9919     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9920       CheckForConstantInitializer(Init, DclT);
9921   }
9922 
9923   // We will represent direct-initialization similarly to copy-initialization:
9924   //    int x(1);  -as-> int x = 1;
9925   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9926   //
9927   // Clients that want to distinguish between the two forms, can check for
9928   // direct initializer using VarDecl::getInitStyle().
9929   // A major benefit is that clients that don't particularly care about which
9930   // exactly form was it (like the CodeGen) can handle both cases without
9931   // special case code.
9932 
9933   // C++ 8.5p11:
9934   // The form of initialization (using parentheses or '=') is generally
9935   // insignificant, but does matter when the entity being initialized has a
9936   // class type.
9937   if (CXXDirectInit) {
9938     assert(DirectInit && "Call-style initializer must be direct init.");
9939     VDecl->setInitStyle(VarDecl::CallInit);
9940   } else if (DirectInit) {
9941     // This must be list-initialization. No other way is direct-initialization.
9942     VDecl->setInitStyle(VarDecl::ListInit);
9943   }
9944 
9945   CheckCompleteVariableDeclaration(VDecl);
9946 }
9947 
9948 /// ActOnInitializerError - Given that there was an error parsing an
9949 /// initializer for the given declaration, try to return to some form
9950 /// of sanity.
9951 void Sema::ActOnInitializerError(Decl *D) {
9952   // Our main concern here is re-establishing invariants like "a
9953   // variable's type is either dependent or complete".
9954   if (!D || D->isInvalidDecl()) return;
9955 
9956   VarDecl *VD = dyn_cast<VarDecl>(D);
9957   if (!VD) return;
9958 
9959   // Auto types are meaningless if we can't make sense of the initializer.
9960   if (ParsingInitForAutoVars.count(D)) {
9961     D->setInvalidDecl();
9962     return;
9963   }
9964 
9965   QualType Ty = VD->getType();
9966   if (Ty->isDependentType()) return;
9967 
9968   // Require a complete type.
9969   if (RequireCompleteType(VD->getLocation(),
9970                           Context.getBaseElementType(Ty),
9971                           diag::err_typecheck_decl_incomplete_type)) {
9972     VD->setInvalidDecl();
9973     return;
9974   }
9975 
9976   // Require a non-abstract type.
9977   if (RequireNonAbstractType(VD->getLocation(), Ty,
9978                              diag::err_abstract_type_in_decl,
9979                              AbstractVariableType)) {
9980     VD->setInvalidDecl();
9981     return;
9982   }
9983 
9984   // Don't bother complaining about constructors or destructors,
9985   // though.
9986 }
9987 
9988 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9989                                   bool TypeMayContainAuto) {
9990   // If there is no declaration, there was an error parsing it. Just ignore it.
9991   if (!RealDecl)
9992     return;
9993 
9994   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9995     QualType Type = Var->getType();
9996 
9997     // C++11 [dcl.spec.auto]p3
9998     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9999       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10000         << Var->getDeclName() << Type;
10001       Var->setInvalidDecl();
10002       return;
10003     }
10004 
10005     // C++11 [class.static.data]p3: A static data member can be declared with
10006     // the constexpr specifier; if so, its declaration shall specify
10007     // a brace-or-equal-initializer.
10008     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10009     // the definition of a variable [...] or the declaration of a static data
10010     // member.
10011     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
10012       if (Var->isStaticDataMember()) {
10013         // C++1z removes the relevant rule; the in-class declaration is always
10014         // a definition there.
10015         if (!getLangOpts().CPlusPlus1z) {
10016           Diag(Var->getLocation(),
10017                diag::err_constexpr_static_mem_var_requires_init)
10018             << Var->getDeclName();
10019           Var->setInvalidDecl();
10020           return;
10021         }
10022       } else {
10023         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10024         Var->setInvalidDecl();
10025         return;
10026       }
10027     }
10028 
10029     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10030     // definition having the concept specifier is called a variable concept. A
10031     // concept definition refers to [...] a variable concept and its initializer.
10032     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10033       if (VTD->isConcept()) {
10034         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10035         Var->setInvalidDecl();
10036         return;
10037       }
10038     }
10039 
10040     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10041     // be initialized.
10042     if (!Var->isInvalidDecl() &&
10043         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10044         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10045       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10046       Var->setInvalidDecl();
10047       return;
10048     }
10049 
10050     switch (Var->isThisDeclarationADefinition()) {
10051     case VarDecl::Definition:
10052       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10053         break;
10054 
10055       // We have an out-of-line definition of a static data member
10056       // that has an in-class initializer, so we type-check this like
10057       // a declaration.
10058       //
10059       // Fall through
10060 
10061     case VarDecl::DeclarationOnly:
10062       // It's only a declaration.
10063 
10064       // Block scope. C99 6.7p7: If an identifier for an object is
10065       // declared with no linkage (C99 6.2.2p6), the type for the
10066       // object shall be complete.
10067       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10068           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10069           RequireCompleteType(Var->getLocation(), Type,
10070                               diag::err_typecheck_decl_incomplete_type))
10071         Var->setInvalidDecl();
10072 
10073       // Make sure that the type is not abstract.
10074       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10075           RequireNonAbstractType(Var->getLocation(), Type,
10076                                  diag::err_abstract_type_in_decl,
10077                                  AbstractVariableType))
10078         Var->setInvalidDecl();
10079       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10080           Var->getStorageClass() == SC_PrivateExtern) {
10081         Diag(Var->getLocation(), diag::warn_private_extern);
10082         Diag(Var->getLocation(), diag::note_private_extern);
10083       }
10084 
10085       return;
10086 
10087     case VarDecl::TentativeDefinition:
10088       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10089       // object that has file scope without an initializer, and without a
10090       // storage-class specifier or with the storage-class specifier "static",
10091       // constitutes a tentative definition. Note: A tentative definition with
10092       // external linkage is valid (C99 6.2.2p5).
10093       if (!Var->isInvalidDecl()) {
10094         if (const IncompleteArrayType *ArrayT
10095                                     = Context.getAsIncompleteArrayType(Type)) {
10096           if (RequireCompleteType(Var->getLocation(),
10097                                   ArrayT->getElementType(),
10098                                   diag::err_illegal_decl_array_incomplete_type))
10099             Var->setInvalidDecl();
10100         } else if (Var->getStorageClass() == SC_Static) {
10101           // C99 6.9.2p3: If the declaration of an identifier for an object is
10102           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10103           // declared type shall not be an incomplete type.
10104           // NOTE: code such as the following
10105           //     static struct s;
10106           //     struct s { int a; };
10107           // is accepted by gcc. Hence here we issue a warning instead of
10108           // an error and we do not invalidate the static declaration.
10109           // NOTE: to avoid multiple warnings, only check the first declaration.
10110           if (Var->isFirstDecl())
10111             RequireCompleteType(Var->getLocation(), Type,
10112                                 diag::ext_typecheck_decl_incomplete_type);
10113         }
10114       }
10115 
10116       // Record the tentative definition; we're done.
10117       if (!Var->isInvalidDecl())
10118         TentativeDefinitions.push_back(Var);
10119       return;
10120     }
10121 
10122     // Provide a specific diagnostic for uninitialized variable
10123     // definitions with incomplete array type.
10124     if (Type->isIncompleteArrayType()) {
10125       Diag(Var->getLocation(),
10126            diag::err_typecheck_incomplete_array_needs_initializer);
10127       Var->setInvalidDecl();
10128       return;
10129     }
10130 
10131     // Provide a specific diagnostic for uninitialized variable
10132     // definitions with reference type.
10133     if (Type->isReferenceType()) {
10134       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10135         << Var->getDeclName()
10136         << SourceRange(Var->getLocation(), Var->getLocation());
10137       Var->setInvalidDecl();
10138       return;
10139     }
10140 
10141     // Do not attempt to type-check the default initializer for a
10142     // variable with dependent type.
10143     if (Type->isDependentType())
10144       return;
10145 
10146     if (Var->isInvalidDecl())
10147       return;
10148 
10149     if (!Var->hasAttr<AliasAttr>()) {
10150       if (RequireCompleteType(Var->getLocation(),
10151                               Context.getBaseElementType(Type),
10152                               diag::err_typecheck_decl_incomplete_type)) {
10153         Var->setInvalidDecl();
10154         return;
10155       }
10156     } else {
10157       return;
10158     }
10159 
10160     // The variable can not have an abstract class type.
10161     if (RequireNonAbstractType(Var->getLocation(), Type,
10162                                diag::err_abstract_type_in_decl,
10163                                AbstractVariableType)) {
10164       Var->setInvalidDecl();
10165       return;
10166     }
10167 
10168     // Check for jumps past the implicit initializer.  C++0x
10169     // clarifies that this applies to a "variable with automatic
10170     // storage duration", not a "local variable".
10171     // C++11 [stmt.dcl]p3
10172     //   A program that jumps from a point where a variable with automatic
10173     //   storage duration is not in scope to a point where it is in scope is
10174     //   ill-formed unless the variable has scalar type, class type with a
10175     //   trivial default constructor and a trivial destructor, a cv-qualified
10176     //   version of one of these types, or an array of one of the preceding
10177     //   types and is declared without an initializer.
10178     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10179       if (const RecordType *Record
10180             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10181         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10182         // Mark the function for further checking even if the looser rules of
10183         // C++11 do not require such checks, so that we can diagnose
10184         // incompatibilities with C++98.
10185         if (!CXXRecord->isPOD())
10186           getCurFunction()->setHasBranchProtectedScope();
10187       }
10188     }
10189 
10190     // C++03 [dcl.init]p9:
10191     //   If no initializer is specified for an object, and the
10192     //   object is of (possibly cv-qualified) non-POD class type (or
10193     //   array thereof), the object shall be default-initialized; if
10194     //   the object is of const-qualified type, the underlying class
10195     //   type shall have a user-declared default
10196     //   constructor. Otherwise, if no initializer is specified for
10197     //   a non- static object, the object and its subobjects, if
10198     //   any, have an indeterminate initial value); if the object
10199     //   or any of its subobjects are of const-qualified type, the
10200     //   program is ill-formed.
10201     // C++0x [dcl.init]p11:
10202     //   If no initializer is specified for an object, the object is
10203     //   default-initialized; [...].
10204     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10205     InitializationKind Kind
10206       = InitializationKind::CreateDefault(Var->getLocation());
10207 
10208     InitializationSequence InitSeq(*this, Entity, Kind, None);
10209     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10210     if (Init.isInvalid())
10211       Var->setInvalidDecl();
10212     else if (Init.get()) {
10213       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10214       // This is important for template substitution.
10215       Var->setInitStyle(VarDecl::CallInit);
10216     }
10217 
10218     CheckCompleteVariableDeclaration(Var);
10219   }
10220 }
10221 
10222 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10223   // If there is no declaration, there was an error parsing it. Ignore it.
10224   if (!D)
10225     return;
10226 
10227   VarDecl *VD = dyn_cast<VarDecl>(D);
10228   if (!VD) {
10229     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10230     D->setInvalidDecl();
10231     return;
10232   }
10233 
10234   VD->setCXXForRangeDecl(true);
10235 
10236   // for-range-declaration cannot be given a storage class specifier.
10237   int Error = -1;
10238   switch (VD->getStorageClass()) {
10239   case SC_None:
10240     break;
10241   case SC_Extern:
10242     Error = 0;
10243     break;
10244   case SC_Static:
10245     Error = 1;
10246     break;
10247   case SC_PrivateExtern:
10248     Error = 2;
10249     break;
10250   case SC_Auto:
10251     Error = 3;
10252     break;
10253   case SC_Register:
10254     Error = 4;
10255     break;
10256   }
10257   if (Error != -1) {
10258     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10259       << VD->getDeclName() << Error;
10260     D->setInvalidDecl();
10261   }
10262 }
10263 
10264 StmtResult
10265 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10266                                  IdentifierInfo *Ident,
10267                                  ParsedAttributes &Attrs,
10268                                  SourceLocation AttrEnd) {
10269   // C++1y [stmt.iter]p1:
10270   //   A range-based for statement of the form
10271   //      for ( for-range-identifier : for-range-initializer ) statement
10272   //   is equivalent to
10273   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10274   DeclSpec DS(Attrs.getPool().getFactory());
10275 
10276   const char *PrevSpec;
10277   unsigned DiagID;
10278   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10279                      getPrintingPolicy());
10280 
10281   Declarator D(DS, Declarator::ForContext);
10282   D.SetIdentifier(Ident, IdentLoc);
10283   D.takeAttributes(Attrs, AttrEnd);
10284 
10285   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10286   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10287                 EmptyAttrs, IdentLoc);
10288   Decl *Var = ActOnDeclarator(S, D);
10289   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10290   FinalizeDeclaration(Var);
10291   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10292                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10293 }
10294 
10295 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10296   if (var->isInvalidDecl()) return;
10297 
10298   if (getLangOpts().OpenCL) {
10299     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10300     // initialiser
10301     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10302         !var->hasInit()) {
10303       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10304           << 1 /*Init*/;
10305       var->setInvalidDecl();
10306       return;
10307     }
10308   }
10309 
10310   // In Objective-C, don't allow jumps past the implicit initialization of a
10311   // local retaining variable.
10312   if (getLangOpts().ObjC1 &&
10313       var->hasLocalStorage()) {
10314     switch (var->getType().getObjCLifetime()) {
10315     case Qualifiers::OCL_None:
10316     case Qualifiers::OCL_ExplicitNone:
10317     case Qualifiers::OCL_Autoreleasing:
10318       break;
10319 
10320     case Qualifiers::OCL_Weak:
10321     case Qualifiers::OCL_Strong:
10322       getCurFunction()->setHasBranchProtectedScope();
10323       break;
10324     }
10325   }
10326 
10327   // Warn about externally-visible variables being defined without a
10328   // prior declaration.  We only want to do this for global
10329   // declarations, but we also specifically need to avoid doing it for
10330   // class members because the linkage of an anonymous class can
10331   // change if it's later given a typedef name.
10332   if (var->isThisDeclarationADefinition() &&
10333       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10334       var->isExternallyVisible() && var->hasLinkage() &&
10335       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10336                                   var->getLocation())) {
10337     // Find a previous declaration that's not a definition.
10338     VarDecl *prev = var->getPreviousDecl();
10339     while (prev && prev->isThisDeclarationADefinition())
10340       prev = prev->getPreviousDecl();
10341 
10342     if (!prev)
10343       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10344   }
10345 
10346   if (var->getTLSKind() == VarDecl::TLS_Static) {
10347     const Expr *Culprit;
10348     if (var->getType().isDestructedType()) {
10349       // GNU C++98 edits for __thread, [basic.start.term]p3:
10350       //   The type of an object with thread storage duration shall not
10351       //   have a non-trivial destructor.
10352       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10353       if (getLangOpts().CPlusPlus11)
10354         Diag(var->getLocation(), diag::note_use_thread_local);
10355     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10356                !var->getInit()->isConstantInitializer(
10357                    Context, var->getType()->isReferenceType(), &Culprit)) {
10358       // GNU C++98 edits for __thread, [basic.start.init]p4:
10359       //   An object of thread storage duration shall not require dynamic
10360       //   initialization.
10361       // FIXME: Need strict checking here.
10362       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10363         << Culprit->getSourceRange();
10364       if (getLangOpts().CPlusPlus11)
10365         Diag(var->getLocation(), diag::note_use_thread_local);
10366     }
10367   }
10368 
10369   // Apply section attributes and pragmas to global variables.
10370   bool GlobalStorage = var->hasGlobalStorage();
10371   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10372       ActiveTemplateInstantiations.empty()) {
10373     PragmaStack<StringLiteral *> *Stack = nullptr;
10374     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10375     if (var->getType().isConstQualified())
10376       Stack = &ConstSegStack;
10377     else if (!var->getInit()) {
10378       Stack = &BSSSegStack;
10379       SectionFlags |= ASTContext::PSF_Write;
10380     } else {
10381       Stack = &DataSegStack;
10382       SectionFlags |= ASTContext::PSF_Write;
10383     }
10384     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10385       var->addAttr(SectionAttr::CreateImplicit(
10386           Context, SectionAttr::Declspec_allocate,
10387           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10388     }
10389     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10390       if (UnifySection(SA->getName(), SectionFlags, var))
10391         var->dropAttr<SectionAttr>();
10392 
10393     // Apply the init_seg attribute if this has an initializer.  If the
10394     // initializer turns out to not be dynamic, we'll end up ignoring this
10395     // attribute.
10396     if (CurInitSeg && var->getInit())
10397       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10398                                                CurInitSegLoc));
10399   }
10400 
10401   // All the following checks are C++ only.
10402   if (!getLangOpts().CPlusPlus) return;
10403 
10404   QualType type = var->getType();
10405   if (type->isDependentType()) return;
10406 
10407   // __block variables might require us to capture a copy-initializer.
10408   if (var->hasAttr<BlocksAttr>()) {
10409     // It's currently invalid to ever have a __block variable with an
10410     // array type; should we diagnose that here?
10411 
10412     // Regardless, we don't want to ignore array nesting when
10413     // constructing this copy.
10414     if (type->isStructureOrClassType()) {
10415       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10416       SourceLocation poi = var->getLocation();
10417       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10418       ExprResult result
10419         = PerformMoveOrCopyInitialization(
10420             InitializedEntity::InitializeBlock(poi, type, false),
10421             var, var->getType(), varRef, /*AllowNRVO=*/true);
10422       if (!result.isInvalid()) {
10423         result = MaybeCreateExprWithCleanups(result);
10424         Expr *init = result.getAs<Expr>();
10425         Context.setBlockVarCopyInits(var, init);
10426       }
10427     }
10428   }
10429 
10430   Expr *Init = var->getInit();
10431   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10432   QualType baseType = Context.getBaseElementType(type);
10433 
10434   if (!var->getDeclContext()->isDependentContext() &&
10435       Init && !Init->isValueDependent()) {
10436     if (IsGlobal && !var->isConstexpr() &&
10437         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10438                                     var->getLocation())) {
10439       // Warn about globals which don't have a constant initializer.  Don't
10440       // warn about globals with a non-trivial destructor because we already
10441       // warned about them.
10442       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10443       if (!(RD && !RD->hasTrivialDestructor()) &&
10444           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10445         Diag(var->getLocation(), diag::warn_global_constructor)
10446           << Init->getSourceRange();
10447     }
10448 
10449     if (var->isConstexpr()) {
10450       SmallVector<PartialDiagnosticAt, 8> Notes;
10451       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10452         SourceLocation DiagLoc = var->getLocation();
10453         // If the note doesn't add any useful information other than a source
10454         // location, fold it into the primary diagnostic.
10455         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10456               diag::note_invalid_subexpr_in_const_expr) {
10457           DiagLoc = Notes[0].first;
10458           Notes.clear();
10459         }
10460         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10461           << var << Init->getSourceRange();
10462         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10463           Diag(Notes[I].first, Notes[I].second);
10464       }
10465     } else if (var->isUsableInConstantExpressions(Context)) {
10466       // Check whether the initializer of a const variable of integral or
10467       // enumeration type is an ICE now, since we can't tell whether it was
10468       // initialized by a constant expression if we check later.
10469       var->checkInitIsICE();
10470     }
10471   }
10472 
10473   // Require the destructor.
10474   if (const RecordType *recordType = baseType->getAs<RecordType>())
10475     FinalizeVarWithDestructor(var, recordType);
10476 }
10477 
10478 /// \brief Determines if a variable's alignment is dependent.
10479 static bool hasDependentAlignment(VarDecl *VD) {
10480   if (VD->getType()->isDependentType())
10481     return true;
10482   for (auto *I : VD->specific_attrs<AlignedAttr>())
10483     if (I->isAlignmentDependent())
10484       return true;
10485   return false;
10486 }
10487 
10488 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10489 /// any semantic actions necessary after any initializer has been attached.
10490 void
10491 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10492   // Note that we are no longer parsing the initializer for this declaration.
10493   ParsingInitForAutoVars.erase(ThisDecl);
10494 
10495   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10496   if (!VD)
10497     return;
10498 
10499   checkAttributesAfterMerging(*this, *VD);
10500 
10501   // Perform TLS alignment check here after attributes attached to the variable
10502   // which may affect the alignment have been processed. Only perform the check
10503   // if the target has a maximum TLS alignment (zero means no constraints).
10504   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10505     // Protect the check so that it's not performed on dependent types and
10506     // dependent alignments (we can't determine the alignment in that case).
10507     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10508       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10509       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10510         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10511           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10512           << (unsigned)MaxAlignChars.getQuantity();
10513       }
10514     }
10515   }
10516 
10517   if (VD->isStaticLocal()) {
10518     if (FunctionDecl *FD =
10519             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10520       // Static locals inherit dll attributes from their function.
10521       if (Attr *A = getDLLAttr(FD)) {
10522         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10523         NewAttr->setInherited(true);
10524         VD->addAttr(NewAttr);
10525       }
10526       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10527       // function, only __shared__ variables may be declared with
10528       // static storage class.
10529       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10530           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10531           !VD->hasAttr<CUDASharedAttr>()) {
10532         Diag(VD->getLocation(), diag::err_device_static_local_var);
10533         VD->setInvalidDecl();
10534       }
10535     }
10536   }
10537 
10538   // Perform check for initializers of device-side global variables.
10539   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10540   // 7.5). We must also apply the same checks to all __shared__
10541   // variables whether they are local or not. CUDA also allows
10542   // constant initializers for __constant__ and __device__ variables.
10543   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10544     const Expr *Init = VD->getInit();
10545     if (Init && VD->hasGlobalStorage() &&
10546         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10547          VD->hasAttr<CUDASharedAttr>())) {
10548       assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10549       bool AllowedInit = false;
10550       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10551         AllowedInit =
10552             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10553       // We'll allow constant initializers even if it's a non-empty
10554       // constructor according to CUDA rules. This deviates from NVCC,
10555       // but allows us to handle things like constexpr constructors.
10556       if (!AllowedInit &&
10557           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10558         AllowedInit = VD->getInit()->isConstantInitializer(
10559             Context, VD->getType()->isReferenceType());
10560 
10561       // Also make sure that destructor, if there is one, is empty.
10562       if (AllowedInit)
10563         if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10564           AllowedInit =
10565               isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10566 
10567       if (!AllowedInit) {
10568         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10569                                     ? diag::err_shared_var_init
10570                                     : diag::err_dynamic_var_init)
10571             << Init->getSourceRange();
10572         VD->setInvalidDecl();
10573       }
10574     }
10575   }
10576 
10577   // Grab the dllimport or dllexport attribute off of the VarDecl.
10578   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10579 
10580   // Imported static data members cannot be defined out-of-line.
10581   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10582     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10583         VD->isThisDeclarationADefinition()) {
10584       // We allow definitions of dllimport class template static data members
10585       // with a warning.
10586       CXXRecordDecl *Context =
10587         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10588       bool IsClassTemplateMember =
10589           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10590           Context->getDescribedClassTemplate();
10591 
10592       Diag(VD->getLocation(),
10593            IsClassTemplateMember
10594                ? diag::warn_attribute_dllimport_static_field_definition
10595                : diag::err_attribute_dllimport_static_field_definition);
10596       Diag(IA->getLocation(), diag::note_attribute);
10597       if (!IsClassTemplateMember)
10598         VD->setInvalidDecl();
10599     }
10600   }
10601 
10602   // dllimport/dllexport variables cannot be thread local, their TLS index
10603   // isn't exported with the variable.
10604   if (DLLAttr && VD->getTLSKind()) {
10605     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10606     if (F && getDLLAttr(F)) {
10607       assert(VD->isStaticLocal());
10608       // But if this is a static local in a dlimport/dllexport function, the
10609       // function will never be inlined, which means the var would never be
10610       // imported, so having it marked import/export is safe.
10611     } else {
10612       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10613                                                                     << DLLAttr;
10614       VD->setInvalidDecl();
10615     }
10616   }
10617 
10618   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10619     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10620       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10621       VD->dropAttr<UsedAttr>();
10622     }
10623   }
10624 
10625   const DeclContext *DC = VD->getDeclContext();
10626   // If there's a #pragma GCC visibility in scope, and this isn't a class
10627   // member, set the visibility of this variable.
10628   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10629     AddPushedVisibilityAttribute(VD);
10630 
10631   // FIXME: Warn on unused templates.
10632   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10633       !isa<VarTemplatePartialSpecializationDecl>(VD))
10634     MarkUnusedFileScopedDecl(VD);
10635 
10636   // Now we have parsed the initializer and can update the table of magic
10637   // tag values.
10638   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10639       !VD->getType()->isIntegralOrEnumerationType())
10640     return;
10641 
10642   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10643     const Expr *MagicValueExpr = VD->getInit();
10644     if (!MagicValueExpr) {
10645       continue;
10646     }
10647     llvm::APSInt MagicValueInt;
10648     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10649       Diag(I->getRange().getBegin(),
10650            diag::err_type_tag_for_datatype_not_ice)
10651         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10652       continue;
10653     }
10654     if (MagicValueInt.getActiveBits() > 64) {
10655       Diag(I->getRange().getBegin(),
10656            diag::err_type_tag_for_datatype_too_large)
10657         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10658       continue;
10659     }
10660     uint64_t MagicValue = MagicValueInt.getZExtValue();
10661     RegisterTypeTagForDatatype(I->getArgumentKind(),
10662                                MagicValue,
10663                                I->getMatchingCType(),
10664                                I->getLayoutCompatible(),
10665                                I->getMustBeNull());
10666   }
10667 }
10668 
10669 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10670                                                    ArrayRef<Decl *> Group) {
10671   SmallVector<Decl*, 8> Decls;
10672 
10673   if (DS.isTypeSpecOwned())
10674     Decls.push_back(DS.getRepAsDecl());
10675 
10676   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10677   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10678     if (Decl *D = Group[i]) {
10679       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10680         if (!FirstDeclaratorInGroup)
10681           FirstDeclaratorInGroup = DD;
10682       Decls.push_back(D);
10683     }
10684 
10685   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10686     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10687       handleTagNumbering(Tag, S);
10688       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10689           getLangOpts().CPlusPlus)
10690         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10691     }
10692   }
10693 
10694   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10695 }
10696 
10697 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10698 /// group, performing any necessary semantic checking.
10699 Sema::DeclGroupPtrTy
10700 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10701                            bool TypeMayContainAuto) {
10702   // C++0x [dcl.spec.auto]p7:
10703   //   If the type deduced for the template parameter U is not the same in each
10704   //   deduction, the program is ill-formed.
10705   // FIXME: When initializer-list support is added, a distinction is needed
10706   // between the deduced type U and the deduced type which 'auto' stands for.
10707   //   auto a = 0, b = { 1, 2, 3 };
10708   // is legal because the deduced type U is 'int' in both cases.
10709   if (TypeMayContainAuto && Group.size() > 1) {
10710     QualType Deduced;
10711     CanQualType DeducedCanon;
10712     VarDecl *DeducedDecl = nullptr;
10713     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10714       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10715         AutoType *AT = D->getType()->getContainedAutoType();
10716         // Don't reissue diagnostics when instantiating a template.
10717         if (AT && D->isInvalidDecl())
10718           break;
10719         QualType U = AT ? AT->getDeducedType() : QualType();
10720         if (!U.isNull()) {
10721           CanQualType UCanon = Context.getCanonicalType(U);
10722           if (Deduced.isNull()) {
10723             Deduced = U;
10724             DeducedCanon = UCanon;
10725             DeducedDecl = D;
10726           } else if (DeducedCanon != UCanon) {
10727             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10728                  diag::err_auto_different_deductions)
10729               << (unsigned)AT->getKeyword()
10730               << Deduced << DeducedDecl->getDeclName()
10731               << U << D->getDeclName()
10732               << DeducedDecl->getInit()->getSourceRange()
10733               << D->getInit()->getSourceRange();
10734             D->setInvalidDecl();
10735             break;
10736           }
10737         }
10738       }
10739     }
10740   }
10741 
10742   ActOnDocumentableDecls(Group);
10743 
10744   return DeclGroupPtrTy::make(
10745       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10746 }
10747 
10748 void Sema::ActOnDocumentableDecl(Decl *D) {
10749   ActOnDocumentableDecls(D);
10750 }
10751 
10752 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10753   // Don't parse the comment if Doxygen diagnostics are ignored.
10754   if (Group.empty() || !Group[0])
10755     return;
10756 
10757   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10758                       Group[0]->getLocation()) &&
10759       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10760                       Group[0]->getLocation()))
10761     return;
10762 
10763   if (Group.size() >= 2) {
10764     // This is a decl group.  Normally it will contain only declarations
10765     // produced from declarator list.  But in case we have any definitions or
10766     // additional declaration references:
10767     //   'typedef struct S {} S;'
10768     //   'typedef struct S *S;'
10769     //   'struct S *pS;'
10770     // FinalizeDeclaratorGroup adds these as separate declarations.
10771     Decl *MaybeTagDecl = Group[0];
10772     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10773       Group = Group.slice(1);
10774     }
10775   }
10776 
10777   // See if there are any new comments that are not attached to a decl.
10778   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10779   if (!Comments.empty() &&
10780       !Comments.back()->isAttached()) {
10781     // There is at least one comment that not attached to a decl.
10782     // Maybe it should be attached to one of these decls?
10783     //
10784     // Note that this way we pick up not only comments that precede the
10785     // declaration, but also comments that *follow* the declaration -- thanks to
10786     // the lookahead in the lexer: we've consumed the semicolon and looked
10787     // ahead through comments.
10788     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10789       Context.getCommentForDecl(Group[i], &PP);
10790   }
10791 }
10792 
10793 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10794 /// to introduce parameters into function prototype scope.
10795 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10796   const DeclSpec &DS = D.getDeclSpec();
10797 
10798   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10799 
10800   // C++03 [dcl.stc]p2 also permits 'auto'.
10801   StorageClass SC = SC_None;
10802   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10803     SC = SC_Register;
10804   } else if (getLangOpts().CPlusPlus &&
10805              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10806     SC = SC_Auto;
10807   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10808     Diag(DS.getStorageClassSpecLoc(),
10809          diag::err_invalid_storage_class_in_func_decl);
10810     D.getMutableDeclSpec().ClearStorageClassSpecs();
10811   }
10812 
10813   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10814     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10815       << DeclSpec::getSpecifierName(TSCS);
10816   if (DS.isInlineSpecified())
10817     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
10818         << getLangOpts().CPlusPlus1z;
10819   if (DS.isConstexprSpecified())
10820     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10821       << 0;
10822   if (DS.isConceptSpecified())
10823     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10824 
10825   DiagnoseFunctionSpecifiers(DS);
10826 
10827   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10828   QualType parmDeclType = TInfo->getType();
10829 
10830   if (getLangOpts().CPlusPlus) {
10831     // Check that there are no default arguments inside the type of this
10832     // parameter.
10833     CheckExtraCXXDefaultArguments(D);
10834 
10835     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10836     if (D.getCXXScopeSpec().isSet()) {
10837       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10838         << D.getCXXScopeSpec().getRange();
10839       D.getCXXScopeSpec().clear();
10840     }
10841   }
10842 
10843   // Ensure we have a valid name
10844   IdentifierInfo *II = nullptr;
10845   if (D.hasName()) {
10846     II = D.getIdentifier();
10847     if (!II) {
10848       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10849         << GetNameForDeclarator(D).getName();
10850       D.setInvalidType(true);
10851     }
10852   }
10853 
10854   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10855   if (II) {
10856     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10857                    ForRedeclaration);
10858     LookupName(R, S);
10859     if (R.isSingleResult()) {
10860       NamedDecl *PrevDecl = R.getFoundDecl();
10861       if (PrevDecl->isTemplateParameter()) {
10862         // Maybe we will complain about the shadowed template parameter.
10863         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10864         // Just pretend that we didn't see the previous declaration.
10865         PrevDecl = nullptr;
10866       } else if (S->isDeclScope(PrevDecl)) {
10867         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10868         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10869 
10870         // Recover by removing the name
10871         II = nullptr;
10872         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10873         D.setInvalidType(true);
10874       }
10875     }
10876   }
10877 
10878   // Temporarily put parameter variables in the translation unit, not
10879   // the enclosing context.  This prevents them from accidentally
10880   // looking like class members in C++.
10881   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10882                                     D.getLocStart(),
10883                                     D.getIdentifierLoc(), II,
10884                                     parmDeclType, TInfo,
10885                                     SC);
10886 
10887   if (D.isInvalidType())
10888     New->setInvalidDecl();
10889 
10890   assert(S->isFunctionPrototypeScope());
10891   assert(S->getFunctionPrototypeDepth() >= 1);
10892   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10893                     S->getNextFunctionPrototypeIndex());
10894 
10895   // Add the parameter declaration into this scope.
10896   S->AddDecl(New);
10897   if (II)
10898     IdResolver.AddDecl(New);
10899 
10900   ProcessDeclAttributes(S, New, D);
10901 
10902   if (D.getDeclSpec().isModulePrivateSpecified())
10903     Diag(New->getLocation(), diag::err_module_private_local)
10904       << 1 << New->getDeclName()
10905       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10906       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10907 
10908   if (New->hasAttr<BlocksAttr>()) {
10909     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10910   }
10911   return New;
10912 }
10913 
10914 /// \brief Synthesizes a variable for a parameter arising from a
10915 /// typedef.
10916 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10917                                               SourceLocation Loc,
10918                                               QualType T) {
10919   /* FIXME: setting StartLoc == Loc.
10920      Would it be worth to modify callers so as to provide proper source
10921      location for the unnamed parameters, embedding the parameter's type? */
10922   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10923                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10924                                            SC_None, nullptr);
10925   Param->setImplicit();
10926   return Param;
10927 }
10928 
10929 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
10930   // Don't diagnose unused-parameter errors in template instantiations; we
10931   // will already have done so in the template itself.
10932   if (!ActiveTemplateInstantiations.empty())
10933     return;
10934 
10935   for (const ParmVarDecl *Parameter : Parameters) {
10936     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
10937         !Parameter->hasAttr<UnusedAttr>()) {
10938       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
10939         << Parameter->getDeclName();
10940     }
10941   }
10942 }
10943 
10944 void Sema::DiagnoseSizeOfParametersAndReturnValue(
10945     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
10946   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10947     return;
10948 
10949   // Warn if the return value is pass-by-value and larger than the specified
10950   // threshold.
10951   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10952     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10953     if (Size > LangOpts.NumLargeByValueCopy)
10954       Diag(D->getLocation(), diag::warn_return_value_size)
10955           << D->getDeclName() << Size;
10956   }
10957 
10958   // Warn if any parameter is pass-by-value and larger than the specified
10959   // threshold.
10960   for (const ParmVarDecl *Parameter : Parameters) {
10961     QualType T = Parameter->getType();
10962     if (T->isDependentType() || !T.isPODType(Context))
10963       continue;
10964     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10965     if (Size > LangOpts.NumLargeByValueCopy)
10966       Diag(Parameter->getLocation(), diag::warn_parameter_size)
10967           << Parameter->getDeclName() << Size;
10968   }
10969 }
10970 
10971 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10972                                   SourceLocation NameLoc, IdentifierInfo *Name,
10973                                   QualType T, TypeSourceInfo *TSInfo,
10974                                   StorageClass SC) {
10975   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10976   if (getLangOpts().ObjCAutoRefCount &&
10977       T.getObjCLifetime() == Qualifiers::OCL_None &&
10978       T->isObjCLifetimeType()) {
10979 
10980     Qualifiers::ObjCLifetime lifetime;
10981 
10982     // Special cases for arrays:
10983     //   - if it's const, use __unsafe_unretained
10984     //   - otherwise, it's an error
10985     if (T->isArrayType()) {
10986       if (!T.isConstQualified()) {
10987         DelayedDiagnostics.add(
10988             sema::DelayedDiagnostic::makeForbiddenType(
10989             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10990       }
10991       lifetime = Qualifiers::OCL_ExplicitNone;
10992     } else {
10993       lifetime = T->getObjCARCImplicitLifetime();
10994     }
10995     T = Context.getLifetimeQualifiedType(T, lifetime);
10996   }
10997 
10998   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10999                                          Context.getAdjustedParameterType(T),
11000                                          TSInfo, SC, nullptr);
11001 
11002   // Parameters can not be abstract class types.
11003   // For record types, this is done by the AbstractClassUsageDiagnoser once
11004   // the class has been completely parsed.
11005   if (!CurContext->isRecord() &&
11006       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11007                              AbstractParamType))
11008     New->setInvalidDecl();
11009 
11010   // Parameter declarators cannot be interface types. All ObjC objects are
11011   // passed by reference.
11012   if (T->isObjCObjectType()) {
11013     SourceLocation TypeEndLoc =
11014         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11015     Diag(NameLoc,
11016          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11017       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11018     T = Context.getObjCObjectPointerType(T);
11019     New->setType(T);
11020   }
11021 
11022   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11023   // duration shall not be qualified by an address-space qualifier."
11024   // Since all parameters have automatic store duration, they can not have
11025   // an address space.
11026   if (T.getAddressSpace() != 0) {
11027     // OpenCL allows function arguments declared to be an array of a type
11028     // to be qualified with an address space.
11029     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11030       Diag(NameLoc, diag::err_arg_with_address_space);
11031       New->setInvalidDecl();
11032     }
11033   }
11034 
11035   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
11036   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
11037   if (getLangOpts().OpenCL && T->isPointerType()) {
11038     const QualType PTy = T->getPointeeType();
11039     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
11040       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
11041       New->setInvalidDecl();
11042     }
11043   }
11044 
11045   return New;
11046 }
11047 
11048 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11049                                            SourceLocation LocAfterDecls) {
11050   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11051 
11052   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11053   // for a K&R function.
11054   if (!FTI.hasPrototype) {
11055     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11056       --i;
11057       if (FTI.Params[i].Param == nullptr) {
11058         SmallString<256> Code;
11059         llvm::raw_svector_ostream(Code)
11060             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11061         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11062             << FTI.Params[i].Ident
11063             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11064 
11065         // Implicitly declare the argument as type 'int' for lack of a better
11066         // type.
11067         AttributeFactory attrs;
11068         DeclSpec DS(attrs);
11069         const char* PrevSpec; // unused
11070         unsigned DiagID; // unused
11071         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11072                            DiagID, Context.getPrintingPolicy());
11073         // Use the identifier location for the type source range.
11074         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11075         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11076         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11077         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11078         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11079       }
11080     }
11081   }
11082 }
11083 
11084 Decl *
11085 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11086                               MultiTemplateParamsArg TemplateParameterLists,
11087                               SkipBodyInfo *SkipBody) {
11088   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11089   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11090   Scope *ParentScope = FnBodyScope->getParent();
11091 
11092   D.setFunctionDefinitionKind(FDK_Definition);
11093   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11094   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11095 }
11096 
11097 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11098   Consumer.HandleInlineFunctionDefinition(D);
11099 }
11100 
11101 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11102                              const FunctionDecl*& PossibleZeroParamPrototype) {
11103   // Don't warn about invalid declarations.
11104   if (FD->isInvalidDecl())
11105     return false;
11106 
11107   // Or declarations that aren't global.
11108   if (!FD->isGlobal())
11109     return false;
11110 
11111   // Don't warn about C++ member functions.
11112   if (isa<CXXMethodDecl>(FD))
11113     return false;
11114 
11115   // Don't warn about 'main'.
11116   if (FD->isMain())
11117     return false;
11118 
11119   // Don't warn about inline functions.
11120   if (FD->isInlined())
11121     return false;
11122 
11123   // Don't warn about function templates.
11124   if (FD->getDescribedFunctionTemplate())
11125     return false;
11126 
11127   // Don't warn about function template specializations.
11128   if (FD->isFunctionTemplateSpecialization())
11129     return false;
11130 
11131   // Don't warn for OpenCL kernels.
11132   if (FD->hasAttr<OpenCLKernelAttr>())
11133     return false;
11134 
11135   // Don't warn on explicitly deleted functions.
11136   if (FD->isDeleted())
11137     return false;
11138 
11139   bool MissingPrototype = true;
11140   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11141        Prev; Prev = Prev->getPreviousDecl()) {
11142     // Ignore any declarations that occur in function or method
11143     // scope, because they aren't visible from the header.
11144     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11145       continue;
11146 
11147     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11148     if (FD->getNumParams() == 0)
11149       PossibleZeroParamPrototype = Prev;
11150     break;
11151   }
11152 
11153   return MissingPrototype;
11154 }
11155 
11156 void
11157 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11158                                    const FunctionDecl *EffectiveDefinition,
11159                                    SkipBodyInfo *SkipBody) {
11160   // Don't complain if we're in GNU89 mode and the previous definition
11161   // was an extern inline function.
11162   const FunctionDecl *Definition = EffectiveDefinition;
11163   if (!Definition)
11164     if (!FD->isDefined(Definition))
11165       return;
11166 
11167   if (canRedefineFunction(Definition, getLangOpts()))
11168     return;
11169 
11170   // If we don't have a visible definition of the function, and it's inline or
11171   // a template, skip the new definition.
11172   if (SkipBody && !hasVisibleDefinition(Definition) &&
11173       (Definition->getFormalLinkage() == InternalLinkage ||
11174        Definition->isInlined() ||
11175        Definition->getDescribedFunctionTemplate() ||
11176        Definition->getNumTemplateParameterLists())) {
11177     SkipBody->ShouldSkip = true;
11178     if (auto *TD = Definition->getDescribedFunctionTemplate())
11179       makeMergedDefinitionVisible(TD, FD->getLocation());
11180     else
11181       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11182                                   FD->getLocation());
11183     return;
11184   }
11185 
11186   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11187       Definition->getStorageClass() == SC_Extern)
11188     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11189         << FD->getDeclName() << getLangOpts().CPlusPlus;
11190   else
11191     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11192 
11193   Diag(Definition->getLocation(), diag::note_previous_definition);
11194   FD->setInvalidDecl();
11195 }
11196 
11197 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11198                                    Sema &S) {
11199   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11200 
11201   LambdaScopeInfo *LSI = S.PushLambdaScope();
11202   LSI->CallOperator = CallOperator;
11203   LSI->Lambda = LambdaClass;
11204   LSI->ReturnType = CallOperator->getReturnType();
11205   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11206 
11207   if (LCD == LCD_None)
11208     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11209   else if (LCD == LCD_ByCopy)
11210     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11211   else if (LCD == LCD_ByRef)
11212     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11213   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11214 
11215   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11216   LSI->Mutable = !CallOperator->isConst();
11217 
11218   // Add the captures to the LSI so they can be noted as already
11219   // captured within tryCaptureVar.
11220   auto I = LambdaClass->field_begin();
11221   for (const auto &C : LambdaClass->captures()) {
11222     if (C.capturesVariable()) {
11223       VarDecl *VD = C.getCapturedVar();
11224       if (VD->isInitCapture())
11225         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11226       QualType CaptureType = VD->getType();
11227       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11228       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11229           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11230           /*EllipsisLoc*/C.isPackExpansion()
11231                          ? C.getEllipsisLoc() : SourceLocation(),
11232           CaptureType, /*Expr*/ nullptr);
11233 
11234     } else if (C.capturesThis()) {
11235       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11236                               /*Expr*/ nullptr,
11237                               C.getCaptureKind() == LCK_StarThis);
11238     } else {
11239       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11240     }
11241     ++I;
11242   }
11243 }
11244 
11245 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11246                                     SkipBodyInfo *SkipBody) {
11247   // Clear the last template instantiation error context.
11248   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11249 
11250   if (!D)
11251     return D;
11252   FunctionDecl *FD = nullptr;
11253 
11254   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11255     FD = FunTmpl->getTemplatedDecl();
11256   else
11257     FD = cast<FunctionDecl>(D);
11258 
11259   // See if this is a redefinition.
11260   if (!FD->isLateTemplateParsed()) {
11261     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11262 
11263     // If we're skipping the body, we're done. Don't enter the scope.
11264     if (SkipBody && SkipBody->ShouldSkip)
11265       return D;
11266   }
11267 
11268   // If we are instantiating a generic lambda call operator, push
11269   // a LambdaScopeInfo onto the function stack.  But use the information
11270   // that's already been calculated (ActOnLambdaExpr) to prime the current
11271   // LambdaScopeInfo.
11272   // When the template operator is being specialized, the LambdaScopeInfo,
11273   // has to be properly restored so that tryCaptureVariable doesn't try
11274   // and capture any new variables. In addition when calculating potential
11275   // captures during transformation of nested lambdas, it is necessary to
11276   // have the LSI properly restored.
11277   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11278     assert(ActiveTemplateInstantiations.size() &&
11279       "There should be an active template instantiation on the stack "
11280       "when instantiating a generic lambda!");
11281     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11282   }
11283   else
11284     // Enter a new function scope
11285     PushFunctionScope();
11286 
11287   // Builtin functions cannot be defined.
11288   if (unsigned BuiltinID = FD->getBuiltinID()) {
11289     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11290         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11291       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11292       FD->setInvalidDecl();
11293     }
11294   }
11295 
11296   // The return type of a function definition must be complete
11297   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11298   QualType ResultType = FD->getReturnType();
11299   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11300       !FD->isInvalidDecl() &&
11301       RequireCompleteType(FD->getLocation(), ResultType,
11302                           diag::err_func_def_incomplete_result))
11303     FD->setInvalidDecl();
11304 
11305   if (FnBodyScope)
11306     PushDeclContext(FnBodyScope, FD);
11307 
11308   // Check the validity of our function parameters
11309   CheckParmsForFunctionDef(FD->parameters(),
11310                            /*CheckParameterNames=*/true);
11311 
11312   // Introduce our parameters into the function scope
11313   for (auto Param : FD->parameters()) {
11314     Param->setOwningFunction(FD);
11315 
11316     // If this has an identifier, add it to the scope stack.
11317     if (Param->getIdentifier() && FnBodyScope) {
11318       CheckShadow(FnBodyScope, Param);
11319 
11320       PushOnScopeChains(Param, FnBodyScope);
11321     }
11322   }
11323 
11324   // If we had any tags defined in the function prototype,
11325   // introduce them into the function scope.
11326   if (FnBodyScope) {
11327     for (ArrayRef<NamedDecl *>::iterator
11328              I = FD->getDeclsInPrototypeScope().begin(),
11329              E = FD->getDeclsInPrototypeScope().end();
11330          I != E; ++I) {
11331       NamedDecl *D = *I;
11332 
11333       // Some of these decls (like enums) may have been pinned to the
11334       // translation unit for lack of a real context earlier. If so, remove
11335       // from the translation unit and reattach to the current context.
11336       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11337         // Is the decl actually in the context?
11338         if (Context.getTranslationUnitDecl()->containsDecl(D))
11339           Context.getTranslationUnitDecl()->removeDecl(D);
11340         // Either way, reassign the lexical decl context to our FunctionDecl.
11341         D->setLexicalDeclContext(CurContext);
11342       }
11343 
11344       // If the decl has a non-null name, make accessible in the current scope.
11345       if (!D->getName().empty())
11346         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11347 
11348       // Similarly, dive into enums and fish their constants out, making them
11349       // accessible in this scope.
11350       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11351         for (auto *EI : ED->enumerators())
11352           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11353       }
11354     }
11355   }
11356 
11357   // Ensure that the function's exception specification is instantiated.
11358   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11359     ResolveExceptionSpec(D->getLocation(), FPT);
11360 
11361   // dllimport cannot be applied to non-inline function definitions.
11362   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11363       !FD->isTemplateInstantiation()) {
11364     assert(!FD->hasAttr<DLLExportAttr>());
11365     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11366     FD->setInvalidDecl();
11367     return D;
11368   }
11369   // We want to attach documentation to original Decl (which might be
11370   // a function template).
11371   ActOnDocumentableDecl(D);
11372   if (getCurLexicalContext()->isObjCContainer() &&
11373       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11374       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11375     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11376 
11377   return D;
11378 }
11379 
11380 /// \brief Given the set of return statements within a function body,
11381 /// compute the variables that are subject to the named return value
11382 /// optimization.
11383 ///
11384 /// Each of the variables that is subject to the named return value
11385 /// optimization will be marked as NRVO variables in the AST, and any
11386 /// return statement that has a marked NRVO variable as its NRVO candidate can
11387 /// use the named return value optimization.
11388 ///
11389 /// This function applies a very simplistic algorithm for NRVO: if every return
11390 /// statement in the scope of a variable has the same NRVO candidate, that
11391 /// candidate is an NRVO variable.
11392 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11393   ReturnStmt **Returns = Scope->Returns.data();
11394 
11395   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11396     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11397       if (!NRVOCandidate->isNRVOVariable())
11398         Returns[I]->setNRVOCandidate(nullptr);
11399     }
11400   }
11401 }
11402 
11403 bool Sema::canDelayFunctionBody(const Declarator &D) {
11404   // We can't delay parsing the body of a constexpr function template (yet).
11405   if (D.getDeclSpec().isConstexprSpecified())
11406     return false;
11407 
11408   // We can't delay parsing the body of a function template with a deduced
11409   // return type (yet).
11410   if (D.getDeclSpec().containsPlaceholderType()) {
11411     // If the placeholder introduces a non-deduced trailing return type,
11412     // we can still delay parsing it.
11413     if (D.getNumTypeObjects()) {
11414       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11415       if (Outer.Kind == DeclaratorChunk::Function &&
11416           Outer.Fun.hasTrailingReturnType()) {
11417         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11418         return Ty.isNull() || !Ty->isUndeducedType();
11419       }
11420     }
11421     return false;
11422   }
11423 
11424   return true;
11425 }
11426 
11427 bool Sema::canSkipFunctionBody(Decl *D) {
11428   // We cannot skip the body of a function (or function template) which is
11429   // constexpr, since we may need to evaluate its body in order to parse the
11430   // rest of the file.
11431   // We cannot skip the body of a function with an undeduced return type,
11432   // because any callers of that function need to know the type.
11433   if (const FunctionDecl *FD = D->getAsFunction())
11434     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11435       return false;
11436   return Consumer.shouldSkipFunctionBody(D);
11437 }
11438 
11439 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11440   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11441     FD->setHasSkippedBody();
11442   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11443     MD->setHasSkippedBody();
11444   return Decl;
11445 }
11446 
11447 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11448   return ActOnFinishFunctionBody(D, BodyArg, false);
11449 }
11450 
11451 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11452                                     bool IsInstantiation) {
11453   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11454 
11455   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11456   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11457 
11458   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11459     CheckCompletedCoroutineBody(FD, Body);
11460 
11461   if (FD) {
11462     FD->setBody(Body);
11463 
11464     if (getLangOpts().CPlusPlus14) {
11465       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11466           FD->getReturnType()->isUndeducedType()) {
11467         // If the function has a deduced result type but contains no 'return'
11468         // statements, the result type as written must be exactly 'auto', and
11469         // the deduced result type is 'void'.
11470         if (!FD->getReturnType()->getAs<AutoType>()) {
11471           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11472               << FD->getReturnType();
11473           FD->setInvalidDecl();
11474         } else {
11475           // Substitute 'void' for the 'auto' in the type.
11476           TypeLoc ResultType = getReturnTypeLoc(FD);
11477           Context.adjustDeducedFunctionResultType(
11478               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11479         }
11480       }
11481     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11482       // In C++11, we don't use 'auto' deduction rules for lambda call
11483       // operators because we don't support return type deduction.
11484       auto *LSI = getCurLambda();
11485       if (LSI->HasImplicitReturnType) {
11486         deduceClosureReturnType(*LSI);
11487 
11488         // C++11 [expr.prim.lambda]p4:
11489         //   [...] if there are no return statements in the compound-statement
11490         //   [the deduced type is] the type void
11491         QualType RetType =
11492             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11493 
11494         // Update the return type to the deduced type.
11495         const FunctionProtoType *Proto =
11496             FD->getType()->getAs<FunctionProtoType>();
11497         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11498                                             Proto->getExtProtoInfo()));
11499       }
11500     }
11501 
11502     // The only way to be included in UndefinedButUsed is if there is an
11503     // ODR use before the definition. Avoid the expensive map lookup if this
11504     // is the first declaration.
11505     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11506       if (!FD->isExternallyVisible())
11507         UndefinedButUsed.erase(FD);
11508       else if (FD->isInlined() &&
11509                !LangOpts.GNUInline &&
11510                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11511         UndefinedButUsed.erase(FD);
11512     }
11513 
11514     // If the function implicitly returns zero (like 'main') or is naked,
11515     // don't complain about missing return statements.
11516     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11517       WP.disableCheckFallThrough();
11518 
11519     // MSVC permits the use of pure specifier (=0) on function definition,
11520     // defined at class scope, warn about this non-standard construct.
11521     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11522       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11523 
11524     if (!FD->isInvalidDecl()) {
11525       // Don't diagnose unused parameters of defaulted or deleted functions.
11526       if (!FD->isDeleted() && !FD->isDefaulted())
11527         DiagnoseUnusedParameters(FD->parameters());
11528       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11529                                              FD->getReturnType(), FD);
11530 
11531       // If this is a structor, we need a vtable.
11532       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11533         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11534       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11535         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11536 
11537       // Try to apply the named return value optimization. We have to check
11538       // if we can do this here because lambdas keep return statements around
11539       // to deduce an implicit return type.
11540       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11541           !FD->isDependentContext())
11542         computeNRVO(Body, getCurFunction());
11543     }
11544 
11545     // GNU warning -Wmissing-prototypes:
11546     //   Warn if a global function is defined without a previous
11547     //   prototype declaration. This warning is issued even if the
11548     //   definition itself provides a prototype. The aim is to detect
11549     //   global functions that fail to be declared in header files.
11550     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11551     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11552       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11553 
11554       if (PossibleZeroParamPrototype) {
11555         // We found a declaration that is not a prototype,
11556         // but that could be a zero-parameter prototype
11557         if (TypeSourceInfo *TI =
11558                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11559           TypeLoc TL = TI->getTypeLoc();
11560           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11561             Diag(PossibleZeroParamPrototype->getLocation(),
11562                  diag::note_declaration_not_a_prototype)
11563                 << PossibleZeroParamPrototype
11564                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11565         }
11566       }
11567     }
11568 
11569     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11570       const CXXMethodDecl *KeyFunction;
11571       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11572           MD->isVirtual() &&
11573           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11574           MD == KeyFunction->getCanonicalDecl()) {
11575         // Update the key-function state if necessary for this ABI.
11576         if (FD->isInlined() &&
11577             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11578           Context.setNonKeyFunction(MD);
11579 
11580           // If the newly-chosen key function is already defined, then we
11581           // need to mark the vtable as used retroactively.
11582           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11583           const FunctionDecl *Definition;
11584           if (KeyFunction && KeyFunction->isDefined(Definition))
11585             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11586         } else {
11587           // We just defined they key function; mark the vtable as used.
11588           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11589         }
11590       }
11591     }
11592 
11593     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11594            "Function parsing confused");
11595   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11596     assert(MD == getCurMethodDecl() && "Method parsing confused");
11597     MD->setBody(Body);
11598     if (!MD->isInvalidDecl()) {
11599       DiagnoseUnusedParameters(MD->parameters());
11600       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11601                                              MD->getReturnType(), MD);
11602 
11603       if (Body)
11604         computeNRVO(Body, getCurFunction());
11605     }
11606     if (getCurFunction()->ObjCShouldCallSuper) {
11607       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11608         << MD->getSelector().getAsString();
11609       getCurFunction()->ObjCShouldCallSuper = false;
11610     }
11611     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11612       const ObjCMethodDecl *InitMethod = nullptr;
11613       bool isDesignated =
11614           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11615       assert(isDesignated && InitMethod);
11616       (void)isDesignated;
11617 
11618       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11619         auto IFace = MD->getClassInterface();
11620         if (!IFace)
11621           return false;
11622         auto SuperD = IFace->getSuperClass();
11623         if (!SuperD)
11624           return false;
11625         return SuperD->getIdentifier() ==
11626             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11627       };
11628       // Don't issue this warning for unavailable inits or direct subclasses
11629       // of NSObject.
11630       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11631         Diag(MD->getLocation(),
11632              diag::warn_objc_designated_init_missing_super_call);
11633         Diag(InitMethod->getLocation(),
11634              diag::note_objc_designated_init_marked_here);
11635       }
11636       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11637     }
11638     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11639       // Don't issue this warning for unavaialable inits.
11640       if (!MD->isUnavailable())
11641         Diag(MD->getLocation(),
11642              diag::warn_objc_secondary_init_missing_init_call);
11643       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11644     }
11645   } else {
11646     return nullptr;
11647   }
11648 
11649   assert(!getCurFunction()->ObjCShouldCallSuper &&
11650          "This should only be set for ObjC methods, which should have been "
11651          "handled in the block above.");
11652 
11653   // Verify and clean out per-function state.
11654   if (Body && (!FD || !FD->isDefaulted())) {
11655     // C++ constructors that have function-try-blocks can't have return
11656     // statements in the handlers of that block. (C++ [except.handle]p14)
11657     // Verify this.
11658     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11659       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11660 
11661     // Verify that gotos and switch cases don't jump into scopes illegally.
11662     if (getCurFunction()->NeedsScopeChecking() &&
11663         !PP.isCodeCompletionEnabled())
11664       DiagnoseInvalidJumps(Body);
11665 
11666     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11667       if (!Destructor->getParent()->isDependentType())
11668         CheckDestructor(Destructor);
11669 
11670       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11671                                              Destructor->getParent());
11672     }
11673 
11674     // If any errors have occurred, clear out any temporaries that may have
11675     // been leftover. This ensures that these temporaries won't be picked up for
11676     // deletion in some later function.
11677     if (getDiagnostics().hasErrorOccurred() ||
11678         getDiagnostics().getSuppressAllDiagnostics()) {
11679       DiscardCleanupsInEvaluationContext();
11680     }
11681     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11682         !isa<FunctionTemplateDecl>(dcl)) {
11683       // Since the body is valid, issue any analysis-based warnings that are
11684       // enabled.
11685       ActivePolicy = &WP;
11686     }
11687 
11688     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11689         (!CheckConstexprFunctionDecl(FD) ||
11690          !CheckConstexprFunctionBody(FD, Body)))
11691       FD->setInvalidDecl();
11692 
11693     if (FD && FD->hasAttr<NakedAttr>()) {
11694       for (const Stmt *S : Body->children()) {
11695         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11696           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11697           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11698           FD->setInvalidDecl();
11699           break;
11700         }
11701       }
11702     }
11703 
11704     assert(ExprCleanupObjects.size() ==
11705                ExprEvalContexts.back().NumCleanupObjects &&
11706            "Leftover temporaries in function");
11707     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
11708     assert(MaybeODRUseExprs.empty() &&
11709            "Leftover expressions for odr-use checking");
11710   }
11711 
11712   if (!IsInstantiation)
11713     PopDeclContext();
11714 
11715   PopFunctionScopeInfo(ActivePolicy, dcl);
11716   // If any errors have occurred, clear out any temporaries that may have
11717   // been leftover. This ensures that these temporaries won't be picked up for
11718   // deletion in some later function.
11719   if (getDiagnostics().hasErrorOccurred()) {
11720     DiscardCleanupsInEvaluationContext();
11721   }
11722 
11723   return dcl;
11724 }
11725 
11726 /// When we finish delayed parsing of an attribute, we must attach it to the
11727 /// relevant Decl.
11728 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11729                                        ParsedAttributes &Attrs) {
11730   // Always attach attributes to the underlying decl.
11731   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11732     D = TD->getTemplatedDecl();
11733   ProcessDeclAttributeList(S, D, Attrs.getList());
11734 
11735   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11736     if (Method->isStatic())
11737       checkThisInStaticMemberFunctionAttributes(Method);
11738 }
11739 
11740 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11741 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11742 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11743                                           IdentifierInfo &II, Scope *S) {
11744   // Before we produce a declaration for an implicitly defined
11745   // function, see whether there was a locally-scoped declaration of
11746   // this name as a function or variable. If so, use that
11747   // (non-visible) declaration, and complain about it.
11748   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11749     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11750     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11751     return ExternCPrev;
11752   }
11753 
11754   // Extension in C99.  Legal in C90, but warn about it.
11755   unsigned diag_id;
11756   if (II.getName().startswith("__builtin_"))
11757     diag_id = diag::warn_builtin_unknown;
11758   else if (getLangOpts().C99)
11759     diag_id = diag::ext_implicit_function_decl;
11760   else
11761     diag_id = diag::warn_implicit_function_decl;
11762   Diag(Loc, diag_id) << &II;
11763 
11764   // Because typo correction is expensive, only do it if the implicit
11765   // function declaration is going to be treated as an error.
11766   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11767     TypoCorrection Corrected;
11768     if (S &&
11769         (Corrected = CorrectTypo(
11770              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11771              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11772       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11773                    /*ErrorRecovery*/false);
11774   }
11775 
11776   // Set a Declarator for the implicit definition: int foo();
11777   const char *Dummy;
11778   AttributeFactory attrFactory;
11779   DeclSpec DS(attrFactory);
11780   unsigned DiagID;
11781   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11782                                   Context.getPrintingPolicy());
11783   (void)Error; // Silence warning.
11784   assert(!Error && "Error setting up implicit decl!");
11785   SourceLocation NoLoc;
11786   Declarator D(DS, Declarator::BlockContext);
11787   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11788                                              /*IsAmbiguous=*/false,
11789                                              /*LParenLoc=*/NoLoc,
11790                                              /*Params=*/nullptr,
11791                                              /*NumParams=*/0,
11792                                              /*EllipsisLoc=*/NoLoc,
11793                                              /*RParenLoc=*/NoLoc,
11794                                              /*TypeQuals=*/0,
11795                                              /*RefQualifierIsLvalueRef=*/true,
11796                                              /*RefQualifierLoc=*/NoLoc,
11797                                              /*ConstQualifierLoc=*/NoLoc,
11798                                              /*VolatileQualifierLoc=*/NoLoc,
11799                                              /*RestrictQualifierLoc=*/NoLoc,
11800                                              /*MutableLoc=*/NoLoc,
11801                                              EST_None,
11802                                              /*ESpecRange=*/SourceRange(),
11803                                              /*Exceptions=*/nullptr,
11804                                              /*ExceptionRanges=*/nullptr,
11805                                              /*NumExceptions=*/0,
11806                                              /*NoexceptExpr=*/nullptr,
11807                                              /*ExceptionSpecTokens=*/nullptr,
11808                                              Loc, Loc, D),
11809                 DS.getAttributes(),
11810                 SourceLocation());
11811   D.SetIdentifier(&II, Loc);
11812 
11813   // Insert this function into translation-unit scope.
11814 
11815   DeclContext *PrevDC = CurContext;
11816   CurContext = Context.getTranslationUnitDecl();
11817 
11818   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11819   FD->setImplicit();
11820 
11821   CurContext = PrevDC;
11822 
11823   AddKnownFunctionAttributes(FD);
11824 
11825   return FD;
11826 }
11827 
11828 /// \brief Adds any function attributes that we know a priori based on
11829 /// the declaration of this function.
11830 ///
11831 /// These attributes can apply both to implicitly-declared builtins
11832 /// (like __builtin___printf_chk) or to library-declared functions
11833 /// like NSLog or printf.
11834 ///
11835 /// We need to check for duplicate attributes both here and where user-written
11836 /// attributes are applied to declarations.
11837 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11838   if (FD->isInvalidDecl())
11839     return;
11840 
11841   // If this is a built-in function, map its builtin attributes to
11842   // actual attributes.
11843   if (unsigned BuiltinID = FD->getBuiltinID()) {
11844     // Handle printf-formatting attributes.
11845     unsigned FormatIdx;
11846     bool HasVAListArg;
11847     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11848       if (!FD->hasAttr<FormatAttr>()) {
11849         const char *fmt = "printf";
11850         unsigned int NumParams = FD->getNumParams();
11851         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11852             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11853           fmt = "NSString";
11854         FD->addAttr(FormatAttr::CreateImplicit(Context,
11855                                                &Context.Idents.get(fmt),
11856                                                FormatIdx+1,
11857                                                HasVAListArg ? 0 : FormatIdx+2,
11858                                                FD->getLocation()));
11859       }
11860     }
11861     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11862                                              HasVAListArg)) {
11863      if (!FD->hasAttr<FormatAttr>())
11864        FD->addAttr(FormatAttr::CreateImplicit(Context,
11865                                               &Context.Idents.get("scanf"),
11866                                               FormatIdx+1,
11867                                               HasVAListArg ? 0 : FormatIdx+2,
11868                                               FD->getLocation()));
11869     }
11870 
11871     // Mark const if we don't care about errno and that is the only
11872     // thing preventing the function from being const. This allows
11873     // IRgen to use LLVM intrinsics for such functions.
11874     if (!getLangOpts().MathErrno &&
11875         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11876       if (!FD->hasAttr<ConstAttr>())
11877         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11878     }
11879 
11880     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11881         !FD->hasAttr<ReturnsTwiceAttr>())
11882       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11883                                          FD->getLocation()));
11884     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11885       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11886     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11887       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11888     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11889       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11890     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11891         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11892       // Add the appropriate attribute, depending on the CUDA compilation mode
11893       // and which target the builtin belongs to. For example, during host
11894       // compilation, aux builtins are __device__, while the rest are __host__.
11895       if (getLangOpts().CUDAIsDevice !=
11896           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11897         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11898       else
11899         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11900     }
11901   }
11902 
11903   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11904   // throw, add an implicit nothrow attribute to any extern "C" function we come
11905   // across.
11906   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11907       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11908     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11909     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11910       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11911   }
11912 
11913   IdentifierInfo *Name = FD->getIdentifier();
11914   if (!Name)
11915     return;
11916   if ((!getLangOpts().CPlusPlus &&
11917        FD->getDeclContext()->isTranslationUnit()) ||
11918       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11919        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11920        LinkageSpecDecl::lang_c)) {
11921     // Okay: this could be a libc/libm/Objective-C function we know
11922     // about.
11923   } else
11924     return;
11925 
11926   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11927     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11928     // target-specific builtins, perhaps?
11929     if (!FD->hasAttr<FormatAttr>())
11930       FD->addAttr(FormatAttr::CreateImplicit(Context,
11931                                              &Context.Idents.get("printf"), 2,
11932                                              Name->isStr("vasprintf") ? 0 : 3,
11933                                              FD->getLocation()));
11934   }
11935 
11936   if (Name->isStr("__CFStringMakeConstantString")) {
11937     // We already have a __builtin___CFStringMakeConstantString,
11938     // but builds that use -fno-constant-cfstrings don't go through that.
11939     if (!FD->hasAttr<FormatArgAttr>())
11940       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11941                                                 FD->getLocation()));
11942   }
11943 }
11944 
11945 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11946                                     TypeSourceInfo *TInfo) {
11947   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11948   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11949 
11950   if (!TInfo) {
11951     assert(D.isInvalidType() && "no declarator info for valid type");
11952     TInfo = Context.getTrivialTypeSourceInfo(T);
11953   }
11954 
11955   // Scope manipulation handled by caller.
11956   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11957                                            D.getLocStart(),
11958                                            D.getIdentifierLoc(),
11959                                            D.getIdentifier(),
11960                                            TInfo);
11961 
11962   // Bail out immediately if we have an invalid declaration.
11963   if (D.isInvalidType()) {
11964     NewTD->setInvalidDecl();
11965     return NewTD;
11966   }
11967 
11968   if (D.getDeclSpec().isModulePrivateSpecified()) {
11969     if (CurContext->isFunctionOrMethod())
11970       Diag(NewTD->getLocation(), diag::err_module_private_local)
11971         << 2 << NewTD->getDeclName()
11972         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11973         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11974     else
11975       NewTD->setModulePrivate();
11976   }
11977 
11978   // C++ [dcl.typedef]p8:
11979   //   If the typedef declaration defines an unnamed class (or
11980   //   enum), the first typedef-name declared by the declaration
11981   //   to be that class type (or enum type) is used to denote the
11982   //   class type (or enum type) for linkage purposes only.
11983   // We need to check whether the type was declared in the declaration.
11984   switch (D.getDeclSpec().getTypeSpecType()) {
11985   case TST_enum:
11986   case TST_struct:
11987   case TST_interface:
11988   case TST_union:
11989   case TST_class: {
11990     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11991     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11992     break;
11993   }
11994 
11995   default:
11996     break;
11997   }
11998 
11999   return NewTD;
12000 }
12001 
12002 /// \brief Check that this is a valid underlying type for an enum declaration.
12003 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12004   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12005   QualType T = TI->getType();
12006 
12007   if (T->isDependentType())
12008     return false;
12009 
12010   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12011     if (BT->isInteger())
12012       return false;
12013 
12014   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12015   return true;
12016 }
12017 
12018 /// Check whether this is a valid redeclaration of a previous enumeration.
12019 /// \return true if the redeclaration was invalid.
12020 bool Sema::CheckEnumRedeclaration(
12021     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12022     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12023   bool IsFixed = !EnumUnderlyingTy.isNull();
12024 
12025   if (IsScoped != Prev->isScoped()) {
12026     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12027       << Prev->isScoped();
12028     Diag(Prev->getLocation(), diag::note_previous_declaration);
12029     return true;
12030   }
12031 
12032   if (IsFixed && Prev->isFixed()) {
12033     if (!EnumUnderlyingTy->isDependentType() &&
12034         !Prev->getIntegerType()->isDependentType() &&
12035         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12036                                         Prev->getIntegerType())) {
12037       // TODO: Highlight the underlying type of the redeclaration.
12038       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12039         << EnumUnderlyingTy << Prev->getIntegerType();
12040       Diag(Prev->getLocation(), diag::note_previous_declaration)
12041           << Prev->getIntegerTypeRange();
12042       return true;
12043     }
12044   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12045     ;
12046   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12047     ;
12048   } else if (IsFixed != Prev->isFixed()) {
12049     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12050       << Prev->isFixed();
12051     Diag(Prev->getLocation(), diag::note_previous_declaration);
12052     return true;
12053   }
12054 
12055   return false;
12056 }
12057 
12058 /// \brief Get diagnostic %select index for tag kind for
12059 /// redeclaration diagnostic message.
12060 /// WARNING: Indexes apply to particular diagnostics only!
12061 ///
12062 /// \returns diagnostic %select index.
12063 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12064   switch (Tag) {
12065   case TTK_Struct: return 0;
12066   case TTK_Interface: return 1;
12067   case TTK_Class:  return 2;
12068   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12069   }
12070 }
12071 
12072 /// \brief Determine if tag kind is a class-key compatible with
12073 /// class for redeclaration (class, struct, or __interface).
12074 ///
12075 /// \returns true iff the tag kind is compatible.
12076 static bool isClassCompatTagKind(TagTypeKind Tag)
12077 {
12078   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12079 }
12080 
12081 /// \brief Determine whether a tag with a given kind is acceptable
12082 /// as a redeclaration of the given tag declaration.
12083 ///
12084 /// \returns true if the new tag kind is acceptable, false otherwise.
12085 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12086                                         TagTypeKind NewTag, bool isDefinition,
12087                                         SourceLocation NewTagLoc,
12088                                         const IdentifierInfo *Name) {
12089   // C++ [dcl.type.elab]p3:
12090   //   The class-key or enum keyword present in the
12091   //   elaborated-type-specifier shall agree in kind with the
12092   //   declaration to which the name in the elaborated-type-specifier
12093   //   refers. This rule also applies to the form of
12094   //   elaborated-type-specifier that declares a class-name or
12095   //   friend class since it can be construed as referring to the
12096   //   definition of the class. Thus, in any
12097   //   elaborated-type-specifier, the enum keyword shall be used to
12098   //   refer to an enumeration (7.2), the union class-key shall be
12099   //   used to refer to a union (clause 9), and either the class or
12100   //   struct class-key shall be used to refer to a class (clause 9)
12101   //   declared using the class or struct class-key.
12102   TagTypeKind OldTag = Previous->getTagKind();
12103   if (!isDefinition || !isClassCompatTagKind(NewTag))
12104     if (OldTag == NewTag)
12105       return true;
12106 
12107   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12108     // Warn about the struct/class tag mismatch.
12109     bool isTemplate = false;
12110     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12111       isTemplate = Record->getDescribedClassTemplate();
12112 
12113     if (!ActiveTemplateInstantiations.empty()) {
12114       // In a template instantiation, do not offer fix-its for tag mismatches
12115       // since they usually mess up the template instead of fixing the problem.
12116       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12117         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12118         << getRedeclDiagFromTagKind(OldTag);
12119       return true;
12120     }
12121 
12122     if (isDefinition) {
12123       // On definitions, check previous tags and issue a fix-it for each
12124       // one that doesn't match the current tag.
12125       if (Previous->getDefinition()) {
12126         // Don't suggest fix-its for redefinitions.
12127         return true;
12128       }
12129 
12130       bool previousMismatch = false;
12131       for (auto I : Previous->redecls()) {
12132         if (I->getTagKind() != NewTag) {
12133           if (!previousMismatch) {
12134             previousMismatch = true;
12135             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12136               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12137               << getRedeclDiagFromTagKind(I->getTagKind());
12138           }
12139           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12140             << getRedeclDiagFromTagKind(NewTag)
12141             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12142                  TypeWithKeyword::getTagTypeKindName(NewTag));
12143         }
12144       }
12145       return true;
12146     }
12147 
12148     // Check for a previous definition.  If current tag and definition
12149     // are same type, do nothing.  If no definition, but disagree with
12150     // with previous tag type, give a warning, but no fix-it.
12151     const TagDecl *Redecl = Previous->getDefinition() ?
12152                             Previous->getDefinition() : Previous;
12153     if (Redecl->getTagKind() == NewTag) {
12154       return true;
12155     }
12156 
12157     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12158       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12159       << getRedeclDiagFromTagKind(OldTag);
12160     Diag(Redecl->getLocation(), diag::note_previous_use);
12161 
12162     // If there is a previous definition, suggest a fix-it.
12163     if (Previous->getDefinition()) {
12164         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12165           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12166           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12167                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12168     }
12169 
12170     return true;
12171   }
12172   return false;
12173 }
12174 
12175 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12176 /// from an outer enclosing namespace or file scope inside a friend declaration.
12177 /// This should provide the commented out code in the following snippet:
12178 ///   namespace N {
12179 ///     struct X;
12180 ///     namespace M {
12181 ///       struct Y { friend struct /*N::*/ X; };
12182 ///     }
12183 ///   }
12184 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12185                                          SourceLocation NameLoc) {
12186   // While the decl is in a namespace, do repeated lookup of that name and see
12187   // if we get the same namespace back.  If we do not, continue until
12188   // translation unit scope, at which point we have a fully qualified NNS.
12189   SmallVector<IdentifierInfo *, 4> Namespaces;
12190   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12191   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12192     // This tag should be declared in a namespace, which can only be enclosed by
12193     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12194     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12195     if (!Namespace || Namespace->isAnonymousNamespace())
12196       return FixItHint();
12197     IdentifierInfo *II = Namespace->getIdentifier();
12198     Namespaces.push_back(II);
12199     NamedDecl *Lookup = SemaRef.LookupSingleName(
12200         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12201     if (Lookup == Namespace)
12202       break;
12203   }
12204 
12205   // Once we have all the namespaces, reverse them to go outermost first, and
12206   // build an NNS.
12207   SmallString<64> Insertion;
12208   llvm::raw_svector_ostream OS(Insertion);
12209   if (DC->isTranslationUnit())
12210     OS << "::";
12211   std::reverse(Namespaces.begin(), Namespaces.end());
12212   for (auto *II : Namespaces)
12213     OS << II->getName() << "::";
12214   return FixItHint::CreateInsertion(NameLoc, Insertion);
12215 }
12216 
12217 /// \brief Determine whether a tag originally declared in context \p OldDC can
12218 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12219 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12220 /// using-declaration).
12221 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12222                                          DeclContext *NewDC) {
12223   OldDC = OldDC->getRedeclContext();
12224   NewDC = NewDC->getRedeclContext();
12225 
12226   if (OldDC->Equals(NewDC))
12227     return true;
12228 
12229   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12230   // encloses the other).
12231   if (S.getLangOpts().MSVCCompat &&
12232       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12233     return true;
12234 
12235   return false;
12236 }
12237 
12238 /// Find the DeclContext in which a tag is implicitly declared if we see an
12239 /// elaborated type specifier in the specified context, and lookup finds
12240 /// nothing.
12241 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12242   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12243     DC = DC->getParent();
12244   return DC;
12245 }
12246 
12247 /// Find the Scope in which a tag is implicitly declared if we see an
12248 /// elaborated type specifier in the specified context, and lookup finds
12249 /// nothing.
12250 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12251   while (S->isClassScope() ||
12252          (LangOpts.CPlusPlus &&
12253           S->isFunctionPrototypeScope()) ||
12254          ((S->getFlags() & Scope::DeclScope) == 0) ||
12255          (S->getEntity() && S->getEntity()->isTransparentContext()))
12256     S = S->getParent();
12257   return S;
12258 }
12259 
12260 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12261 /// former case, Name will be non-null.  In the later case, Name will be null.
12262 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12263 /// reference/declaration/definition of a tag.
12264 ///
12265 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12266 /// trailing-type-specifier) other than one in an alias-declaration.
12267 ///
12268 /// \param SkipBody If non-null, will be set to indicate if the caller should
12269 /// skip the definition of this tag and treat it as if it were a declaration.
12270 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12271                      SourceLocation KWLoc, CXXScopeSpec &SS,
12272                      IdentifierInfo *Name, SourceLocation NameLoc,
12273                      AttributeList *Attr, AccessSpecifier AS,
12274                      SourceLocation ModulePrivateLoc,
12275                      MultiTemplateParamsArg TemplateParameterLists,
12276                      bool &OwnedDecl, bool &IsDependent,
12277                      SourceLocation ScopedEnumKWLoc,
12278                      bool ScopedEnumUsesClassTag,
12279                      TypeResult UnderlyingType,
12280                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12281   // If this is not a definition, it must have a name.
12282   IdentifierInfo *OrigName = Name;
12283   assert((Name != nullptr || TUK == TUK_Definition) &&
12284          "Nameless record must be a definition!");
12285   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12286 
12287   OwnedDecl = false;
12288   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12289   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12290 
12291   // FIXME: Check explicit specializations more carefully.
12292   bool isExplicitSpecialization = false;
12293   bool Invalid = false;
12294 
12295   // We only need to do this matching if we have template parameters
12296   // or a scope specifier, which also conveniently avoids this work
12297   // for non-C++ cases.
12298   if (TemplateParameterLists.size() > 0 ||
12299       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12300     if (TemplateParameterList *TemplateParams =
12301             MatchTemplateParametersToScopeSpecifier(
12302                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12303                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12304       if (Kind == TTK_Enum) {
12305         Diag(KWLoc, diag::err_enum_template);
12306         return nullptr;
12307       }
12308 
12309       if (TemplateParams->size() > 0) {
12310         // This is a declaration or definition of a class template (which may
12311         // be a member of another template).
12312 
12313         if (Invalid)
12314           return nullptr;
12315 
12316         OwnedDecl = false;
12317         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12318                                                SS, Name, NameLoc, Attr,
12319                                                TemplateParams, AS,
12320                                                ModulePrivateLoc,
12321                                                /*FriendLoc*/SourceLocation(),
12322                                                TemplateParameterLists.size()-1,
12323                                                TemplateParameterLists.data(),
12324                                                SkipBody);
12325         return Result.get();
12326       } else {
12327         // The "template<>" header is extraneous.
12328         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12329           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12330         isExplicitSpecialization = true;
12331       }
12332     }
12333   }
12334 
12335   // Figure out the underlying type if this a enum declaration. We need to do
12336   // this early, because it's needed to detect if this is an incompatible
12337   // redeclaration.
12338   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12339   bool EnumUnderlyingIsImplicit = false;
12340 
12341   if (Kind == TTK_Enum) {
12342     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12343       // No underlying type explicitly specified, or we failed to parse the
12344       // type, default to int.
12345       EnumUnderlying = Context.IntTy.getTypePtr();
12346     else if (UnderlyingType.get()) {
12347       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12348       // integral type; any cv-qualification is ignored.
12349       TypeSourceInfo *TI = nullptr;
12350       GetTypeFromParser(UnderlyingType.get(), &TI);
12351       EnumUnderlying = TI;
12352 
12353       if (CheckEnumUnderlyingType(TI))
12354         // Recover by falling back to int.
12355         EnumUnderlying = Context.IntTy.getTypePtr();
12356 
12357       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12358                                           UPPC_FixedUnderlyingType))
12359         EnumUnderlying = Context.IntTy.getTypePtr();
12360 
12361     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12362       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12363         // Microsoft enums are always of int type.
12364         EnumUnderlying = Context.IntTy.getTypePtr();
12365         EnumUnderlyingIsImplicit = true;
12366       }
12367     }
12368   }
12369 
12370   DeclContext *SearchDC = CurContext;
12371   DeclContext *DC = CurContext;
12372   bool isStdBadAlloc = false;
12373 
12374   RedeclarationKind Redecl = ForRedeclaration;
12375   if (TUK == TUK_Friend || TUK == TUK_Reference)
12376     Redecl = NotForRedeclaration;
12377 
12378   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12379   if (Name && SS.isNotEmpty()) {
12380     // We have a nested-name tag ('struct foo::bar').
12381 
12382     // Check for invalid 'foo::'.
12383     if (SS.isInvalid()) {
12384       Name = nullptr;
12385       goto CreateNewDecl;
12386     }
12387 
12388     // If this is a friend or a reference to a class in a dependent
12389     // context, don't try to make a decl for it.
12390     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12391       DC = computeDeclContext(SS, false);
12392       if (!DC) {
12393         IsDependent = true;
12394         return nullptr;
12395       }
12396     } else {
12397       DC = computeDeclContext(SS, true);
12398       if (!DC) {
12399         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12400           << SS.getRange();
12401         return nullptr;
12402       }
12403     }
12404 
12405     if (RequireCompleteDeclContext(SS, DC))
12406       return nullptr;
12407 
12408     SearchDC = DC;
12409     // Look-up name inside 'foo::'.
12410     LookupQualifiedName(Previous, DC);
12411 
12412     if (Previous.isAmbiguous())
12413       return nullptr;
12414 
12415     if (Previous.empty()) {
12416       // Name lookup did not find anything. However, if the
12417       // nested-name-specifier refers to the current instantiation,
12418       // and that current instantiation has any dependent base
12419       // classes, we might find something at instantiation time: treat
12420       // this as a dependent elaborated-type-specifier.
12421       // But this only makes any sense for reference-like lookups.
12422       if (Previous.wasNotFoundInCurrentInstantiation() &&
12423           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12424         IsDependent = true;
12425         return nullptr;
12426       }
12427 
12428       // A tag 'foo::bar' must already exist.
12429       Diag(NameLoc, diag::err_not_tag_in_scope)
12430         << Kind << Name << DC << SS.getRange();
12431       Name = nullptr;
12432       Invalid = true;
12433       goto CreateNewDecl;
12434     }
12435   } else if (Name) {
12436     // C++14 [class.mem]p14:
12437     //   If T is the name of a class, then each of the following shall have a
12438     //   name different from T:
12439     //    -- every member of class T that is itself a type
12440     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12441         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12442       return nullptr;
12443 
12444     // If this is a named struct, check to see if there was a previous forward
12445     // declaration or definition.
12446     // FIXME: We're looking into outer scopes here, even when we
12447     // shouldn't be. Doing so can result in ambiguities that we
12448     // shouldn't be diagnosing.
12449     LookupName(Previous, S);
12450 
12451     // When declaring or defining a tag, ignore ambiguities introduced
12452     // by types using'ed into this scope.
12453     if (Previous.isAmbiguous() &&
12454         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12455       LookupResult::Filter F = Previous.makeFilter();
12456       while (F.hasNext()) {
12457         NamedDecl *ND = F.next();
12458         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12459                 SearchDC->getRedeclContext()))
12460           F.erase();
12461       }
12462       F.done();
12463     }
12464 
12465     // C++11 [namespace.memdef]p3:
12466     //   If the name in a friend declaration is neither qualified nor
12467     //   a template-id and the declaration is a function or an
12468     //   elaborated-type-specifier, the lookup to determine whether
12469     //   the entity has been previously declared shall not consider
12470     //   any scopes outside the innermost enclosing namespace.
12471     //
12472     // MSVC doesn't implement the above rule for types, so a friend tag
12473     // declaration may be a redeclaration of a type declared in an enclosing
12474     // scope.  They do implement this rule for friend functions.
12475     //
12476     // Does it matter that this should be by scope instead of by
12477     // semantic context?
12478     if (!Previous.empty() && TUK == TUK_Friend) {
12479       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12480       LookupResult::Filter F = Previous.makeFilter();
12481       bool FriendSawTagOutsideEnclosingNamespace = false;
12482       while (F.hasNext()) {
12483         NamedDecl *ND = F.next();
12484         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12485         if (DC->isFileContext() &&
12486             !EnclosingNS->Encloses(ND->getDeclContext())) {
12487           if (getLangOpts().MSVCCompat)
12488             FriendSawTagOutsideEnclosingNamespace = true;
12489           else
12490             F.erase();
12491         }
12492       }
12493       F.done();
12494 
12495       // Diagnose this MSVC extension in the easy case where lookup would have
12496       // unambiguously found something outside the enclosing namespace.
12497       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12498         NamedDecl *ND = Previous.getFoundDecl();
12499         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12500             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12501       }
12502     }
12503 
12504     // Note:  there used to be some attempt at recovery here.
12505     if (Previous.isAmbiguous())
12506       return nullptr;
12507 
12508     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12509       // FIXME: This makes sure that we ignore the contexts associated
12510       // with C structs, unions, and enums when looking for a matching
12511       // tag declaration or definition. See the similar lookup tweak
12512       // in Sema::LookupName; is there a better way to deal with this?
12513       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12514         SearchDC = SearchDC->getParent();
12515     }
12516   }
12517 
12518   if (Previous.isSingleResult() &&
12519       Previous.getFoundDecl()->isTemplateParameter()) {
12520     // Maybe we will complain about the shadowed template parameter.
12521     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12522     // Just pretend that we didn't see the previous declaration.
12523     Previous.clear();
12524   }
12525 
12526   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12527       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12528     // This is a declaration of or a reference to "std::bad_alloc".
12529     isStdBadAlloc = true;
12530 
12531     if (Previous.empty() && StdBadAlloc) {
12532       // std::bad_alloc has been implicitly declared (but made invisible to
12533       // name lookup). Fill in this implicit declaration as the previous
12534       // declaration, so that the declarations get chained appropriately.
12535       Previous.addDecl(getStdBadAlloc());
12536     }
12537   }
12538 
12539   // If we didn't find a previous declaration, and this is a reference
12540   // (or friend reference), move to the correct scope.  In C++, we
12541   // also need to do a redeclaration lookup there, just in case
12542   // there's a shadow friend decl.
12543   if (Name && Previous.empty() &&
12544       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12545     if (Invalid) goto CreateNewDecl;
12546     assert(SS.isEmpty());
12547 
12548     if (TUK == TUK_Reference) {
12549       // C++ [basic.scope.pdecl]p5:
12550       //   -- for an elaborated-type-specifier of the form
12551       //
12552       //          class-key identifier
12553       //
12554       //      if the elaborated-type-specifier is used in the
12555       //      decl-specifier-seq or parameter-declaration-clause of a
12556       //      function defined in namespace scope, the identifier is
12557       //      declared as a class-name in the namespace that contains
12558       //      the declaration; otherwise, except as a friend
12559       //      declaration, the identifier is declared in the smallest
12560       //      non-class, non-function-prototype scope that contains the
12561       //      declaration.
12562       //
12563       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12564       // C structs and unions.
12565       //
12566       // It is an error in C++ to declare (rather than define) an enum
12567       // type, including via an elaborated type specifier.  We'll
12568       // diagnose that later; for now, declare the enum in the same
12569       // scope as we would have picked for any other tag type.
12570       //
12571       // GNU C also supports this behavior as part of its incomplete
12572       // enum types extension, while GNU C++ does not.
12573       //
12574       // Find the context where we'll be declaring the tag.
12575       // FIXME: We would like to maintain the current DeclContext as the
12576       // lexical context,
12577       SearchDC = getTagInjectionContext(SearchDC);
12578 
12579       // Find the scope where we'll be declaring the tag.
12580       S = getTagInjectionScope(S, getLangOpts());
12581     } else {
12582       assert(TUK == TUK_Friend);
12583       // C++ [namespace.memdef]p3:
12584       //   If a friend declaration in a non-local class first declares a
12585       //   class or function, the friend class or function is a member of
12586       //   the innermost enclosing namespace.
12587       SearchDC = SearchDC->getEnclosingNamespaceContext();
12588     }
12589 
12590     // In C++, we need to do a redeclaration lookup to properly
12591     // diagnose some problems.
12592     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12593     // hidden declaration so that we don't get ambiguity errors when using a
12594     // type declared by an elaborated-type-specifier.  In C that is not correct
12595     // and we should instead merge compatible types found by lookup.
12596     if (getLangOpts().CPlusPlus) {
12597       Previous.setRedeclarationKind(ForRedeclaration);
12598       LookupQualifiedName(Previous, SearchDC);
12599     } else {
12600       Previous.setRedeclarationKind(ForRedeclaration);
12601       LookupName(Previous, S);
12602     }
12603   }
12604 
12605   // If we have a known previous declaration to use, then use it.
12606   if (Previous.empty() && SkipBody && SkipBody->Previous)
12607     Previous.addDecl(SkipBody->Previous);
12608 
12609   if (!Previous.empty()) {
12610     NamedDecl *PrevDecl = Previous.getFoundDecl();
12611     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12612 
12613     // It's okay to have a tag decl in the same scope as a typedef
12614     // which hides a tag decl in the same scope.  Finding this
12615     // insanity with a redeclaration lookup can only actually happen
12616     // in C++.
12617     //
12618     // This is also okay for elaborated-type-specifiers, which is
12619     // technically forbidden by the current standard but which is
12620     // okay according to the likely resolution of an open issue;
12621     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12622     if (getLangOpts().CPlusPlus) {
12623       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12624         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12625           TagDecl *Tag = TT->getDecl();
12626           if (Tag->getDeclName() == Name &&
12627               Tag->getDeclContext()->getRedeclContext()
12628                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12629             PrevDecl = Tag;
12630             Previous.clear();
12631             Previous.addDecl(Tag);
12632             Previous.resolveKind();
12633           }
12634         }
12635       }
12636     }
12637 
12638     // If this is a redeclaration of a using shadow declaration, it must
12639     // declare a tag in the same context. In MSVC mode, we allow a
12640     // redefinition if either context is within the other.
12641     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12642       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12643       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12644           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12645           !(OldTag && isAcceptableTagRedeclContext(
12646                           *this, OldTag->getDeclContext(), SearchDC))) {
12647         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12648         Diag(Shadow->getTargetDecl()->getLocation(),
12649              diag::note_using_decl_target);
12650         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12651             << 0;
12652         // Recover by ignoring the old declaration.
12653         Previous.clear();
12654         goto CreateNewDecl;
12655       }
12656     }
12657 
12658     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12659       // If this is a use of a previous tag, or if the tag is already declared
12660       // in the same scope (so that the definition/declaration completes or
12661       // rementions the tag), reuse the decl.
12662       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12663           isDeclInScope(DirectPrevDecl, SearchDC, S,
12664                         SS.isNotEmpty() || isExplicitSpecialization)) {
12665         // Make sure that this wasn't declared as an enum and now used as a
12666         // struct or something similar.
12667         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12668                                           TUK == TUK_Definition, KWLoc,
12669                                           Name)) {
12670           bool SafeToContinue
12671             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12672                Kind != TTK_Enum);
12673           if (SafeToContinue)
12674             Diag(KWLoc, diag::err_use_with_wrong_tag)
12675               << Name
12676               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12677                                               PrevTagDecl->getKindName());
12678           else
12679             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12680           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12681 
12682           if (SafeToContinue)
12683             Kind = PrevTagDecl->getTagKind();
12684           else {
12685             // Recover by making this an anonymous redefinition.
12686             Name = nullptr;
12687             Previous.clear();
12688             Invalid = true;
12689           }
12690         }
12691 
12692         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12693           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12694 
12695           // If this is an elaborated-type-specifier for a scoped enumeration,
12696           // the 'class' keyword is not necessary and not permitted.
12697           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12698             if (ScopedEnum)
12699               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12700                 << PrevEnum->isScoped()
12701                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12702             return PrevTagDecl;
12703           }
12704 
12705           QualType EnumUnderlyingTy;
12706           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12707             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12708           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12709             EnumUnderlyingTy = QualType(T, 0);
12710 
12711           // All conflicts with previous declarations are recovered by
12712           // returning the previous declaration, unless this is a definition,
12713           // in which case we want the caller to bail out.
12714           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12715                                      ScopedEnum, EnumUnderlyingTy,
12716                                      EnumUnderlyingIsImplicit, PrevEnum))
12717             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12718         }
12719 
12720         // C++11 [class.mem]p1:
12721         //   A member shall not be declared twice in the member-specification,
12722         //   except that a nested class or member class template can be declared
12723         //   and then later defined.
12724         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12725             S->isDeclScope(PrevDecl)) {
12726           Diag(NameLoc, diag::ext_member_redeclared);
12727           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12728         }
12729 
12730         if (!Invalid) {
12731           // If this is a use, just return the declaration we found, unless
12732           // we have attributes.
12733           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12734             if (Attr) {
12735               // FIXME: Diagnose these attributes. For now, we create a new
12736               // declaration to hold them.
12737             } else if (TUK == TUK_Reference &&
12738                        (PrevTagDecl->getFriendObjectKind() ==
12739                             Decl::FOK_Undeclared ||
12740                         PP.getModuleContainingLocation(
12741                             PrevDecl->getLocation()) !=
12742                             PP.getModuleContainingLocation(KWLoc)) &&
12743                        SS.isEmpty()) {
12744               // This declaration is a reference to an existing entity, but
12745               // has different visibility from that entity: it either makes
12746               // a friend visible or it makes a type visible in a new module.
12747               // In either case, create a new declaration. We only do this if
12748               // the declaration would have meant the same thing if no prior
12749               // declaration were found, that is, if it was found in the same
12750               // scope where we would have injected a declaration.
12751               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12752                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12753                 return PrevTagDecl;
12754               // This is in the injected scope, create a new declaration in
12755               // that scope.
12756               S = getTagInjectionScope(S, getLangOpts());
12757             } else {
12758               return PrevTagDecl;
12759             }
12760           }
12761 
12762           // Diagnose attempts to redefine a tag.
12763           if (TUK == TUK_Definition) {
12764             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12765               // If we're defining a specialization and the previous definition
12766               // is from an implicit instantiation, don't emit an error
12767               // here; we'll catch this in the general case below.
12768               bool IsExplicitSpecializationAfterInstantiation = false;
12769               if (isExplicitSpecialization) {
12770                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12771                   IsExplicitSpecializationAfterInstantiation =
12772                     RD->getTemplateSpecializationKind() !=
12773                     TSK_ExplicitSpecialization;
12774                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12775                   IsExplicitSpecializationAfterInstantiation =
12776                     ED->getTemplateSpecializationKind() !=
12777                     TSK_ExplicitSpecialization;
12778               }
12779 
12780               NamedDecl *Hidden = nullptr;
12781               if (SkipBody && getLangOpts().CPlusPlus &&
12782                   !hasVisibleDefinition(Def, &Hidden)) {
12783                 // There is a definition of this tag, but it is not visible. We
12784                 // explicitly make use of C++'s one definition rule here, and
12785                 // assume that this definition is identical to the hidden one
12786                 // we already have. Make the existing definition visible and
12787                 // use it in place of this one.
12788                 SkipBody->ShouldSkip = true;
12789                 makeMergedDefinitionVisible(Hidden, KWLoc);
12790                 return Def;
12791               } else if (!IsExplicitSpecializationAfterInstantiation) {
12792                 // A redeclaration in function prototype scope in C isn't
12793                 // visible elsewhere, so merely issue a warning.
12794                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12795                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12796                 else
12797                   Diag(NameLoc, diag::err_redefinition) << Name;
12798                 Diag(Def->getLocation(), diag::note_previous_definition);
12799                 // If this is a redefinition, recover by making this
12800                 // struct be anonymous, which will make any later
12801                 // references get the previous definition.
12802                 Name = nullptr;
12803                 Previous.clear();
12804                 Invalid = true;
12805               }
12806             } else {
12807               // If the type is currently being defined, complain
12808               // about a nested redefinition.
12809               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12810               if (TD->isBeingDefined()) {
12811                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12812                 Diag(PrevTagDecl->getLocation(),
12813                      diag::note_previous_definition);
12814                 Name = nullptr;
12815                 Previous.clear();
12816                 Invalid = true;
12817               }
12818             }
12819 
12820             // Okay, this is definition of a previously declared or referenced
12821             // tag. We're going to create a new Decl for it.
12822           }
12823 
12824           // Okay, we're going to make a redeclaration.  If this is some kind
12825           // of reference, make sure we build the redeclaration in the same DC
12826           // as the original, and ignore the current access specifier.
12827           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12828             SearchDC = PrevTagDecl->getDeclContext();
12829             AS = AS_none;
12830           }
12831         }
12832         // If we get here we have (another) forward declaration or we
12833         // have a definition.  Just create a new decl.
12834 
12835       } else {
12836         // If we get here, this is a definition of a new tag type in a nested
12837         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12838         // new decl/type.  We set PrevDecl to NULL so that the entities
12839         // have distinct types.
12840         Previous.clear();
12841       }
12842       // If we get here, we're going to create a new Decl. If PrevDecl
12843       // is non-NULL, it's a definition of the tag declared by
12844       // PrevDecl. If it's NULL, we have a new definition.
12845 
12846     // Otherwise, PrevDecl is not a tag, but was found with tag
12847     // lookup.  This is only actually possible in C++, where a few
12848     // things like templates still live in the tag namespace.
12849     } else {
12850       // Use a better diagnostic if an elaborated-type-specifier
12851       // found the wrong kind of type on the first
12852       // (non-redeclaration) lookup.
12853       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12854           !Previous.isForRedeclaration()) {
12855         unsigned Kind = 0;
12856         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12857         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12858         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12859         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12860         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12861         Invalid = true;
12862 
12863       // Otherwise, only diagnose if the declaration is in scope.
12864       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12865                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12866         // do nothing
12867 
12868       // Diagnose implicit declarations introduced by elaborated types.
12869       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12870         unsigned Kind = 0;
12871         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12872         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12873         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12874         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12875         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12876         Invalid = true;
12877 
12878       // Otherwise it's a declaration.  Call out a particularly common
12879       // case here.
12880       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12881         unsigned Kind = 0;
12882         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12883         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12884           << Name << Kind << TND->getUnderlyingType();
12885         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12886         Invalid = true;
12887 
12888       // Otherwise, diagnose.
12889       } else {
12890         // The tag name clashes with something else in the target scope,
12891         // issue an error and recover by making this tag be anonymous.
12892         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12893         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12894         Name = nullptr;
12895         Invalid = true;
12896       }
12897 
12898       // The existing declaration isn't relevant to us; we're in a
12899       // new scope, so clear out the previous declaration.
12900       Previous.clear();
12901     }
12902   }
12903 
12904 CreateNewDecl:
12905 
12906   TagDecl *PrevDecl = nullptr;
12907   if (Previous.isSingleResult())
12908     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12909 
12910   // If there is an identifier, use the location of the identifier as the
12911   // location of the decl, otherwise use the location of the struct/union
12912   // keyword.
12913   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12914 
12915   // Otherwise, create a new declaration. If there is a previous
12916   // declaration of the same entity, the two will be linked via
12917   // PrevDecl.
12918   TagDecl *New;
12919 
12920   bool IsForwardReference = false;
12921   if (Kind == TTK_Enum) {
12922     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12923     // enum X { A, B, C } D;    D should chain to X.
12924     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12925                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12926                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12927     // If this is an undefined enum, warn.
12928     if (TUK != TUK_Definition && !Invalid) {
12929       TagDecl *Def;
12930       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12931           cast<EnumDecl>(New)->isFixed()) {
12932         // C++0x: 7.2p2: opaque-enum-declaration.
12933         // Conflicts are diagnosed above. Do nothing.
12934       }
12935       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12936         Diag(Loc, diag::ext_forward_ref_enum_def)
12937           << New;
12938         Diag(Def->getLocation(), diag::note_previous_definition);
12939       } else {
12940         unsigned DiagID = diag::ext_forward_ref_enum;
12941         if (getLangOpts().MSVCCompat)
12942           DiagID = diag::ext_ms_forward_ref_enum;
12943         else if (getLangOpts().CPlusPlus)
12944           DiagID = diag::err_forward_ref_enum;
12945         Diag(Loc, DiagID);
12946 
12947         // If this is a forward-declared reference to an enumeration, make a
12948         // note of it; we won't actually be introducing the declaration into
12949         // the declaration context.
12950         if (TUK == TUK_Reference)
12951           IsForwardReference = true;
12952       }
12953     }
12954 
12955     if (EnumUnderlying) {
12956       EnumDecl *ED = cast<EnumDecl>(New);
12957       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12958         ED->setIntegerTypeSourceInfo(TI);
12959       else
12960         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12961       ED->setPromotionType(ED->getIntegerType());
12962     }
12963   } else {
12964     // struct/union/class
12965 
12966     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12967     // struct X { int A; } D;    D should chain to X.
12968     if (getLangOpts().CPlusPlus) {
12969       // FIXME: Look for a way to use RecordDecl for simple structs.
12970       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12971                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12972 
12973       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12974         StdBadAlloc = cast<CXXRecordDecl>(New);
12975     } else
12976       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12977                                cast_or_null<RecordDecl>(PrevDecl));
12978   }
12979 
12980   // C++11 [dcl.type]p3:
12981   //   A type-specifier-seq shall not define a class or enumeration [...].
12982   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12983     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12984       << Context.getTagDeclType(New);
12985     Invalid = true;
12986   }
12987 
12988   // Maybe add qualifier info.
12989   if (SS.isNotEmpty()) {
12990     if (SS.isSet()) {
12991       // If this is either a declaration or a definition, check the
12992       // nested-name-specifier against the current context. We don't do this
12993       // for explicit specializations, because they have similar checking
12994       // (with more specific diagnostics) in the call to
12995       // CheckMemberSpecialization, below.
12996       if (!isExplicitSpecialization &&
12997           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12998           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12999         Invalid = true;
13000 
13001       New->setQualifierInfo(SS.getWithLocInContext(Context));
13002       if (TemplateParameterLists.size() > 0) {
13003         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13004       }
13005     }
13006     else
13007       Invalid = true;
13008   }
13009 
13010   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13011     // Add alignment attributes if necessary; these attributes are checked when
13012     // the ASTContext lays out the structure.
13013     //
13014     // It is important for implementing the correct semantics that this
13015     // happen here (in act on tag decl). The #pragma pack stack is
13016     // maintained as a result of parser callbacks which can occur at
13017     // many points during the parsing of a struct declaration (because
13018     // the #pragma tokens are effectively skipped over during the
13019     // parsing of the struct).
13020     if (TUK == TUK_Definition) {
13021       AddAlignmentAttributesForRecord(RD);
13022       AddMsStructLayoutForRecord(RD);
13023     }
13024   }
13025 
13026   if (ModulePrivateLoc.isValid()) {
13027     if (isExplicitSpecialization)
13028       Diag(New->getLocation(), diag::err_module_private_specialization)
13029         << 2
13030         << FixItHint::CreateRemoval(ModulePrivateLoc);
13031     // __module_private__ does not apply to local classes. However, we only
13032     // diagnose this as an error when the declaration specifiers are
13033     // freestanding. Here, we just ignore the __module_private__.
13034     else if (!SearchDC->isFunctionOrMethod())
13035       New->setModulePrivate();
13036   }
13037 
13038   // If this is a specialization of a member class (of a class template),
13039   // check the specialization.
13040   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13041     Invalid = true;
13042 
13043   // If we're declaring or defining a tag in function prototype scope in C,
13044   // note that this type can only be used within the function and add it to
13045   // the list of decls to inject into the function definition scope.
13046   if ((Name || Kind == TTK_Enum) &&
13047       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13048     if (getLangOpts().CPlusPlus) {
13049       // C++ [dcl.fct]p6:
13050       //   Types shall not be defined in return or parameter types.
13051       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13052         Diag(Loc, diag::err_type_defined_in_param_type)
13053             << Name;
13054         Invalid = true;
13055       }
13056     } else if (!PrevDecl) {
13057       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13058     }
13059     DeclsInPrototypeScope.push_back(New);
13060   }
13061 
13062   if (Invalid)
13063     New->setInvalidDecl();
13064 
13065   if (Attr)
13066     ProcessDeclAttributeList(S, New, Attr);
13067 
13068   // Set the lexical context. If the tag has a C++ scope specifier, the
13069   // lexical context will be different from the semantic context.
13070   New->setLexicalDeclContext(CurContext);
13071 
13072   // Mark this as a friend decl if applicable.
13073   // In Microsoft mode, a friend declaration also acts as a forward
13074   // declaration so we always pass true to setObjectOfFriendDecl to make
13075   // the tag name visible.
13076   if (TUK == TUK_Friend)
13077     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13078 
13079   // Set the access specifier.
13080   if (!Invalid && SearchDC->isRecord())
13081     SetMemberAccessSpecifier(New, PrevDecl, AS);
13082 
13083   if (TUK == TUK_Definition)
13084     New->startDefinition();
13085 
13086   // If this has an identifier, add it to the scope stack.
13087   if (TUK == TUK_Friend) {
13088     // We might be replacing an existing declaration in the lookup tables;
13089     // if so, borrow its access specifier.
13090     if (PrevDecl)
13091       New->setAccess(PrevDecl->getAccess());
13092 
13093     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13094     DC->makeDeclVisibleInContext(New);
13095     if (Name) // can be null along some error paths
13096       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13097         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13098   } else if (Name) {
13099     S = getNonFieldDeclScope(S);
13100     PushOnScopeChains(New, S, !IsForwardReference);
13101     if (IsForwardReference)
13102       SearchDC->makeDeclVisibleInContext(New);
13103   } else {
13104     CurContext->addDecl(New);
13105   }
13106 
13107   // If this is the C FILE type, notify the AST context.
13108   if (IdentifierInfo *II = New->getIdentifier())
13109     if (!New->isInvalidDecl() &&
13110         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13111         II->isStr("FILE"))
13112       Context.setFILEDecl(New);
13113 
13114   if (PrevDecl)
13115     mergeDeclAttributes(New, PrevDecl);
13116 
13117   // If there's a #pragma GCC visibility in scope, set the visibility of this
13118   // record.
13119   AddPushedVisibilityAttribute(New);
13120 
13121   OwnedDecl = true;
13122   // In C++, don't return an invalid declaration. We can't recover well from
13123   // the cases where we make the type anonymous.
13124   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13125 }
13126 
13127 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13128   AdjustDeclIfTemplate(TagD);
13129   TagDecl *Tag = cast<TagDecl>(TagD);
13130 
13131   // Enter the tag context.
13132   PushDeclContext(S, Tag);
13133 
13134   ActOnDocumentableDecl(TagD);
13135 
13136   // If there's a #pragma GCC visibility in scope, set the visibility of this
13137   // record.
13138   AddPushedVisibilityAttribute(Tag);
13139 }
13140 
13141 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13142   assert(isa<ObjCContainerDecl>(IDecl) &&
13143          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13144   DeclContext *OCD = cast<DeclContext>(IDecl);
13145   assert(getContainingDC(OCD) == CurContext &&
13146       "The next DeclContext should be lexically contained in the current one.");
13147   CurContext = OCD;
13148   return IDecl;
13149 }
13150 
13151 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13152                                            SourceLocation FinalLoc,
13153                                            bool IsFinalSpelledSealed,
13154                                            SourceLocation LBraceLoc) {
13155   AdjustDeclIfTemplate(TagD);
13156   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13157 
13158   FieldCollector->StartClass();
13159 
13160   if (!Record->getIdentifier())
13161     return;
13162 
13163   if (FinalLoc.isValid())
13164     Record->addAttr(new (Context)
13165                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13166 
13167   // C++ [class]p2:
13168   //   [...] The class-name is also inserted into the scope of the
13169   //   class itself; this is known as the injected-class-name. For
13170   //   purposes of access checking, the injected-class-name is treated
13171   //   as if it were a public member name.
13172   CXXRecordDecl *InjectedClassName
13173     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13174                             Record->getLocStart(), Record->getLocation(),
13175                             Record->getIdentifier(),
13176                             /*PrevDecl=*/nullptr,
13177                             /*DelayTypeCreation=*/true);
13178   Context.getTypeDeclType(InjectedClassName, Record);
13179   InjectedClassName->setImplicit();
13180   InjectedClassName->setAccess(AS_public);
13181   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13182       InjectedClassName->setDescribedClassTemplate(Template);
13183   PushOnScopeChains(InjectedClassName, S);
13184   assert(InjectedClassName->isInjectedClassName() &&
13185          "Broken injected-class-name");
13186 }
13187 
13188 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13189                                     SourceLocation RBraceLoc) {
13190   AdjustDeclIfTemplate(TagD);
13191   TagDecl *Tag = cast<TagDecl>(TagD);
13192   Tag->setRBraceLoc(RBraceLoc);
13193 
13194   // Make sure we "complete" the definition even it is invalid.
13195   if (Tag->isBeingDefined()) {
13196     assert(Tag->isInvalidDecl() && "We should already have completed it");
13197     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13198       RD->completeDefinition();
13199   }
13200 
13201   if (isa<CXXRecordDecl>(Tag))
13202     FieldCollector->FinishClass();
13203 
13204   // Exit this scope of this tag's definition.
13205   PopDeclContext();
13206 
13207   if (getCurLexicalContext()->isObjCContainer() &&
13208       Tag->getDeclContext()->isFileContext())
13209     Tag->setTopLevelDeclInObjCContainer();
13210 
13211   // Notify the consumer that we've defined a tag.
13212   if (!Tag->isInvalidDecl())
13213     Consumer.HandleTagDeclDefinition(Tag);
13214 }
13215 
13216 void Sema::ActOnObjCContainerFinishDefinition() {
13217   // Exit this scope of this interface definition.
13218   PopDeclContext();
13219 }
13220 
13221 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13222   assert(DC == CurContext && "Mismatch of container contexts");
13223   OriginalLexicalContext = DC;
13224   ActOnObjCContainerFinishDefinition();
13225 }
13226 
13227 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13228   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13229   OriginalLexicalContext = nullptr;
13230 }
13231 
13232 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13233   AdjustDeclIfTemplate(TagD);
13234   TagDecl *Tag = cast<TagDecl>(TagD);
13235   Tag->setInvalidDecl();
13236 
13237   // Make sure we "complete" the definition even it is invalid.
13238   if (Tag->isBeingDefined()) {
13239     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13240       RD->completeDefinition();
13241   }
13242 
13243   // We're undoing ActOnTagStartDefinition here, not
13244   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13245   // the FieldCollector.
13246 
13247   PopDeclContext();
13248 }
13249 
13250 // Note that FieldName may be null for anonymous bitfields.
13251 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13252                                 IdentifierInfo *FieldName,
13253                                 QualType FieldTy, bool IsMsStruct,
13254                                 Expr *BitWidth, bool *ZeroWidth) {
13255   // Default to true; that shouldn't confuse checks for emptiness
13256   if (ZeroWidth)
13257     *ZeroWidth = true;
13258 
13259   // C99 6.7.2.1p4 - verify the field type.
13260   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13261   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13262     // Handle incomplete types with specific error.
13263     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13264       return ExprError();
13265     if (FieldName)
13266       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13267         << FieldName << FieldTy << BitWidth->getSourceRange();
13268     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13269       << FieldTy << BitWidth->getSourceRange();
13270   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13271                                              UPPC_BitFieldWidth))
13272     return ExprError();
13273 
13274   // If the bit-width is type- or value-dependent, don't try to check
13275   // it now.
13276   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13277     return BitWidth;
13278 
13279   llvm::APSInt Value;
13280   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13281   if (ICE.isInvalid())
13282     return ICE;
13283   BitWidth = ICE.get();
13284 
13285   if (Value != 0 && ZeroWidth)
13286     *ZeroWidth = false;
13287 
13288   // Zero-width bitfield is ok for anonymous field.
13289   if (Value == 0 && FieldName)
13290     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13291 
13292   if (Value.isSigned() && Value.isNegative()) {
13293     if (FieldName)
13294       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13295                << FieldName << Value.toString(10);
13296     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13297       << Value.toString(10);
13298   }
13299 
13300   if (!FieldTy->isDependentType()) {
13301     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13302     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13303     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13304 
13305     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13306     // ABI.
13307     bool CStdConstraintViolation =
13308         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13309     bool MSBitfieldViolation =
13310         Value.ugt(TypeStorageSize) &&
13311         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13312     if (CStdConstraintViolation || MSBitfieldViolation) {
13313       unsigned DiagWidth =
13314           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13315       if (FieldName)
13316         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13317                << FieldName << (unsigned)Value.getZExtValue()
13318                << !CStdConstraintViolation << DiagWidth;
13319 
13320       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13321              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13322              << DiagWidth;
13323     }
13324 
13325     // Warn on types where the user might conceivably expect to get all
13326     // specified bits as value bits: that's all integral types other than
13327     // 'bool'.
13328     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13329       if (FieldName)
13330         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13331             << FieldName << (unsigned)Value.getZExtValue()
13332             << (unsigned)TypeWidth;
13333       else
13334         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13335             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13336     }
13337   }
13338 
13339   return BitWidth;
13340 }
13341 
13342 /// ActOnField - Each field of a C struct/union is passed into this in order
13343 /// to create a FieldDecl object for it.
13344 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13345                        Declarator &D, Expr *BitfieldWidth) {
13346   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13347                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13348                                /*InitStyle=*/ICIS_NoInit, AS_public);
13349   return Res;
13350 }
13351 
13352 /// HandleField - Analyze a field of a C struct or a C++ data member.
13353 ///
13354 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13355                              SourceLocation DeclStart,
13356                              Declarator &D, Expr *BitWidth,
13357                              InClassInitStyle InitStyle,
13358                              AccessSpecifier AS) {
13359   IdentifierInfo *II = D.getIdentifier();
13360   SourceLocation Loc = DeclStart;
13361   if (II) Loc = D.getIdentifierLoc();
13362 
13363   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13364   QualType T = TInfo->getType();
13365   if (getLangOpts().CPlusPlus) {
13366     CheckExtraCXXDefaultArguments(D);
13367 
13368     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13369                                         UPPC_DataMemberType)) {
13370       D.setInvalidType();
13371       T = Context.IntTy;
13372       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13373     }
13374   }
13375 
13376   // TR 18037 does not allow fields to be declared with address spaces.
13377   if (T.getQualifiers().hasAddressSpace()) {
13378     Diag(Loc, diag::err_field_with_address_space);
13379     D.setInvalidType();
13380   }
13381 
13382   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13383   // used as structure or union field: image, sampler, event or block types.
13384   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13385                           T->isSamplerT() || T->isBlockPointerType())) {
13386     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13387     D.setInvalidType();
13388   }
13389 
13390   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13391 
13392   if (D.getDeclSpec().isInlineSpecified())
13393     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13394         << getLangOpts().CPlusPlus1z;
13395   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13396     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13397          diag::err_invalid_thread)
13398       << DeclSpec::getSpecifierName(TSCS);
13399 
13400   // Check to see if this name was declared as a member previously
13401   NamedDecl *PrevDecl = nullptr;
13402   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13403   LookupName(Previous, S);
13404   switch (Previous.getResultKind()) {
13405     case LookupResult::Found:
13406     case LookupResult::FoundUnresolvedValue:
13407       PrevDecl = Previous.getAsSingle<NamedDecl>();
13408       break;
13409 
13410     case LookupResult::FoundOverloaded:
13411       PrevDecl = Previous.getRepresentativeDecl();
13412       break;
13413 
13414     case LookupResult::NotFound:
13415     case LookupResult::NotFoundInCurrentInstantiation:
13416     case LookupResult::Ambiguous:
13417       break;
13418   }
13419   Previous.suppressDiagnostics();
13420 
13421   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13422     // Maybe we will complain about the shadowed template parameter.
13423     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13424     // Just pretend that we didn't see the previous declaration.
13425     PrevDecl = nullptr;
13426   }
13427 
13428   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13429     PrevDecl = nullptr;
13430 
13431   bool Mutable
13432     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13433   SourceLocation TSSL = D.getLocStart();
13434   FieldDecl *NewFD
13435     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13436                      TSSL, AS, PrevDecl, &D);
13437 
13438   if (NewFD->isInvalidDecl())
13439     Record->setInvalidDecl();
13440 
13441   if (D.getDeclSpec().isModulePrivateSpecified())
13442     NewFD->setModulePrivate();
13443 
13444   if (NewFD->isInvalidDecl() && PrevDecl) {
13445     // Don't introduce NewFD into scope; there's already something
13446     // with the same name in the same scope.
13447   } else if (II) {
13448     PushOnScopeChains(NewFD, S);
13449   } else
13450     Record->addDecl(NewFD);
13451 
13452   return NewFD;
13453 }
13454 
13455 /// \brief Build a new FieldDecl and check its well-formedness.
13456 ///
13457 /// This routine builds a new FieldDecl given the fields name, type,
13458 /// record, etc. \p PrevDecl should refer to any previous declaration
13459 /// with the same name and in the same scope as the field to be
13460 /// created.
13461 ///
13462 /// \returns a new FieldDecl.
13463 ///
13464 /// \todo The Declarator argument is a hack. It will be removed once
13465 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13466                                 TypeSourceInfo *TInfo,
13467                                 RecordDecl *Record, SourceLocation Loc,
13468                                 bool Mutable, Expr *BitWidth,
13469                                 InClassInitStyle InitStyle,
13470                                 SourceLocation TSSL,
13471                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13472                                 Declarator *D) {
13473   IdentifierInfo *II = Name.getAsIdentifierInfo();
13474   bool InvalidDecl = false;
13475   if (D) InvalidDecl = D->isInvalidType();
13476 
13477   // If we receive a broken type, recover by assuming 'int' and
13478   // marking this declaration as invalid.
13479   if (T.isNull()) {
13480     InvalidDecl = true;
13481     T = Context.IntTy;
13482   }
13483 
13484   QualType EltTy = Context.getBaseElementType(T);
13485   if (!EltTy->isDependentType()) {
13486     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13487       // Fields of incomplete type force their record to be invalid.
13488       Record->setInvalidDecl();
13489       InvalidDecl = true;
13490     } else {
13491       NamedDecl *Def;
13492       EltTy->isIncompleteType(&Def);
13493       if (Def && Def->isInvalidDecl()) {
13494         Record->setInvalidDecl();
13495         InvalidDecl = true;
13496       }
13497     }
13498   }
13499 
13500   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13501   if (BitWidth && getLangOpts().OpenCL) {
13502     Diag(Loc, diag::err_opencl_bitfields);
13503     InvalidDecl = true;
13504   }
13505 
13506   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13507   // than a variably modified type.
13508   if (!InvalidDecl && T->isVariablyModifiedType()) {
13509     bool SizeIsNegative;
13510     llvm::APSInt Oversized;
13511 
13512     TypeSourceInfo *FixedTInfo =
13513       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13514                                                     SizeIsNegative,
13515                                                     Oversized);
13516     if (FixedTInfo) {
13517       Diag(Loc, diag::warn_illegal_constant_array_size);
13518       TInfo = FixedTInfo;
13519       T = FixedTInfo->getType();
13520     } else {
13521       if (SizeIsNegative)
13522         Diag(Loc, diag::err_typecheck_negative_array_size);
13523       else if (Oversized.getBoolValue())
13524         Diag(Loc, diag::err_array_too_large)
13525           << Oversized.toString(10);
13526       else
13527         Diag(Loc, diag::err_typecheck_field_variable_size);
13528       InvalidDecl = true;
13529     }
13530   }
13531 
13532   // Fields can not have abstract class types
13533   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13534                                              diag::err_abstract_type_in_decl,
13535                                              AbstractFieldType))
13536     InvalidDecl = true;
13537 
13538   bool ZeroWidth = false;
13539   if (InvalidDecl)
13540     BitWidth = nullptr;
13541   // If this is declared as a bit-field, check the bit-field.
13542   if (BitWidth) {
13543     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13544                               &ZeroWidth).get();
13545     if (!BitWidth) {
13546       InvalidDecl = true;
13547       BitWidth = nullptr;
13548       ZeroWidth = false;
13549     }
13550   }
13551 
13552   // Check that 'mutable' is consistent with the type of the declaration.
13553   if (!InvalidDecl && Mutable) {
13554     unsigned DiagID = 0;
13555     if (T->isReferenceType())
13556       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13557                                         : diag::err_mutable_reference;
13558     else if (T.isConstQualified())
13559       DiagID = diag::err_mutable_const;
13560 
13561     if (DiagID) {
13562       SourceLocation ErrLoc = Loc;
13563       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13564         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13565       Diag(ErrLoc, DiagID);
13566       if (DiagID != diag::ext_mutable_reference) {
13567         Mutable = false;
13568         InvalidDecl = true;
13569       }
13570     }
13571   }
13572 
13573   // C++11 [class.union]p8 (DR1460):
13574   //   At most one variant member of a union may have a
13575   //   brace-or-equal-initializer.
13576   if (InitStyle != ICIS_NoInit)
13577     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13578 
13579   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13580                                        BitWidth, Mutable, InitStyle);
13581   if (InvalidDecl)
13582     NewFD->setInvalidDecl();
13583 
13584   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13585     Diag(Loc, diag::err_duplicate_member) << II;
13586     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13587     NewFD->setInvalidDecl();
13588   }
13589 
13590   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13591     if (Record->isUnion()) {
13592       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13593         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13594         if (RDecl->getDefinition()) {
13595           // C++ [class.union]p1: An object of a class with a non-trivial
13596           // constructor, a non-trivial copy constructor, a non-trivial
13597           // destructor, or a non-trivial copy assignment operator
13598           // cannot be a member of a union, nor can an array of such
13599           // objects.
13600           if (CheckNontrivialField(NewFD))
13601             NewFD->setInvalidDecl();
13602         }
13603       }
13604 
13605       // C++ [class.union]p1: If a union contains a member of reference type,
13606       // the program is ill-formed, except when compiling with MSVC extensions
13607       // enabled.
13608       if (EltTy->isReferenceType()) {
13609         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13610                                     diag::ext_union_member_of_reference_type :
13611                                     diag::err_union_member_of_reference_type)
13612           << NewFD->getDeclName() << EltTy;
13613         if (!getLangOpts().MicrosoftExt)
13614           NewFD->setInvalidDecl();
13615       }
13616     }
13617   }
13618 
13619   // FIXME: We need to pass in the attributes given an AST
13620   // representation, not a parser representation.
13621   if (D) {
13622     // FIXME: The current scope is almost... but not entirely... correct here.
13623     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13624 
13625     if (NewFD->hasAttrs())
13626       CheckAlignasUnderalignment(NewFD);
13627   }
13628 
13629   // In auto-retain/release, infer strong retension for fields of
13630   // retainable type.
13631   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13632     NewFD->setInvalidDecl();
13633 
13634   if (T.isObjCGCWeak())
13635     Diag(Loc, diag::warn_attribute_weak_on_field);
13636 
13637   NewFD->setAccess(AS);
13638   return NewFD;
13639 }
13640 
13641 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13642   assert(FD);
13643   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13644 
13645   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13646     return false;
13647 
13648   QualType EltTy = Context.getBaseElementType(FD->getType());
13649   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13650     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13651     if (RDecl->getDefinition()) {
13652       // We check for copy constructors before constructors
13653       // because otherwise we'll never get complaints about
13654       // copy constructors.
13655 
13656       CXXSpecialMember member = CXXInvalid;
13657       // We're required to check for any non-trivial constructors. Since the
13658       // implicit default constructor is suppressed if there are any
13659       // user-declared constructors, we just need to check that there is a
13660       // trivial default constructor and a trivial copy constructor. (We don't
13661       // worry about move constructors here, since this is a C++98 check.)
13662       if (RDecl->hasNonTrivialCopyConstructor())
13663         member = CXXCopyConstructor;
13664       else if (!RDecl->hasTrivialDefaultConstructor())
13665         member = CXXDefaultConstructor;
13666       else if (RDecl->hasNonTrivialCopyAssignment())
13667         member = CXXCopyAssignment;
13668       else if (RDecl->hasNonTrivialDestructor())
13669         member = CXXDestructor;
13670 
13671       if (member != CXXInvalid) {
13672         if (!getLangOpts().CPlusPlus11 &&
13673             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13674           // Objective-C++ ARC: it is an error to have a non-trivial field of
13675           // a union. However, system headers in Objective-C programs
13676           // occasionally have Objective-C lifetime objects within unions,
13677           // and rather than cause the program to fail, we make those
13678           // members unavailable.
13679           SourceLocation Loc = FD->getLocation();
13680           if (getSourceManager().isInSystemHeader(Loc)) {
13681             if (!FD->hasAttr<UnavailableAttr>())
13682               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13683                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13684             return false;
13685           }
13686         }
13687 
13688         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13689                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13690                diag::err_illegal_union_or_anon_struct_member)
13691           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13692         DiagnoseNontrivial(RDecl, member);
13693         return !getLangOpts().CPlusPlus11;
13694       }
13695     }
13696   }
13697 
13698   return false;
13699 }
13700 
13701 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13702 ///  AST enum value.
13703 static ObjCIvarDecl::AccessControl
13704 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13705   switch (ivarVisibility) {
13706   default: llvm_unreachable("Unknown visitibility kind");
13707   case tok::objc_private: return ObjCIvarDecl::Private;
13708   case tok::objc_public: return ObjCIvarDecl::Public;
13709   case tok::objc_protected: return ObjCIvarDecl::Protected;
13710   case tok::objc_package: return ObjCIvarDecl::Package;
13711   }
13712 }
13713 
13714 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13715 /// in order to create an IvarDecl object for it.
13716 Decl *Sema::ActOnIvar(Scope *S,
13717                                 SourceLocation DeclStart,
13718                                 Declarator &D, Expr *BitfieldWidth,
13719                                 tok::ObjCKeywordKind Visibility) {
13720 
13721   IdentifierInfo *II = D.getIdentifier();
13722   Expr *BitWidth = (Expr*)BitfieldWidth;
13723   SourceLocation Loc = DeclStart;
13724   if (II) Loc = D.getIdentifierLoc();
13725 
13726   // FIXME: Unnamed fields can be handled in various different ways, for
13727   // example, unnamed unions inject all members into the struct namespace!
13728 
13729   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13730   QualType T = TInfo->getType();
13731 
13732   if (BitWidth) {
13733     // 6.7.2.1p3, 6.7.2.1p4
13734     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13735     if (!BitWidth)
13736       D.setInvalidType();
13737   } else {
13738     // Not a bitfield.
13739 
13740     // validate II.
13741 
13742   }
13743   if (T->isReferenceType()) {
13744     Diag(Loc, diag::err_ivar_reference_type);
13745     D.setInvalidType();
13746   }
13747   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13748   // than a variably modified type.
13749   else if (T->isVariablyModifiedType()) {
13750     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13751     D.setInvalidType();
13752   }
13753 
13754   // Get the visibility (access control) for this ivar.
13755   ObjCIvarDecl::AccessControl ac =
13756     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13757                                         : ObjCIvarDecl::None;
13758   // Must set ivar's DeclContext to its enclosing interface.
13759   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13760   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13761     return nullptr;
13762   ObjCContainerDecl *EnclosingContext;
13763   if (ObjCImplementationDecl *IMPDecl =
13764       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13765     if (LangOpts.ObjCRuntime.isFragile()) {
13766     // Case of ivar declared in an implementation. Context is that of its class.
13767       EnclosingContext = IMPDecl->getClassInterface();
13768       assert(EnclosingContext && "Implementation has no class interface!");
13769     }
13770     else
13771       EnclosingContext = EnclosingDecl;
13772   } else {
13773     if (ObjCCategoryDecl *CDecl =
13774         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13775       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13776         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13777         return nullptr;
13778       }
13779     }
13780     EnclosingContext = EnclosingDecl;
13781   }
13782 
13783   // Construct the decl.
13784   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13785                                              DeclStart, Loc, II, T,
13786                                              TInfo, ac, (Expr *)BitfieldWidth);
13787 
13788   if (II) {
13789     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13790                                            ForRedeclaration);
13791     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13792         && !isa<TagDecl>(PrevDecl)) {
13793       Diag(Loc, diag::err_duplicate_member) << II;
13794       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13795       NewID->setInvalidDecl();
13796     }
13797   }
13798 
13799   // Process attributes attached to the ivar.
13800   ProcessDeclAttributes(S, NewID, D);
13801 
13802   if (D.isInvalidType())
13803     NewID->setInvalidDecl();
13804 
13805   // In ARC, infer 'retaining' for ivars of retainable type.
13806   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13807     NewID->setInvalidDecl();
13808 
13809   if (D.getDeclSpec().isModulePrivateSpecified())
13810     NewID->setModulePrivate();
13811 
13812   if (II) {
13813     // FIXME: When interfaces are DeclContexts, we'll need to add
13814     // these to the interface.
13815     S->AddDecl(NewID);
13816     IdResolver.AddDecl(NewID);
13817   }
13818 
13819   if (LangOpts.ObjCRuntime.isNonFragile() &&
13820       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13821     Diag(Loc, diag::warn_ivars_in_interface);
13822 
13823   return NewID;
13824 }
13825 
13826 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13827 /// class and class extensions. For every class \@interface and class
13828 /// extension \@interface, if the last ivar is a bitfield of any type,
13829 /// then add an implicit `char :0` ivar to the end of that interface.
13830 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13831                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13832   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13833     return;
13834 
13835   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13836   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13837 
13838   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13839     return;
13840   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13841   if (!ID) {
13842     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13843       if (!CD->IsClassExtension())
13844         return;
13845     }
13846     // No need to add this to end of @implementation.
13847     else
13848       return;
13849   }
13850   // All conditions are met. Add a new bitfield to the tail end of ivars.
13851   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13852   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13853 
13854   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13855                               DeclLoc, DeclLoc, nullptr,
13856                               Context.CharTy,
13857                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13858                                                                DeclLoc),
13859                               ObjCIvarDecl::Private, BW,
13860                               true);
13861   AllIvarDecls.push_back(Ivar);
13862 }
13863 
13864 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13865                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13866                        SourceLocation RBrac, AttributeList *Attr) {
13867   assert(EnclosingDecl && "missing record or interface decl");
13868 
13869   // If this is an Objective-C @implementation or category and we have
13870   // new fields here we should reset the layout of the interface since
13871   // it will now change.
13872   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13873     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13874     switch (DC->getKind()) {
13875     default: break;
13876     case Decl::ObjCCategory:
13877       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13878       break;
13879     case Decl::ObjCImplementation:
13880       Context.
13881         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13882       break;
13883     }
13884   }
13885 
13886   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13887 
13888   // Start counting up the number of named members; make sure to include
13889   // members of anonymous structs and unions in the total.
13890   unsigned NumNamedMembers = 0;
13891   if (Record) {
13892     for (const auto *I : Record->decls()) {
13893       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13894         if (IFD->getDeclName())
13895           ++NumNamedMembers;
13896     }
13897   }
13898 
13899   // Verify that all the fields are okay.
13900   SmallVector<FieldDecl*, 32> RecFields;
13901 
13902   bool ARCErrReported = false;
13903   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13904        i != end; ++i) {
13905     FieldDecl *FD = cast<FieldDecl>(*i);
13906 
13907     // Get the type for the field.
13908     const Type *FDTy = FD->getType().getTypePtr();
13909 
13910     if (!FD->isAnonymousStructOrUnion()) {
13911       // Remember all fields written by the user.
13912       RecFields.push_back(FD);
13913     }
13914 
13915     // If the field is already invalid for some reason, don't emit more
13916     // diagnostics about it.
13917     if (FD->isInvalidDecl()) {
13918       EnclosingDecl->setInvalidDecl();
13919       continue;
13920     }
13921 
13922     // C99 6.7.2.1p2:
13923     //   A structure or union shall not contain a member with
13924     //   incomplete or function type (hence, a structure shall not
13925     //   contain an instance of itself, but may contain a pointer to
13926     //   an instance of itself), except that the last member of a
13927     //   structure with more than one named member may have incomplete
13928     //   array type; such a structure (and any union containing,
13929     //   possibly recursively, a member that is such a structure)
13930     //   shall not be a member of a structure or an element of an
13931     //   array.
13932     if (FDTy->isFunctionType()) {
13933       // Field declared as a function.
13934       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13935         << FD->getDeclName();
13936       FD->setInvalidDecl();
13937       EnclosingDecl->setInvalidDecl();
13938       continue;
13939     } else if (FDTy->isIncompleteArrayType() && Record &&
13940                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13941                 ((getLangOpts().MicrosoftExt ||
13942                   getLangOpts().CPlusPlus) &&
13943                  (i + 1 == Fields.end() || Record->isUnion())))) {
13944       // Flexible array member.
13945       // Microsoft and g++ is more permissive regarding flexible array.
13946       // It will accept flexible array in union and also
13947       // as the sole element of a struct/class.
13948       unsigned DiagID = 0;
13949       if (Record->isUnion())
13950         DiagID = getLangOpts().MicrosoftExt
13951                      ? diag::ext_flexible_array_union_ms
13952                      : getLangOpts().CPlusPlus
13953                            ? diag::ext_flexible_array_union_gnu
13954                            : diag::err_flexible_array_union;
13955       else if (NumNamedMembers < 1)
13956         DiagID = getLangOpts().MicrosoftExt
13957                      ? diag::ext_flexible_array_empty_aggregate_ms
13958                      : getLangOpts().CPlusPlus
13959                            ? diag::ext_flexible_array_empty_aggregate_gnu
13960                            : diag::err_flexible_array_empty_aggregate;
13961 
13962       if (DiagID)
13963         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13964                                         << Record->getTagKind();
13965       // While the layout of types that contain virtual bases is not specified
13966       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13967       // virtual bases after the derived members.  This would make a flexible
13968       // array member declared at the end of an object not adjacent to the end
13969       // of the type.
13970       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13971         if (RD->getNumVBases() != 0)
13972           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13973             << FD->getDeclName() << Record->getTagKind();
13974       if (!getLangOpts().C99)
13975         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13976           << FD->getDeclName() << Record->getTagKind();
13977 
13978       // If the element type has a non-trivial destructor, we would not
13979       // implicitly destroy the elements, so disallow it for now.
13980       //
13981       // FIXME: GCC allows this. We should probably either implicitly delete
13982       // the destructor of the containing class, or just allow this.
13983       QualType BaseElem = Context.getBaseElementType(FD->getType());
13984       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13985         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13986           << FD->getDeclName() << FD->getType();
13987         FD->setInvalidDecl();
13988         EnclosingDecl->setInvalidDecl();
13989         continue;
13990       }
13991       // Okay, we have a legal flexible array member at the end of the struct.
13992       Record->setHasFlexibleArrayMember(true);
13993     } else if (!FDTy->isDependentType() &&
13994                RequireCompleteType(FD->getLocation(), FD->getType(),
13995                                    diag::err_field_incomplete)) {
13996       // Incomplete type
13997       FD->setInvalidDecl();
13998       EnclosingDecl->setInvalidDecl();
13999       continue;
14000     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14001       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14002         // A type which contains a flexible array member is considered to be a
14003         // flexible array member.
14004         Record->setHasFlexibleArrayMember(true);
14005         if (!Record->isUnion()) {
14006           // If this is a struct/class and this is not the last element, reject
14007           // it.  Note that GCC supports variable sized arrays in the middle of
14008           // structures.
14009           if (i + 1 != Fields.end())
14010             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14011               << FD->getDeclName() << FD->getType();
14012           else {
14013             // We support flexible arrays at the end of structs in
14014             // other structs as an extension.
14015             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14016               << FD->getDeclName();
14017           }
14018         }
14019       }
14020       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14021           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14022                                  diag::err_abstract_type_in_decl,
14023                                  AbstractIvarType)) {
14024         // Ivars can not have abstract class types
14025         FD->setInvalidDecl();
14026       }
14027       if (Record && FDTTy->getDecl()->hasObjectMember())
14028         Record->setHasObjectMember(true);
14029       if (Record && FDTTy->getDecl()->hasVolatileMember())
14030         Record->setHasVolatileMember(true);
14031     } else if (FDTy->isObjCObjectType()) {
14032       /// A field cannot be an Objective-c object
14033       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14034         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14035       QualType T = Context.getObjCObjectPointerType(FD->getType());
14036       FD->setType(T);
14037     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14038                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14039       // It's an error in ARC if a field has lifetime.
14040       // We don't want to report this in a system header, though,
14041       // so we just make the field unavailable.
14042       // FIXME: that's really not sufficient; we need to make the type
14043       // itself invalid to, say, initialize or copy.
14044       QualType T = FD->getType();
14045       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14046       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14047         SourceLocation loc = FD->getLocation();
14048         if (getSourceManager().isInSystemHeader(loc)) {
14049           if (!FD->hasAttr<UnavailableAttr>()) {
14050             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14051                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14052           }
14053         } else {
14054           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14055             << T->isBlockPointerType() << Record->getTagKind();
14056         }
14057         ARCErrReported = true;
14058       }
14059     } else if (getLangOpts().ObjC1 &&
14060                getLangOpts().getGC() != LangOptions::NonGC &&
14061                Record && !Record->hasObjectMember()) {
14062       if (FD->getType()->isObjCObjectPointerType() ||
14063           FD->getType().isObjCGCStrong())
14064         Record->setHasObjectMember(true);
14065       else if (Context.getAsArrayType(FD->getType())) {
14066         QualType BaseType = Context.getBaseElementType(FD->getType());
14067         if (BaseType->isRecordType() &&
14068             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14069           Record->setHasObjectMember(true);
14070         else if (BaseType->isObjCObjectPointerType() ||
14071                  BaseType.isObjCGCStrong())
14072                Record->setHasObjectMember(true);
14073       }
14074     }
14075     if (Record && FD->getType().isVolatileQualified())
14076       Record->setHasVolatileMember(true);
14077     // Keep track of the number of named members.
14078     if (FD->getIdentifier())
14079       ++NumNamedMembers;
14080   }
14081 
14082   // Okay, we successfully defined 'Record'.
14083   if (Record) {
14084     bool Completed = false;
14085     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14086       if (!CXXRecord->isInvalidDecl()) {
14087         // Set access bits correctly on the directly-declared conversions.
14088         for (CXXRecordDecl::conversion_iterator
14089                I = CXXRecord->conversion_begin(),
14090                E = CXXRecord->conversion_end(); I != E; ++I)
14091           I.setAccess((*I)->getAccess());
14092       }
14093 
14094       if (!CXXRecord->isDependentType()) {
14095         if (CXXRecord->hasUserDeclaredDestructor()) {
14096           // Adjust user-defined destructor exception spec.
14097           if (getLangOpts().CPlusPlus11)
14098             AdjustDestructorExceptionSpec(CXXRecord,
14099                                           CXXRecord->getDestructor());
14100         }
14101 
14102         if (!CXXRecord->isInvalidDecl()) {
14103           // Add any implicitly-declared members to this class.
14104           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14105 
14106           // If we have virtual base classes, we may end up finding multiple
14107           // final overriders for a given virtual function. Check for this
14108           // problem now.
14109           if (CXXRecord->getNumVBases()) {
14110             CXXFinalOverriderMap FinalOverriders;
14111             CXXRecord->getFinalOverriders(FinalOverriders);
14112 
14113             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14114                                              MEnd = FinalOverriders.end();
14115                  M != MEnd; ++M) {
14116               for (OverridingMethods::iterator SO = M->second.begin(),
14117                                             SOEnd = M->second.end();
14118                    SO != SOEnd; ++SO) {
14119                 assert(SO->second.size() > 0 &&
14120                        "Virtual function without overridding functions?");
14121                 if (SO->second.size() == 1)
14122                   continue;
14123 
14124                 // C++ [class.virtual]p2:
14125                 //   In a derived class, if a virtual member function of a base
14126                 //   class subobject has more than one final overrider the
14127                 //   program is ill-formed.
14128                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14129                   << (const NamedDecl *)M->first << Record;
14130                 Diag(M->first->getLocation(),
14131                      diag::note_overridden_virtual_function);
14132                 for (OverridingMethods::overriding_iterator
14133                           OM = SO->second.begin(),
14134                        OMEnd = SO->second.end();
14135                      OM != OMEnd; ++OM)
14136                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14137                     << (const NamedDecl *)M->first << OM->Method->getParent();
14138 
14139                 Record->setInvalidDecl();
14140               }
14141             }
14142             CXXRecord->completeDefinition(&FinalOverriders);
14143             Completed = true;
14144           }
14145         }
14146       }
14147     }
14148 
14149     if (!Completed)
14150       Record->completeDefinition();
14151 
14152     if (Record->hasAttrs()) {
14153       CheckAlignasUnderalignment(Record);
14154 
14155       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14156         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14157                                            IA->getRange(), IA->getBestCase(),
14158                                            IA->getSemanticSpelling());
14159     }
14160 
14161     // Check if the structure/union declaration is a type that can have zero
14162     // size in C. For C this is a language extension, for C++ it may cause
14163     // compatibility problems.
14164     bool CheckForZeroSize;
14165     if (!getLangOpts().CPlusPlus) {
14166       CheckForZeroSize = true;
14167     } else {
14168       // For C++ filter out types that cannot be referenced in C code.
14169       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14170       CheckForZeroSize =
14171           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14172           !CXXRecord->isDependentType() &&
14173           CXXRecord->isCLike();
14174     }
14175     if (CheckForZeroSize) {
14176       bool ZeroSize = true;
14177       bool IsEmpty = true;
14178       unsigned NonBitFields = 0;
14179       for (RecordDecl::field_iterator I = Record->field_begin(),
14180                                       E = Record->field_end();
14181            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14182         IsEmpty = false;
14183         if (I->isUnnamedBitfield()) {
14184           if (I->getBitWidthValue(Context) > 0)
14185             ZeroSize = false;
14186         } else {
14187           ++NonBitFields;
14188           QualType FieldType = I->getType();
14189           if (FieldType->isIncompleteType() ||
14190               !Context.getTypeSizeInChars(FieldType).isZero())
14191             ZeroSize = false;
14192         }
14193       }
14194 
14195       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14196       // allowed in C++, but warn if its declaration is inside
14197       // extern "C" block.
14198       if (ZeroSize) {
14199         Diag(RecLoc, getLangOpts().CPlusPlus ?
14200                          diag::warn_zero_size_struct_union_in_extern_c :
14201                          diag::warn_zero_size_struct_union_compat)
14202           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14203       }
14204 
14205       // Structs without named members are extension in C (C99 6.7.2.1p7),
14206       // but are accepted by GCC.
14207       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14208         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14209                                diag::ext_no_named_members_in_struct_union)
14210           << Record->isUnion();
14211       }
14212     }
14213   } else {
14214     ObjCIvarDecl **ClsFields =
14215       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14216     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14217       ID->setEndOfDefinitionLoc(RBrac);
14218       // Add ivar's to class's DeclContext.
14219       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14220         ClsFields[i]->setLexicalDeclContext(ID);
14221         ID->addDecl(ClsFields[i]);
14222       }
14223       // Must enforce the rule that ivars in the base classes may not be
14224       // duplicates.
14225       if (ID->getSuperClass())
14226         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14227     } else if (ObjCImplementationDecl *IMPDecl =
14228                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14229       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14230       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14231         // Ivar declared in @implementation never belongs to the implementation.
14232         // Only it is in implementation's lexical context.
14233         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14234       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14235       IMPDecl->setIvarLBraceLoc(LBrac);
14236       IMPDecl->setIvarRBraceLoc(RBrac);
14237     } else if (ObjCCategoryDecl *CDecl =
14238                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14239       // case of ivars in class extension; all other cases have been
14240       // reported as errors elsewhere.
14241       // FIXME. Class extension does not have a LocEnd field.
14242       // CDecl->setLocEnd(RBrac);
14243       // Add ivar's to class extension's DeclContext.
14244       // Diagnose redeclaration of private ivars.
14245       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14246       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14247         if (IDecl) {
14248           if (const ObjCIvarDecl *ClsIvar =
14249               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14250             Diag(ClsFields[i]->getLocation(),
14251                  diag::err_duplicate_ivar_declaration);
14252             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14253             continue;
14254           }
14255           for (const auto *Ext : IDecl->known_extensions()) {
14256             if (const ObjCIvarDecl *ClsExtIvar
14257                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14258               Diag(ClsFields[i]->getLocation(),
14259                    diag::err_duplicate_ivar_declaration);
14260               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14261               continue;
14262             }
14263           }
14264         }
14265         ClsFields[i]->setLexicalDeclContext(CDecl);
14266         CDecl->addDecl(ClsFields[i]);
14267       }
14268       CDecl->setIvarLBraceLoc(LBrac);
14269       CDecl->setIvarRBraceLoc(RBrac);
14270     }
14271   }
14272 
14273   if (Attr)
14274     ProcessDeclAttributeList(S, Record, Attr);
14275 }
14276 
14277 /// \brief Determine whether the given integral value is representable within
14278 /// the given type T.
14279 static bool isRepresentableIntegerValue(ASTContext &Context,
14280                                         llvm::APSInt &Value,
14281                                         QualType T) {
14282   assert(T->isIntegralType(Context) && "Integral type required!");
14283   unsigned BitWidth = Context.getIntWidth(T);
14284 
14285   if (Value.isUnsigned() || Value.isNonNegative()) {
14286     if (T->isSignedIntegerOrEnumerationType())
14287       --BitWidth;
14288     return Value.getActiveBits() <= BitWidth;
14289   }
14290   return Value.getMinSignedBits() <= BitWidth;
14291 }
14292 
14293 // \brief Given an integral type, return the next larger integral type
14294 // (or a NULL type of no such type exists).
14295 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14296   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14297   // enum checking below.
14298   assert(T->isIntegralType(Context) && "Integral type required!");
14299   const unsigned NumTypes = 4;
14300   QualType SignedIntegralTypes[NumTypes] = {
14301     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14302   };
14303   QualType UnsignedIntegralTypes[NumTypes] = {
14304     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14305     Context.UnsignedLongLongTy
14306   };
14307 
14308   unsigned BitWidth = Context.getTypeSize(T);
14309   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14310                                                         : UnsignedIntegralTypes;
14311   for (unsigned I = 0; I != NumTypes; ++I)
14312     if (Context.getTypeSize(Types[I]) > BitWidth)
14313       return Types[I];
14314 
14315   return QualType();
14316 }
14317 
14318 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14319                                           EnumConstantDecl *LastEnumConst,
14320                                           SourceLocation IdLoc,
14321                                           IdentifierInfo *Id,
14322                                           Expr *Val) {
14323   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14324   llvm::APSInt EnumVal(IntWidth);
14325   QualType EltTy;
14326 
14327   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14328     Val = nullptr;
14329 
14330   if (Val)
14331     Val = DefaultLvalueConversion(Val).get();
14332 
14333   if (Val) {
14334     if (Enum->isDependentType() || Val->isTypeDependent())
14335       EltTy = Context.DependentTy;
14336     else {
14337       SourceLocation ExpLoc;
14338       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14339           !getLangOpts().MSVCCompat) {
14340         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14341         // constant-expression in the enumerator-definition shall be a converted
14342         // constant expression of the underlying type.
14343         EltTy = Enum->getIntegerType();
14344         ExprResult Converted =
14345           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14346                                            CCEK_Enumerator);
14347         if (Converted.isInvalid())
14348           Val = nullptr;
14349         else
14350           Val = Converted.get();
14351       } else if (!Val->isValueDependent() &&
14352                  !(Val = VerifyIntegerConstantExpression(Val,
14353                                                          &EnumVal).get())) {
14354         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14355       } else {
14356         if (Enum->isFixed()) {
14357           EltTy = Enum->getIntegerType();
14358 
14359           // In Obj-C and Microsoft mode, require the enumeration value to be
14360           // representable in the underlying type of the enumeration. In C++11,
14361           // we perform a non-narrowing conversion as part of converted constant
14362           // expression checking.
14363           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14364             if (getLangOpts().MSVCCompat) {
14365               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14366               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14367             } else
14368               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14369           } else
14370             Val = ImpCastExprToType(Val, EltTy,
14371                                     EltTy->isBooleanType() ?
14372                                     CK_IntegralToBoolean : CK_IntegralCast)
14373                     .get();
14374         } else if (getLangOpts().CPlusPlus) {
14375           // C++11 [dcl.enum]p5:
14376           //   If the underlying type is not fixed, the type of each enumerator
14377           //   is the type of its initializing value:
14378           //     - If an initializer is specified for an enumerator, the
14379           //       initializing value has the same type as the expression.
14380           EltTy = Val->getType();
14381         } else {
14382           // C99 6.7.2.2p2:
14383           //   The expression that defines the value of an enumeration constant
14384           //   shall be an integer constant expression that has a value
14385           //   representable as an int.
14386 
14387           // Complain if the value is not representable in an int.
14388           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14389             Diag(IdLoc, diag::ext_enum_value_not_int)
14390               << EnumVal.toString(10) << Val->getSourceRange()
14391               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14392           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14393             // Force the type of the expression to 'int'.
14394             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14395           }
14396           EltTy = Val->getType();
14397         }
14398       }
14399     }
14400   }
14401 
14402   if (!Val) {
14403     if (Enum->isDependentType())
14404       EltTy = Context.DependentTy;
14405     else if (!LastEnumConst) {
14406       // C++0x [dcl.enum]p5:
14407       //   If the underlying type is not fixed, the type of each enumerator
14408       //   is the type of its initializing value:
14409       //     - If no initializer is specified for the first enumerator, the
14410       //       initializing value has an unspecified integral type.
14411       //
14412       // GCC uses 'int' for its unspecified integral type, as does
14413       // C99 6.7.2.2p3.
14414       if (Enum->isFixed()) {
14415         EltTy = Enum->getIntegerType();
14416       }
14417       else {
14418         EltTy = Context.IntTy;
14419       }
14420     } else {
14421       // Assign the last value + 1.
14422       EnumVal = LastEnumConst->getInitVal();
14423       ++EnumVal;
14424       EltTy = LastEnumConst->getType();
14425 
14426       // Check for overflow on increment.
14427       if (EnumVal < LastEnumConst->getInitVal()) {
14428         // C++0x [dcl.enum]p5:
14429         //   If the underlying type is not fixed, the type of each enumerator
14430         //   is the type of its initializing value:
14431         //
14432         //     - Otherwise the type of the initializing value is the same as
14433         //       the type of the initializing value of the preceding enumerator
14434         //       unless the incremented value is not representable in that type,
14435         //       in which case the type is an unspecified integral type
14436         //       sufficient to contain the incremented value. If no such type
14437         //       exists, the program is ill-formed.
14438         QualType T = getNextLargerIntegralType(Context, EltTy);
14439         if (T.isNull() || Enum->isFixed()) {
14440           // There is no integral type larger enough to represent this
14441           // value. Complain, then allow the value to wrap around.
14442           EnumVal = LastEnumConst->getInitVal();
14443           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14444           ++EnumVal;
14445           if (Enum->isFixed())
14446             // When the underlying type is fixed, this is ill-formed.
14447             Diag(IdLoc, diag::err_enumerator_wrapped)
14448               << EnumVal.toString(10)
14449               << EltTy;
14450           else
14451             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14452               << EnumVal.toString(10);
14453         } else {
14454           EltTy = T;
14455         }
14456 
14457         // Retrieve the last enumerator's value, extent that type to the
14458         // type that is supposed to be large enough to represent the incremented
14459         // value, then increment.
14460         EnumVal = LastEnumConst->getInitVal();
14461         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14462         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14463         ++EnumVal;
14464 
14465         // If we're not in C++, diagnose the overflow of enumerator values,
14466         // which in C99 means that the enumerator value is not representable in
14467         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14468         // permits enumerator values that are representable in some larger
14469         // integral type.
14470         if (!getLangOpts().CPlusPlus && !T.isNull())
14471           Diag(IdLoc, diag::warn_enum_value_overflow);
14472       } else if (!getLangOpts().CPlusPlus &&
14473                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14474         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14475         Diag(IdLoc, diag::ext_enum_value_not_int)
14476           << EnumVal.toString(10) << 1;
14477       }
14478     }
14479   }
14480 
14481   if (!EltTy->isDependentType()) {
14482     // Make the enumerator value match the signedness and size of the
14483     // enumerator's type.
14484     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14485     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14486   }
14487 
14488   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14489                                   Val, EnumVal);
14490 }
14491 
14492 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14493                                                 SourceLocation IILoc) {
14494   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14495       !getLangOpts().CPlusPlus)
14496     return SkipBodyInfo();
14497 
14498   // We have an anonymous enum definition. Look up the first enumerator to
14499   // determine if we should merge the definition with an existing one and
14500   // skip the body.
14501   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14502                                          ForRedeclaration);
14503   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14504   if (!PrevECD)
14505     return SkipBodyInfo();
14506 
14507   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14508   NamedDecl *Hidden;
14509   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14510     SkipBodyInfo Skip;
14511     Skip.Previous = Hidden;
14512     return Skip;
14513   }
14514 
14515   return SkipBodyInfo();
14516 }
14517 
14518 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14519                               SourceLocation IdLoc, IdentifierInfo *Id,
14520                               AttributeList *Attr,
14521                               SourceLocation EqualLoc, Expr *Val) {
14522   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14523   EnumConstantDecl *LastEnumConst =
14524     cast_or_null<EnumConstantDecl>(lastEnumConst);
14525 
14526   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14527   // we find one that is.
14528   S = getNonFieldDeclScope(S);
14529 
14530   // Verify that there isn't already something declared with this name in this
14531   // scope.
14532   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14533                                          ForRedeclaration);
14534   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14535     // Maybe we will complain about the shadowed template parameter.
14536     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14537     // Just pretend that we didn't see the previous declaration.
14538     PrevDecl = nullptr;
14539   }
14540 
14541   // C++ [class.mem]p15:
14542   // If T is the name of a class, then each of the following shall have a name
14543   // different from T:
14544   // - every enumerator of every member of class T that is an unscoped
14545   // enumerated type
14546   if (!TheEnumDecl->isScoped())
14547     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14548                             DeclarationNameInfo(Id, IdLoc));
14549 
14550   EnumConstantDecl *New =
14551     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14552   if (!New)
14553     return nullptr;
14554 
14555   if (PrevDecl) {
14556     // When in C++, we may get a TagDecl with the same name; in this case the
14557     // enum constant will 'hide' the tag.
14558     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14559            "Received TagDecl when not in C++!");
14560     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14561         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14562       if (isa<EnumConstantDecl>(PrevDecl))
14563         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14564       else
14565         Diag(IdLoc, diag::err_redefinition) << Id;
14566       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14567       return nullptr;
14568     }
14569   }
14570 
14571   // Process attributes.
14572   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14573 
14574   // Register this decl in the current scope stack.
14575   New->setAccess(TheEnumDecl->getAccess());
14576   PushOnScopeChains(New, S);
14577 
14578   ActOnDocumentableDecl(New);
14579 
14580   return New;
14581 }
14582 
14583 // Returns true when the enum initial expression does not trigger the
14584 // duplicate enum warning.  A few common cases are exempted as follows:
14585 // Element2 = Element1
14586 // Element2 = Element1 + 1
14587 // Element2 = Element1 - 1
14588 // Where Element2 and Element1 are from the same enum.
14589 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14590   Expr *InitExpr = ECD->getInitExpr();
14591   if (!InitExpr)
14592     return true;
14593   InitExpr = InitExpr->IgnoreImpCasts();
14594 
14595   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14596     if (!BO->isAdditiveOp())
14597       return true;
14598     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14599     if (!IL)
14600       return true;
14601     if (IL->getValue() != 1)
14602       return true;
14603 
14604     InitExpr = BO->getLHS();
14605   }
14606 
14607   // This checks if the elements are from the same enum.
14608   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14609   if (!DRE)
14610     return true;
14611 
14612   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14613   if (!EnumConstant)
14614     return true;
14615 
14616   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14617       Enum)
14618     return true;
14619 
14620   return false;
14621 }
14622 
14623 namespace {
14624 struct DupKey {
14625   int64_t val;
14626   bool isTombstoneOrEmptyKey;
14627   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14628     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14629 };
14630 
14631 static DupKey GetDupKey(const llvm::APSInt& Val) {
14632   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14633                 false);
14634 }
14635 
14636 struct DenseMapInfoDupKey {
14637   static DupKey getEmptyKey() { return DupKey(0, true); }
14638   static DupKey getTombstoneKey() { return DupKey(1, true); }
14639   static unsigned getHashValue(const DupKey Key) {
14640     return (unsigned)(Key.val * 37);
14641   }
14642   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14643     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14644            LHS.val == RHS.val;
14645   }
14646 };
14647 } // end anonymous namespace
14648 
14649 // Emits a warning when an element is implicitly set a value that
14650 // a previous element has already been set to.
14651 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14652                                         EnumDecl *Enum,
14653                                         QualType EnumType) {
14654   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14655     return;
14656   // Avoid anonymous enums
14657   if (!Enum->getIdentifier())
14658     return;
14659 
14660   // Only check for small enums.
14661   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14662     return;
14663 
14664   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14665   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14666 
14667   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14668   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14669           ValueToVectorMap;
14670 
14671   DuplicatesVector DupVector;
14672   ValueToVectorMap EnumMap;
14673 
14674   // Populate the EnumMap with all values represented by enum constants without
14675   // an initialier.
14676   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14677     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14678 
14679     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14680     // this constant.  Skip this enum since it may be ill-formed.
14681     if (!ECD) {
14682       return;
14683     }
14684 
14685     if (ECD->getInitExpr())
14686       continue;
14687 
14688     DupKey Key = GetDupKey(ECD->getInitVal());
14689     DeclOrVector &Entry = EnumMap[Key];
14690 
14691     // First time encountering this value.
14692     if (Entry.isNull())
14693       Entry = ECD;
14694   }
14695 
14696   // Create vectors for any values that has duplicates.
14697   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14698     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14699     if (!ValidDuplicateEnum(ECD, Enum))
14700       continue;
14701 
14702     DupKey Key = GetDupKey(ECD->getInitVal());
14703 
14704     DeclOrVector& Entry = EnumMap[Key];
14705     if (Entry.isNull())
14706       continue;
14707 
14708     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14709       // Ensure constants are different.
14710       if (D == ECD)
14711         continue;
14712 
14713       // Create new vector and push values onto it.
14714       ECDVector *Vec = new ECDVector();
14715       Vec->push_back(D);
14716       Vec->push_back(ECD);
14717 
14718       // Update entry to point to the duplicates vector.
14719       Entry = Vec;
14720 
14721       // Store the vector somewhere we can consult later for quick emission of
14722       // diagnostics.
14723       DupVector.push_back(Vec);
14724       continue;
14725     }
14726 
14727     ECDVector *Vec = Entry.get<ECDVector*>();
14728     // Make sure constants are not added more than once.
14729     if (*Vec->begin() == ECD)
14730       continue;
14731 
14732     Vec->push_back(ECD);
14733   }
14734 
14735   // Emit diagnostics.
14736   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14737                                   DupVectorEnd = DupVector.end();
14738        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14739     ECDVector *Vec = *DupVectorIter;
14740     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14741 
14742     // Emit warning for one enum constant.
14743     ECDVector::iterator I = Vec->begin();
14744     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14745       << (*I)->getName() << (*I)->getInitVal().toString(10)
14746       << (*I)->getSourceRange();
14747     ++I;
14748 
14749     // Emit one note for each of the remaining enum constants with
14750     // the same value.
14751     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14752       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14753         << (*I)->getName() << (*I)->getInitVal().toString(10)
14754         << (*I)->getSourceRange();
14755     delete Vec;
14756   }
14757 }
14758 
14759 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14760                              bool AllowMask) const {
14761   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14762   assert(ED->isCompleteDefinition() && "expected enum definition");
14763 
14764   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14765   llvm::APInt &FlagBits = R.first->second;
14766 
14767   if (R.second) {
14768     for (auto *E : ED->enumerators()) {
14769       const auto &EVal = E->getInitVal();
14770       // Only single-bit enumerators introduce new flag values.
14771       if (EVal.isPowerOf2())
14772         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14773     }
14774   }
14775 
14776   // A value is in a flag enum if either its bits are a subset of the enum's
14777   // flag bits (the first condition) or we are allowing masks and the same is
14778   // true of its complement (the second condition). When masks are allowed, we
14779   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14780   //
14781   // While it's true that any value could be used as a mask, the assumption is
14782   // that a mask will have all of the insignificant bits set. Anything else is
14783   // likely a logic error.
14784   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14785   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14786 }
14787 
14788 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14789                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14790                          ArrayRef<Decl *> Elements,
14791                          Scope *S, AttributeList *Attr) {
14792   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14793   QualType EnumType = Context.getTypeDeclType(Enum);
14794 
14795   if (Attr)
14796     ProcessDeclAttributeList(S, Enum, Attr);
14797 
14798   if (Enum->isDependentType()) {
14799     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14800       EnumConstantDecl *ECD =
14801         cast_or_null<EnumConstantDecl>(Elements[i]);
14802       if (!ECD) continue;
14803 
14804       ECD->setType(EnumType);
14805     }
14806 
14807     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14808     return;
14809   }
14810 
14811   // TODO: If the result value doesn't fit in an int, it must be a long or long
14812   // long value.  ISO C does not support this, but GCC does as an extension,
14813   // emit a warning.
14814   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14815   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14816   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14817 
14818   // Verify that all the values are okay, compute the size of the values, and
14819   // reverse the list.
14820   unsigned NumNegativeBits = 0;
14821   unsigned NumPositiveBits = 0;
14822 
14823   // Keep track of whether all elements have type int.
14824   bool AllElementsInt = true;
14825 
14826   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14827     EnumConstantDecl *ECD =
14828       cast_or_null<EnumConstantDecl>(Elements[i]);
14829     if (!ECD) continue;  // Already issued a diagnostic.
14830 
14831     const llvm::APSInt &InitVal = ECD->getInitVal();
14832 
14833     // Keep track of the size of positive and negative values.
14834     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14835       NumPositiveBits = std::max(NumPositiveBits,
14836                                  (unsigned)InitVal.getActiveBits());
14837     else
14838       NumNegativeBits = std::max(NumNegativeBits,
14839                                  (unsigned)InitVal.getMinSignedBits());
14840 
14841     // Keep track of whether every enum element has type int (very commmon).
14842     if (AllElementsInt)
14843       AllElementsInt = ECD->getType() == Context.IntTy;
14844   }
14845 
14846   // Figure out the type that should be used for this enum.
14847   QualType BestType;
14848   unsigned BestWidth;
14849 
14850   // C++0x N3000 [conv.prom]p3:
14851   //   An rvalue of an unscoped enumeration type whose underlying
14852   //   type is not fixed can be converted to an rvalue of the first
14853   //   of the following types that can represent all the values of
14854   //   the enumeration: int, unsigned int, long int, unsigned long
14855   //   int, long long int, or unsigned long long int.
14856   // C99 6.4.4.3p2:
14857   //   An identifier declared as an enumeration constant has type int.
14858   // The C99 rule is modified by a gcc extension
14859   QualType BestPromotionType;
14860 
14861   bool Packed = Enum->hasAttr<PackedAttr>();
14862   // -fshort-enums is the equivalent to specifying the packed attribute on all
14863   // enum definitions.
14864   if (LangOpts.ShortEnums)
14865     Packed = true;
14866 
14867   if (Enum->isFixed()) {
14868     BestType = Enum->getIntegerType();
14869     if (BestType->isPromotableIntegerType())
14870       BestPromotionType = Context.getPromotedIntegerType(BestType);
14871     else
14872       BestPromotionType = BestType;
14873 
14874     BestWidth = Context.getIntWidth(BestType);
14875   }
14876   else if (NumNegativeBits) {
14877     // If there is a negative value, figure out the smallest integer type (of
14878     // int/long/longlong) that fits.
14879     // If it's packed, check also if it fits a char or a short.
14880     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14881       BestType = Context.SignedCharTy;
14882       BestWidth = CharWidth;
14883     } else if (Packed && NumNegativeBits <= ShortWidth &&
14884                NumPositiveBits < ShortWidth) {
14885       BestType = Context.ShortTy;
14886       BestWidth = ShortWidth;
14887     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14888       BestType = Context.IntTy;
14889       BestWidth = IntWidth;
14890     } else {
14891       BestWidth = Context.getTargetInfo().getLongWidth();
14892 
14893       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14894         BestType = Context.LongTy;
14895       } else {
14896         BestWidth = Context.getTargetInfo().getLongLongWidth();
14897 
14898         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14899           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14900         BestType = Context.LongLongTy;
14901       }
14902     }
14903     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14904   } else {
14905     // If there is no negative value, figure out the smallest type that fits
14906     // all of the enumerator values.
14907     // If it's packed, check also if it fits a char or a short.
14908     if (Packed && NumPositiveBits <= CharWidth) {
14909       BestType = Context.UnsignedCharTy;
14910       BestPromotionType = Context.IntTy;
14911       BestWidth = CharWidth;
14912     } else if (Packed && NumPositiveBits <= ShortWidth) {
14913       BestType = Context.UnsignedShortTy;
14914       BestPromotionType = Context.IntTy;
14915       BestWidth = ShortWidth;
14916     } else if (NumPositiveBits <= IntWidth) {
14917       BestType = Context.UnsignedIntTy;
14918       BestWidth = IntWidth;
14919       BestPromotionType
14920         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14921                            ? Context.UnsignedIntTy : Context.IntTy;
14922     } else if (NumPositiveBits <=
14923                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14924       BestType = Context.UnsignedLongTy;
14925       BestPromotionType
14926         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14927                            ? Context.UnsignedLongTy : Context.LongTy;
14928     } else {
14929       BestWidth = Context.getTargetInfo().getLongLongWidth();
14930       assert(NumPositiveBits <= BestWidth &&
14931              "How could an initializer get larger than ULL?");
14932       BestType = Context.UnsignedLongLongTy;
14933       BestPromotionType
14934         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14935                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14936     }
14937   }
14938 
14939   // Loop over all of the enumerator constants, changing their types to match
14940   // the type of the enum if needed.
14941   for (auto *D : Elements) {
14942     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14943     if (!ECD) continue;  // Already issued a diagnostic.
14944 
14945     // Standard C says the enumerators have int type, but we allow, as an
14946     // extension, the enumerators to be larger than int size.  If each
14947     // enumerator value fits in an int, type it as an int, otherwise type it the
14948     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14949     // that X has type 'int', not 'unsigned'.
14950 
14951     // Determine whether the value fits into an int.
14952     llvm::APSInt InitVal = ECD->getInitVal();
14953 
14954     // If it fits into an integer type, force it.  Otherwise force it to match
14955     // the enum decl type.
14956     QualType NewTy;
14957     unsigned NewWidth;
14958     bool NewSign;
14959     if (!getLangOpts().CPlusPlus &&
14960         !Enum->isFixed() &&
14961         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14962       NewTy = Context.IntTy;
14963       NewWidth = IntWidth;
14964       NewSign = true;
14965     } else if (ECD->getType() == BestType) {
14966       // Already the right type!
14967       if (getLangOpts().CPlusPlus)
14968         // C++ [dcl.enum]p4: Following the closing brace of an
14969         // enum-specifier, each enumerator has the type of its
14970         // enumeration.
14971         ECD->setType(EnumType);
14972       continue;
14973     } else {
14974       NewTy = BestType;
14975       NewWidth = BestWidth;
14976       NewSign = BestType->isSignedIntegerOrEnumerationType();
14977     }
14978 
14979     // Adjust the APSInt value.
14980     InitVal = InitVal.extOrTrunc(NewWidth);
14981     InitVal.setIsSigned(NewSign);
14982     ECD->setInitVal(InitVal);
14983 
14984     // Adjust the Expr initializer and type.
14985     if (ECD->getInitExpr() &&
14986         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14987       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14988                                                 CK_IntegralCast,
14989                                                 ECD->getInitExpr(),
14990                                                 /*base paths*/ nullptr,
14991                                                 VK_RValue));
14992     if (getLangOpts().CPlusPlus)
14993       // C++ [dcl.enum]p4: Following the closing brace of an
14994       // enum-specifier, each enumerator has the type of its
14995       // enumeration.
14996       ECD->setType(EnumType);
14997     else
14998       ECD->setType(NewTy);
14999   }
15000 
15001   Enum->completeDefinition(BestType, BestPromotionType,
15002                            NumPositiveBits, NumNegativeBits);
15003 
15004   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15005 
15006   if (Enum->hasAttr<FlagEnumAttr>()) {
15007     for (Decl *D : Elements) {
15008       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15009       if (!ECD) continue;  // Already issued a diagnostic.
15010 
15011       llvm::APSInt InitVal = ECD->getInitVal();
15012       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15013           !IsValueInFlagEnum(Enum, InitVal, true))
15014         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15015           << ECD << Enum;
15016     }
15017   }
15018 
15019   // Now that the enum type is defined, ensure it's not been underaligned.
15020   if (Enum->hasAttrs())
15021     CheckAlignasUnderalignment(Enum);
15022 }
15023 
15024 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15025                                   SourceLocation StartLoc,
15026                                   SourceLocation EndLoc) {
15027   StringLiteral *AsmString = cast<StringLiteral>(expr);
15028 
15029   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15030                                                    AsmString, StartLoc,
15031                                                    EndLoc);
15032   CurContext->addDecl(New);
15033   return New;
15034 }
15035 
15036 static void checkModuleImportContext(Sema &S, Module *M,
15037                                      SourceLocation ImportLoc, DeclContext *DC,
15038                                      bool FromInclude = false) {
15039   SourceLocation ExternCLoc;
15040 
15041   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15042     switch (LSD->getLanguage()) {
15043     case LinkageSpecDecl::lang_c:
15044       if (ExternCLoc.isInvalid())
15045         ExternCLoc = LSD->getLocStart();
15046       break;
15047     case LinkageSpecDecl::lang_cxx:
15048       break;
15049     }
15050     DC = LSD->getParent();
15051   }
15052 
15053   while (isa<LinkageSpecDecl>(DC))
15054     DC = DC->getParent();
15055 
15056   if (!isa<TranslationUnitDecl>(DC)) {
15057     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15058                           ? diag::ext_module_import_not_at_top_level_noop
15059                           : diag::err_module_import_not_at_top_level_fatal)
15060         << M->getFullModuleName() << DC;
15061     S.Diag(cast<Decl>(DC)->getLocStart(),
15062            diag::note_module_import_not_at_top_level) << DC;
15063   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15064     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15065       << M->getFullModuleName();
15066     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15067   }
15068 }
15069 
15070 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15071   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15072 }
15073 
15074 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
15075                                    SourceLocation ImportLoc,
15076                                    ModuleIdPath Path) {
15077   Module *Mod =
15078       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15079                                    /*IsIncludeDirective=*/false);
15080   if (!Mod)
15081     return true;
15082 
15083   VisibleModules.setVisible(Mod, ImportLoc);
15084 
15085   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15086 
15087   // FIXME: we should support importing a submodule within a different submodule
15088   // of the same top-level module. Until we do, make it an error rather than
15089   // silently ignoring the import.
15090   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
15091     Diag(ImportLoc, getLangOpts().CompilingModule
15092                         ? diag::err_module_self_import
15093                         : diag::err_module_import_in_implementation)
15094         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15095 
15096   SmallVector<SourceLocation, 2> IdentifierLocs;
15097   Module *ModCheck = Mod;
15098   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15099     // If we've run out of module parents, just drop the remaining identifiers.
15100     // We need the length to be consistent.
15101     if (!ModCheck)
15102       break;
15103     ModCheck = ModCheck->Parent;
15104 
15105     IdentifierLocs.push_back(Path[I].second);
15106   }
15107 
15108   ImportDecl *Import = ImportDecl::Create(Context,
15109                                           Context.getTranslationUnitDecl(),
15110                                           AtLoc.isValid()? AtLoc : ImportLoc,
15111                                           Mod, IdentifierLocs);
15112   Context.getTranslationUnitDecl()->addDecl(Import);
15113   return Import;
15114 }
15115 
15116 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15117   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15118 
15119   // Determine whether we're in the #include buffer for a module. The #includes
15120   // in that buffer do not qualify as module imports; they're just an
15121   // implementation detail of us building the module.
15122   //
15123   // FIXME: Should we even get ActOnModuleInclude calls for those?
15124   bool IsInModuleIncludes =
15125       TUKind == TU_Module &&
15126       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15127 
15128   // Similarly, if we're in the implementation of a module, don't
15129   // synthesize an illegal module import. FIXME: Why not?
15130   bool ShouldAddImport =
15131       !IsInModuleIncludes &&
15132       (getLangOpts().CompilingModule ||
15133        getLangOpts().CurrentModule.empty() ||
15134        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15135 
15136   // If this module import was due to an inclusion directive, create an
15137   // implicit import declaration to capture it in the AST.
15138   if (ShouldAddImport) {
15139     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15140     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15141                                                      DirectiveLoc, Mod,
15142                                                      DirectiveLoc);
15143     TU->addDecl(ImportD);
15144     Consumer.HandleImplicitImportDecl(ImportD);
15145   }
15146 
15147   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15148   VisibleModules.setVisible(Mod, DirectiveLoc);
15149 }
15150 
15151 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15152   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15153 
15154   if (getLangOpts().ModulesLocalVisibility)
15155     VisibleModulesStack.push_back(std::move(VisibleModules));
15156   VisibleModules.setVisible(Mod, DirectiveLoc);
15157 }
15158 
15159 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15160   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15161 
15162   if (getLangOpts().ModulesLocalVisibility) {
15163     VisibleModules = std::move(VisibleModulesStack.back());
15164     VisibleModulesStack.pop_back();
15165     VisibleModules.setVisible(Mod, DirectiveLoc);
15166     // Leaving a module hides namespace names, so our visible namespace cache
15167     // is now out of date.
15168     VisibleNamespaceCache.clear();
15169   }
15170 }
15171 
15172 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15173                                                       Module *Mod) {
15174   // Bail if we're not allowed to implicitly import a module here.
15175   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15176     return;
15177 
15178   // Create the implicit import declaration.
15179   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15180   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15181                                                    Loc, Mod, Loc);
15182   TU->addDecl(ImportD);
15183   Consumer.HandleImplicitImportDecl(ImportD);
15184 
15185   // Make the module visible.
15186   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15187   VisibleModules.setVisible(Mod, Loc);
15188 }
15189 
15190 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15191                                       IdentifierInfo* AliasName,
15192                                       SourceLocation PragmaLoc,
15193                                       SourceLocation NameLoc,
15194                                       SourceLocation AliasNameLoc) {
15195   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15196                                          LookupOrdinaryName);
15197   AsmLabelAttr *Attr =
15198       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15199 
15200   // If a declaration that:
15201   // 1) declares a function or a variable
15202   // 2) has external linkage
15203   // already exists, add a label attribute to it.
15204   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15205     if (isDeclExternC(PrevDecl))
15206       PrevDecl->addAttr(Attr);
15207     else
15208       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15209           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15210   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15211   } else
15212     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15213 }
15214 
15215 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15216                              SourceLocation PragmaLoc,
15217                              SourceLocation NameLoc) {
15218   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15219 
15220   if (PrevDecl) {
15221     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15222   } else {
15223     (void)WeakUndeclaredIdentifiers.insert(
15224       std::pair<IdentifierInfo*,WeakInfo>
15225         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15226   }
15227 }
15228 
15229 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15230                                 IdentifierInfo* AliasName,
15231                                 SourceLocation PragmaLoc,
15232                                 SourceLocation NameLoc,
15233                                 SourceLocation AliasNameLoc) {
15234   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15235                                     LookupOrdinaryName);
15236   WeakInfo W = WeakInfo(Name, NameLoc);
15237 
15238   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15239     if (!PrevDecl->hasAttr<AliasAttr>())
15240       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15241         DeclApplyPragmaWeak(TUScope, ND, W);
15242   } else {
15243     (void)WeakUndeclaredIdentifiers.insert(
15244       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15245   }
15246 }
15247 
15248 Decl *Sema::getObjCDeclContext() const {
15249   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15250 }
15251 
15252 AvailabilityResult Sema::getCurContextAvailability() const {
15253   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15254   if (!D)
15255     return AR_Available;
15256 
15257   // If we are within an Objective-C method, we should consult
15258   // both the availability of the method as well as the
15259   // enclosing class.  If the class is (say) deprecated,
15260   // the entire method is considered deprecated from the
15261   // purpose of checking if the current context is deprecated.
15262   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15263     AvailabilityResult R = MD->getAvailability();
15264     if (R != AR_Available)
15265       return R;
15266     D = MD->getClassInterface();
15267   }
15268   // If we are within an Objective-c @implementation, it
15269   // gets the same availability context as the @interface.
15270   else if (const ObjCImplementationDecl *ID =
15271             dyn_cast<ObjCImplementationDecl>(D)) {
15272     D = ID->getClassInterface();
15273   }
15274   // Recover from user error.
15275   return D ? D->getAvailability() : AR_Available;
15276 }
15277